Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org.el
blob61e2fd2add378fe9e5b6ea846b09cbe0e1c134ab
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2016 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar-local org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
69 ;;;; Require other packages
71 (require 'cl-lib)
73 (eval-when-compile (require 'gnus-sum))
75 (require 'calendar)
76 (require 'find-func)
77 (require 'format-spec)
79 (or (equal this-command 'eval-buffer)
80 (condition-case nil
81 (load (concat (file-name-directory load-file-name)
82 "org-loaddefs.el")
83 nil t t t)
84 (error
85 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
86 (sit-for 3)
87 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
88 (sit-for 3))))
90 (require 'org-macs)
91 (require 'org-compat)
93 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
94 ;; some places -- e.g. see the macro `org-with-limited-levels'.
96 ;; In Org buffers, the value of `outline-regexp' is that of
97 ;; `org-outline-regexp'. The only function still directly relying on
98 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
99 ;; job when `orgstruct-mode' is active.
100 (defvar org-outline-regexp "\\*+ "
101 "Regexp to match Org headlines.")
103 (defvar org-outline-regexp-bol "^\\*+ "
104 "Regexp to match Org headlines.
105 This is similar to `org-outline-regexp' but additionally makes
106 sure that we are at the beginning of the line.")
108 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
109 "Matches a headline, putting stars and text into groups.
110 Stars are put in group 1 and the trimmed body in group 2.")
112 (declare-function calendar-check-holidays "holidays" (&optional date))
113 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
114 (declare-function org-add-archive-files "org-archive" (files))
115 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
116 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
117 (declare-function org-agenda-redo "org-agenda" (&optional all))
118 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
119 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
120 (declare-function org-beamer-mode "ox-beamer" ())
121 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
122 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
123 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
124 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
125 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
127 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
128 (declare-function org-clock-update-time-maybe "org-clock" ())
129 (declare-function org-clocktable-shift "org-clock" (dir n))
130 (declare-function org-element-at-point "org-element" ())
131 (declare-function org-element-cache-refresh "org-element" (pos))
132 (declare-function org-element-cache-reset "org-element" (&optional all))
133 (declare-function org-element-contents "org-element" (element))
134 (declare-function org-element-context "org-element" (&optional element))
135 (declare-function org-element-copy "org-element" (datum))
136 (declare-function org-element-interpret-data "org-element" (data &optional parent))
137 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
138 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
139 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
140 (declare-function org-element-property "org-element" (property element))
141 (declare-function org-element-put-property "org-element" (element property value))
142 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
143 (declare-function org-element-type "org-element" (element))
144 (declare-function org-element-update-syntax "org-element" ())
145 (declare-function org-id-find-id-file "org-id" (id))
146 (declare-function org-id-get-create "org-id" (&optional force))
147 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
148 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
149 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
150 (declare-function org-plot/gnuplot "org-plot" (&optional params))
151 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
152 (declare-function org-table-align "org-table" ())
153 (declare-function org-table-begin "org-table" (&optional table-type))
154 (declare-function org-table-beginning-of-field "org-table" (&optional n))
155 (declare-function org-table-blank-field "org-table" ())
156 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
157 (declare-function org-table-edit-field "org-table" (arg))
158 (declare-function org-table-end "org-table" (&optional table-type))
159 (declare-function org-table-end-of-field "org-table" (&optional n))
160 (declare-function org-table-insert-row "org-table" (&optional arg))
161 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
162 (declare-function org-table-maybe-eval-formula "org-table" ())
163 (declare-function org-table-maybe-recalculate-line "org-table" ())
164 (declare-function org-table-next-row "org-table" ())
165 (declare-function org-table-paste-rectangle "org-table" ())
166 (declare-function org-table-wrap-region "org-table" (arg))
167 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
168 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
169 (declare-function orgtbl-mode "org-table" (&optional arg))
171 (defsubst org-uniquify (list)
172 "Non-destructively remove duplicate elements from LIST."
173 (let ((res (copy-sequence list))) (delete-dups res)))
175 (defsubst org-get-at-bol (property)
176 "Get text property PROPERTY at the beginning of line."
177 (get-text-property (point-at-bol) property))
179 (defsubst org-trim (s)
180 "Remove whitespace at the beginning and the end of string S."
181 (replace-regexp-in-string
182 "\\`[ \t\n\r]+" ""
183 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
185 ;; load languages based on value of `org-babel-load-languages'
186 (defvar org-babel-load-languages)
188 ;;;###autoload
189 (defun org-babel-do-load-languages (sym value)
190 "Load the languages defined in `org-babel-load-languages'."
191 (set-default sym value)
192 (dolist (pair org-babel-load-languages)
193 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
194 (if active
195 (require (intern (concat "ob-" lang)))
196 (funcall 'fmakunbound
197 (intern (concat "org-babel-execute:" lang)))
198 (funcall 'fmakunbound
199 (intern (concat "org-babel-expand-body:" lang)))))))
201 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
202 ;;;###autoload
203 (defun org-babel-load-file (file &optional compile)
204 "Load Emacs Lisp source code blocks in the Org-mode FILE.
205 This function exports the source code using `org-babel-tangle'
206 and then loads the resulting file using `load-file'. With prefix
207 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
208 file to byte-code before it is loaded."
209 (interactive "fFile to load: \nP")
210 (let* ((age (lambda (file)
211 (float-time
212 (time-subtract (current-time)
213 (nth 5 (or (file-attributes (file-truename file))
214 (file-attributes file)))))))
215 (base-name (file-name-sans-extension file))
216 (exported-file (concat base-name ".el")))
217 ;; tangle if the org-mode file is newer than the elisp file
218 (unless (and (file-exists-p exported-file)
219 (> (funcall age file) (funcall age exported-file)))
220 ;; Tangle-file traversal returns reversed list of tangled files
221 ;; and we want to evaluate the first target.
222 (setq exported-file
223 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
224 (message "%s %s"
225 (if compile
226 (progn (byte-compile-file exported-file 'load)
227 "Compiled and loaded")
228 (progn (load-file exported-file) "Loaded"))
229 exported-file)))
231 (defcustom org-babel-load-languages '((emacs-lisp . t))
232 "Languages which can be evaluated in Org-mode buffers.
233 This list can be used to load support for any of the languages
234 below, note that each language will depend on a different set of
235 system executables and/or Emacs modes. When a language is
236 \"loaded\", then code blocks in that language can be evaluated
237 with `org-babel-execute-src-block' bound by default to C-c
238 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
239 be set to remove code block evaluation from the C-c C-c
240 keybinding. By default only Emacs Lisp (which has no
241 requirements) is loaded."
242 :group 'org-babel
243 :set 'org-babel-do-load-languages
244 :version "24.1"
245 :type '(alist :tag "Babel Languages"
246 :key-type
247 (choice
248 (const :tag "Awk" awk)
249 (const :tag "C" C)
250 (const :tag "R" R)
251 (const :tag "Asymptote" asymptote)
252 (const :tag "Calc" calc)
253 (const :tag "Clojure" clojure)
254 (const :tag "CSS" css)
255 (const :tag "Ditaa" ditaa)
256 (const :tag "Dot" dot)
257 (const :tag "Emacs Lisp" emacs-lisp)
258 (const :tag "Forth" forth)
259 (const :tag "Fortran" fortran)
260 (const :tag "Gnuplot" gnuplot)
261 (const :tag "Haskell" haskell)
262 (const :tag "IO" io)
263 (const :tag "J" J)
264 (const :tag "Java" java)
265 (const :tag "Javascript" js)
266 (const :tag "LaTeX" latex)
267 (const :tag "Ledger" ledger)
268 (const :tag "Lilypond" lilypond)
269 (const :tag "Lisp" lisp)
270 (const :tag "Makefile" makefile)
271 (const :tag "Maxima" maxima)
272 (const :tag "Matlab" matlab)
273 (const :tag "Mscgen" mscgen)
274 (const :tag "Ocaml" ocaml)
275 (const :tag "Octave" octave)
276 (const :tag "Org" org)
277 (const :tag "Perl" perl)
278 (const :tag "Pico Lisp" picolisp)
279 (const :tag "PlantUML" plantuml)
280 (const :tag "Python" python)
281 (const :tag "Ruby" ruby)
282 (const :tag "Sass" sass)
283 (const :tag "Scala" scala)
284 (const :tag "Scheme" scheme)
285 (const :tag "Screen" screen)
286 (const :tag "Shell Script" shell)
287 (const :tag "Shen" shen)
288 (const :tag "Sql" sql)
289 (const :tag "Sqlite" sqlite)
290 (const :tag "Stan" stan)
291 (const :tag "ebnf2ps" ebnf2ps))
292 :value-type (boolean :tag "Activate" :value t)))
294 ;;;; Customization variables
295 (defcustom org-clone-delete-id nil
296 "Remove ID property of clones of a subtree.
297 When non-nil, clones of a subtree don't inherit the ID property.
298 Otherwise they inherit the ID property with a new unique
299 identifier."
300 :type 'boolean
301 :version "24.1"
302 :group 'org-id)
304 ;;; Version
305 (org-check-version)
307 ;;;###autoload
308 (defun org-version (&optional here full message)
309 "Show the org-mode version.
310 Interactively, or when MESSAGE is non-nil, show it in echo area.
311 With prefix argument, or when HERE is non-nil, insert it at point.
312 In non-interactive uses, a reduced version string is output unless
313 FULL is given."
314 (interactive (list current-prefix-arg t (not current-prefix-arg)))
315 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
316 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
317 (load-suffixes (list ".el"))
318 (org-install-dir
319 (ignore-errors (org-find-library-dir "org-loaddefs"))))
320 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
321 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
322 (let* ((load-suffixes save-load-suffixes)
323 (release (org-release))
324 (git-version (org-git-version))
325 (version (format "Org-mode version %s (%s @ %s)"
326 release
327 git-version
328 (if org-install-dir
329 (if (string= org-dir org-install-dir)
330 org-install-dir
331 (concat "mixed installation! "
332 org-install-dir
333 " and "
334 org-dir))
335 "org-loaddefs.el can not be found!")))
336 (version1 (if full version release)))
337 (when here (insert version1))
338 (when message (message "%s" version1))
339 version1)))
341 (defconst org-version (org-version))
344 ;;; Syntax Constants
346 ;;;; Block
348 (defconst org-block-regexp
349 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
350 "Regular expression for hiding blocks.")
352 (defconst org-dblock-start-re
353 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
354 "Matches the start line of a dynamic block, with parameters.")
356 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
357 "Matches the end of a dynamic block.")
359 ;;;; Clock and Planning
361 (defconst org-clock-string "CLOCK:"
362 "String used as prefix for timestamps clocking work hours on an item.")
364 (defvar org-closed-string "CLOSED:"
365 "String used as the prefix for timestamps logging closing a TODO entry.")
367 (defvar org-deadline-string "DEADLINE:"
368 "String to mark deadline entries.
369 A deadline is this string, followed by a time stamp. Should be a word,
370 terminated by a colon. You can insert a schedule keyword and
371 a timestamp with \\[org-deadline].")
373 (defvar org-scheduled-string "SCHEDULED:"
374 "String to mark scheduled TODO entries.
375 A schedule is this string, followed by a time stamp. Should be a word,
376 terminated by a colon. You can insert a schedule keyword and
377 a timestamp with \\[org-schedule].")
379 (defconst org-ds-keyword-length
380 (+ 2
381 (apply #'max
382 (mapcar #'length
383 (list org-deadline-string org-scheduled-string
384 org-clock-string org-closed-string))))
385 "Maximum length of the DEADLINE and SCHEDULED keywords.")
387 (defconst org-planning-line-re
388 (concat "^[ \t]*"
389 (regexp-opt
390 (list org-closed-string org-deadline-string org-scheduled-string)
392 "Matches a line with planning info.
393 Matched keyword is in group 1.")
395 (defconst org-clock-line-re
396 (concat "^[ \t]*" org-clock-string)
397 "Matches a line with clock info.")
399 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
400 "Matches the DEADLINE keyword.")
402 (defconst org-deadline-time-regexp
403 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
404 "Matches the DEADLINE keyword together with a time stamp.")
406 (defconst org-deadline-time-hour-regexp
407 (concat "\\<" org-deadline-string
408 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
409 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
411 (defconst org-deadline-line-regexp
412 (concat "\\<\\(" org-deadline-string "\\).*")
413 "Matches the DEADLINE keyword and the rest of the line.")
415 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
416 "Matches the SCHEDULED keyword.")
418 (defconst org-scheduled-time-regexp
419 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
420 "Matches the SCHEDULED keyword together with a time stamp.")
422 (defconst org-scheduled-time-hour-regexp
423 (concat "\\<" org-scheduled-string
424 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
425 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
427 (defconst org-closed-time-regexp
428 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
429 "Matches the CLOSED keyword together with a time stamp.")
431 (defconst org-keyword-time-regexp
432 (concat "\\<"
433 (regexp-opt
434 (list org-scheduled-string org-deadline-string org-closed-string
435 org-clock-string)
437 " *[[<]\\([^]>]+\\)[]>]")
438 "Matches any of the 4 keywords, together with the time stamp.")
440 (defconst org-keyword-time-not-clock-regexp
441 (concat
442 "\\<"
443 (regexp-opt
444 (list org-scheduled-string org-deadline-string org-closed-string) t)
445 " *[[<]\\([^]>]+\\)[]>]")
446 "Matches any of the 3 keywords, together with the time stamp.")
448 (defconst org-maybe-keyword-time-regexp
449 (concat "\\(\\<"
450 (regexp-opt
451 (list org-scheduled-string org-deadline-string org-closed-string
452 org-clock-string)
454 "\\)?"
455 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
456 "\\|"
457 "<%%([^\r\n>]*>\\)")
458 "Matches a timestamp, possibly preceded by a keyword.")
460 (defconst org-all-time-keywords
461 (mapcar (lambda (w) (substring w 0 -1))
462 (list org-scheduled-string org-deadline-string
463 org-clock-string org-closed-string))
464 "List of time keywords.")
466 ;;;; Drawer
468 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
469 "Matches first or last line of a hidden block.
470 Group 1 contains drawer's name or \"END\".")
472 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
473 "Regular expression matching the first line of a property drawer.")
475 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
476 "Regular expression matching the last line of a property drawer.")
478 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
479 "Regular expression matching the first line of a clock drawer.")
481 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
482 "Regular expression matching the last line of a clock drawer.")
484 (defconst org-property-drawer-re
485 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
486 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
487 "[ \t]*:END:[ \t]*$")
488 "Matches an entire property drawer.")
490 (defconst org-clock-drawer-re
491 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
492 org-clock-drawer-end-re "\\)\n?")
493 "Matches an entire clock drawer.")
495 ;;;; Headline
497 (defconst org-heading-keyword-regexp-format
498 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
499 "Printf format for a regexp matching a headline with some keyword.
500 This regexp will match the headline of any node which has the
501 exact keyword that is put into the format. The keyword isn't in
502 any group by default, but the stars and the body are.")
504 (defconst org-heading-keyword-maybe-regexp-format
505 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
506 "Printf format for a regexp matching a headline, possibly with some keyword.
507 This regexp can match any headline with the specified keyword, or
508 without a keyword. The keyword isn't in any group by default,
509 but the stars and the body are.")
511 (defconst org-archive-tag "ARCHIVE"
512 "The tag that marks a subtree as archived.
513 An archived subtree does not open during visibility cycling, and does
514 not contribute to the agenda listings.")
516 (defconst org-comment-string "COMMENT"
517 "Entries starting with this keyword will never be exported.
518 An entry can be toggled between COMMENT and normal with
519 \\[org-toggle-comment].")
522 ;;;; LaTeX Environments and Fragments
524 (defconst org-latex-regexps
525 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
526 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
527 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
528 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
529 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
530 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
531 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
532 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
533 "Regular expressions for matching embedded LaTeX.")
535 ;;;; Node Property
537 (defconst org-effort-property "Effort"
538 "The property that is being used to keep track of effort estimates.
539 Effort estimates given in this property need to have the format H:MM.")
541 ;;;; Table
543 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
544 "Detect an org-type or table-type table.")
546 (defconst org-table-line-regexp "^[ \t]*|"
547 "Detect an org-type table line.")
549 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
550 "Detect an org-type table line.")
552 (defconst org-table-hline-regexp "^[ \t]*|-"
553 "Detect an org-type table hline.")
555 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
556 "Detect a table-type table hline.")
558 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
559 "Detect the first line outside a table when searching from within it.
560 This works for both table types.")
562 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
563 "Detect a #+TBLFM line.")
565 ;;;; Timestamp
567 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
568 "Regular expression for fast time stamp matching.")
570 (defconst org-ts-regexp-inactive
571 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
572 "Regular expression for fast inactive time stamp matching.")
574 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
575 "Regular expression for fast time stamp matching.")
577 (defconst org-ts-regexp0
578 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
579 "Regular expression matching time strings for analysis.
580 This one does not require the space after the date, so it can be used
581 on a string that terminates immediately after the date.")
583 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
584 "Regular expression matching time strings for analysis.")
586 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
587 "Regular expression matching time stamps, with groups.")
589 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
590 "Regular expression matching time stamps (also [..]), with groups.")
592 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
593 "Regular expression matching a time stamp range.")
595 (defconst org-tr-regexp-both
596 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
597 "Regular expression matching a time stamp range.")
599 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
600 org-ts-regexp "\\)?")
601 "Regular expression matching a time stamp or time stamp range.")
603 (defconst org-tsr-regexp-both
604 (concat org-ts-regexp-both "\\(--?-?"
605 org-ts-regexp-both "\\)?")
606 "Regular expression matching a time stamp or time stamp range.
607 The time stamps may be either active or inactive.")
609 (defconst org-repeat-re
610 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
611 "Regular expression for specifying repeated events.
612 After a match, group 1 contains the repeat expression.")
614 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
615 "Formats for `format-time-string' which are used for time stamps.")
618 ;;; The custom variables
620 (defgroup org nil
621 "Outline-based notes management and organizer."
622 :tag "Org"
623 :group 'outlines
624 :group 'calendar)
626 (defcustom org-mode-hook nil
627 "Mode hook for Org-mode, run after the mode was turned on."
628 :group 'org
629 :type 'hook)
631 (defcustom org-load-hook nil
632 "Hook that is run after org.el has been loaded."
633 :group 'org
634 :type 'hook)
636 (defcustom org-log-buffer-setup-hook nil
637 "Hook that is run after an Org log buffer is created."
638 :group 'org
639 :version "24.1"
640 :type 'hook)
642 (defvar org-modules) ; defined below
643 (defvar org-modules-loaded nil
644 "Have the modules been loaded already?")
646 (defun org-load-modules-maybe (&optional force)
647 "Load all extensions listed in `org-modules'."
648 (when (or force (not org-modules-loaded))
649 (dolist (ext org-modules)
650 (condition-case nil (require ext)
651 (error (message "Problems while trying to load feature `%s'" ext))))
652 (setq org-modules-loaded t)))
654 (defun org-set-modules (var value)
655 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
656 (set var value)
657 (when (featurep 'org)
658 (org-load-modules-maybe 'force)
659 (org-element-cache-reset 'all)))
661 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
662 "Modules that should always be loaded together with org.el.
664 If a description starts with <C>, the file is not part of Emacs
665 and loading it will require that you have downloaded and properly
666 installed the Org mode distribution.
668 You can also use this system to load external packages (i.e. neither Org
669 core modules, nor modules from the CONTRIB directory). Just add symbols
670 to the end of the list. If the package is called org-xyz.el, then you need
671 to add the symbol `xyz', and the package must have a call to:
673 (provide \\='org-xyz)
675 For export specific modules, see also `org-export-backends'."
676 :group 'org
677 :set 'org-set-modules
678 :version "24.4"
679 :package-version '(Org . "8.0")
680 :type
681 '(set :greedy t
682 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
683 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
684 (const :tag " crypt: Encryption of subtrees" org-crypt)
685 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
686 (const :tag " docview: Links to doc-view buffers" org-docview)
687 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
688 (const :tag " habit: Track your consistency with habits" org-habit)
689 (const :tag " id: Global IDs for identifying entries" org-id)
690 (const :tag " info: Links to Info nodes" org-info)
691 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
692 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
693 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
694 (const :tag " mouse: Additional mouse support" org-mouse)
695 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
696 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
697 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
699 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
700 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
701 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
702 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
703 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
704 (const :tag "C collector: Collect properties into tables" org-collector)
705 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
706 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
707 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
708 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
709 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
710 (const :tag "C eval: Include command output as text" org-eval)
711 (const :tag "C eww: Store link to url of eww" org-eww)
712 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
713 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
714 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
715 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
716 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
717 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
718 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
719 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
720 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
721 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
722 (const :tag "C mew: Links to Mew folders/messages" org-mew)
723 (const :tag "C mtags: Support for muse-like tags" org-mtags)
724 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
725 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
726 (const :tag "C registry: A registry for Org-mode links" org-registry)
727 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
728 (const :tag "C secretary: Team management with org-mode" org-secretary)
729 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
730 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
731 (const :tag "C track: Keep up with Org-mode development" org-track)
732 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
733 (const :tag "C vm: Links to VM folders/messages" org-vm)
734 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
735 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
736 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
738 (defvar org-export-registered-backends) ; From ox.el.
739 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
740 (declare-function org-export-backend-name "ox" (backend))
741 (defcustom org-export-backends '(ascii html icalendar latex)
742 "List of export back-ends that should be always available.
744 If a description starts with <C>, the file is not part of Emacs
745 and loading it will require that you have downloaded and properly
746 installed the Org mode distribution.
748 Unlike to `org-modules', libraries in this list will not be
749 loaded along with Org, but only once the export framework is
750 needed.
752 This variable needs to be set before org.el is loaded. If you
753 need to make a change while Emacs is running, use the customize
754 interface or run the following code, where VAL stands for the new
755 value of the variable, after updating it:
757 (progn
758 (setq org-export-registered-backends
759 (cl-remove-if-not
760 (lambda (backend)
761 (let ((name (org-export-backend-name backend)))
762 (or (memq name val)
763 (catch \\='parentp
764 (dolist (b val)
765 (and (org-export-derived-backend-p b name)
766 (throw \\='parentp t)))))))
767 org-export-registered-backends))
768 (let ((new-list (mapcar #\\='org-export-backend-name
769 org-export-registered-backends)))
770 (dolist (backend val)
771 (cond
772 ((not (load (format \"ox-%s\" backend) t t))
773 (message \"Problems while trying to load export back-end \\=`%s\\='\"
774 backend))
775 ((not (memq backend new-list)) (push backend new-list))))
776 (set-default \\='org-export-backends new-list)))
778 Adding a back-end to this list will also pull the back-end it
779 depends on, if any."
780 :group 'org
781 :group 'org-export
782 :version "24.4"
783 :package-version '(Org . "8.0")
784 :initialize 'custom-initialize-set
785 :set (lambda (var val)
786 (if (not (featurep 'ox)) (set-default var val)
787 ;; Any back-end not required anymore (not present in VAL and not
788 ;; a parent of any back-end in the new value) is removed from the
789 ;; list of registered back-ends.
790 (setq org-export-registered-backends
791 (cl-remove-if-not
792 (lambda (backend)
793 (let ((name (org-export-backend-name backend)))
794 (or (memq name val)
795 (catch 'parentp
796 (dolist (b val)
797 (and (org-export-derived-backend-p b name)
798 (throw 'parentp t)))))))
799 org-export-registered-backends))
800 ;; Now build NEW-LIST of both new back-ends and required
801 ;; parents.
802 (let ((new-list (mapcar #'org-export-backend-name
803 org-export-registered-backends)))
804 (dolist (backend val)
805 (cond
806 ((not (load (format "ox-%s" backend) t t))
807 (message "Problems while trying to load export back-end `%s'"
808 backend))
809 ((not (memq backend new-list)) (push backend new-list))))
810 ;; Set VAR to that list with fixed dependencies.
811 (set-default var new-list))))
812 :type '(set :greedy t
813 (const :tag " ascii Export buffer to ASCII format" ascii)
814 (const :tag " beamer Export buffer to Beamer presentation" beamer)
815 (const :tag " html Export buffer to HTML format" html)
816 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
817 (const :tag " latex Export buffer to LaTeX format" latex)
818 (const :tag " man Export buffer to MAN format" man)
819 (const :tag " md Export buffer to Markdown format" md)
820 (const :tag " odt Export buffer to ODT format" odt)
821 (const :tag " org Export buffer to Org format" org)
822 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
823 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
824 (const :tag "C deck Export buffer to deck.js presentations" deck)
825 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
826 (const :tag "C groff Export buffer to Groff format" groff)
827 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
828 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
829 (const :tag "C s5 Export buffer to s5 presentations" s5)
830 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
832 (eval-after-load 'ox
833 '(dolist (backend org-export-backends)
834 (condition-case nil (require (intern (format "ox-%s" backend)))
835 (error (message "Problems while trying to load export back-end `%s'"
836 backend)))))
838 (defcustom org-support-shift-select nil
839 "Non-nil means make shift-cursor commands select text when possible.
840 \\<org-mode-map>\
842 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
843 start selecting a region, or enlarge regions started in this way.
844 In Org-mode, in special contexts, these same keys are used for
845 other purposes, important enough to compete with shift selection.
846 Org tries to balance these needs by supporting `shift-select-mode'
847 outside these special contexts, under control of this variable.
849 The default of this variable is nil, to avoid confusing behavior. Shifted
850 cursor keys will then execute Org commands in the following contexts:
851 - on a headline, changing TODO state (left/right) and priority (up/down)
852 - on a time stamp, changing the time
853 - in a plain list item, changing the bullet type
854 - in a property definition line, switching between allowed values
855 - in the BEGIN line of a clock table (changing the time block).
856 Outside these contexts, the commands will throw an error.
858 When this variable is t and the cursor is not in a special
859 context, Org-mode will support shift-selection for making and
860 enlarging regions. To make this more effective, the bullet
861 cycling will no longer happen anywhere in an item line, but only
862 if the cursor is exactly on the bullet.
864 If you set this variable to the symbol `always', then the keys
865 will not be special in headlines, property lines, and item lines,
866 to make shift selection work there as well. If this is what you
867 want, you can use the following alternative commands:
868 `\\[org-todo]' and `\\[org-priority]' \
869 to change TODO state and priority,
870 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
871 can be used to switch TODO sets,
872 `\\[org-ctrl-c-minus]' to cycle item bullet types,
873 and properties can be edited by hand or in column view.
875 However, when the cursor is on a timestamp, shift-cursor commands
876 will still edit the time stamp - this is just too good to give up.
878 XEmacs user should have this variable set to nil, because
879 `shift-select-mode' is in Emacs 23 or later only."
880 :group 'org
881 :type '(choice
882 (const :tag "Never" nil)
883 (const :tag "When outside special context" t)
884 (const :tag "Everywhere except timestamps" always)))
886 (defcustom org-loop-over-headlines-in-active-region nil
887 "Shall some commands act upon headlines in the active region?
889 When set to t, some commands will be performed in all headlines
890 within the active region.
892 When set to `start-level', some commands will be performed in all
893 headlines within the active region, provided that these headlines
894 are of the same level than the first one.
896 When set to a string, those commands will be performed on the
897 matching headlines within the active region. Such string must be
898 a tags/property/todo match as it is used in the agenda tags view.
900 The list of commands is: `org-schedule', `org-deadline',
901 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
902 `org-archive-to-archive-sibling'. The archiving commands skip
903 already archived entries."
904 :type '(choice (const :tag "Don't loop" nil)
905 (const :tag "All headlines in active region" t)
906 (const :tag "In active region, headlines at the same level than the first one" start-level)
907 (string :tag "Tags/Property/Todo matcher"))
908 :version "24.1"
909 :group 'org-todo
910 :group 'org-archive)
912 (defgroup org-startup nil
913 "Options concerning startup of Org-mode."
914 :tag "Org Startup"
915 :group 'org)
917 (defcustom org-startup-folded t
918 "Non-nil means entering Org-mode will switch to OVERVIEW.
919 This can also be configured on a per-file basis by adding one of
920 the following lines anywhere in the buffer:
922 #+STARTUP: fold (or `overview', this is equivalent)
923 #+STARTUP: nofold (or `showall', this is equivalent)
924 #+STARTUP: content
925 #+STARTUP: showeverything
927 By default, this option is ignored when Org opens agenda files
928 for the first time. If you want the agenda to honor the startup
929 option, set `org-agenda-inhibit-startup' to nil."
930 :group 'org-startup
931 :type '(choice
932 (const :tag "nofold: show all" nil)
933 (const :tag "fold: overview" t)
934 (const :tag "content: all headlines" content)
935 (const :tag "show everything, even drawers" showeverything)))
937 (defcustom org-startup-truncated t
938 "Non-nil means entering Org-mode will set `truncate-lines'.
939 This is useful since some lines containing links can be very long and
940 uninteresting. Also tables look terrible when wrapped."
941 :group 'org-startup
942 :type 'boolean)
944 (defcustom org-startup-indented nil
945 "Non-nil means turn on `org-indent-mode' on startup.
946 This can also be configured on a per-file basis by adding one of
947 the following lines anywhere in the buffer:
949 #+STARTUP: indent
950 #+STARTUP: noindent"
951 :group 'org-structure
952 :type '(choice
953 (const :tag "Not" nil)
954 (const :tag "Globally (slow on startup in large files)" t)))
956 (defcustom org-use-sub-superscripts t
957 "Non-nil means interpret \"_\" and \"^\" for display.
959 If you want to control how Org exports those characters, see
960 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
961 used to be an alias for `org-export-with-sub-superscripts' in
962 Org <8.0, it is not anymore.
964 When this option is turned on, you can use TeX-like syntax for
965 sub- and superscripts within the buffer. Several characters after
966 \"_\" or \"^\" will be considered as a single item - so grouping
967 with {} is normally not needed. For example, the following things
968 will be parsed as single sub- or superscripts:
970 10^24 or 10^tau several digits will be considered 1 item.
971 10^-12 or 10^-tau a leading sign with digits or a word
972 x^2-y^3 will be read as x^2 - y^3, because items are
973 terminated by almost any nonword/nondigit char.
974 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
976 Still, ambiguity is possible. So when in doubt, use {} to enclose
977 the sub/superscript. If you set this variable to the symbol `{}',
978 the braces are *required* in order to trigger interpretations as
979 sub/superscript. This can be helpful in documents that need \"_\"
980 frequently in plain text."
981 :group 'org-startup
982 :version "24.4"
983 :package-version '(Org . "8.0")
984 :type '(choice
985 (const :tag "Always interpret" t)
986 (const :tag "Only with braces" {})
987 (const :tag "Never interpret" nil)))
989 (defcustom org-startup-with-beamer-mode nil
990 "Non-nil means turn on `org-beamer-mode' on startup.
991 This can also be configured on a per-file basis by adding one of
992 the following lines anywhere in the buffer:
994 #+STARTUP: beamer"
995 :group 'org-startup
996 :version "24.1"
997 :type 'boolean)
999 (defcustom org-startup-align-all-tables nil
1000 "Non-nil means align all tables when visiting a file.
1001 This is useful when the column width in tables is forced with <N> cookies
1002 in table fields. Such tables will look correct only after the first re-align.
1003 This can also be configured on a per-file basis by adding one of
1004 the following lines anywhere in the buffer:
1005 #+STARTUP: align
1006 #+STARTUP: noalign"
1007 :group 'org-startup
1008 :type 'boolean)
1010 (defcustom org-startup-with-inline-images nil
1011 "Non-nil means show inline images when loading a new Org file.
1012 This can also be configured on a per-file basis by adding one of
1013 the following lines anywhere in the buffer:
1014 #+STARTUP: inlineimages
1015 #+STARTUP: noinlineimages"
1016 :group 'org-startup
1017 :version "24.1"
1018 :type 'boolean)
1020 (defcustom org-startup-with-latex-preview nil
1021 "Non-nil means preview LaTeX fragments when loading a new Org file.
1023 This can also be configured on a per-file basis by adding one of
1024 the following lines anywhere in the buffer:
1025 #+STARTUP: latexpreview
1026 #+STARTUP: nolatexpreview"
1027 :group 'org-startup
1028 :version "24.4"
1029 :package-version '(Org . "8.0")
1030 :type 'boolean)
1032 (defcustom org-insert-mode-line-in-empty-file nil
1033 "Non-nil means insert the first line setting Org-mode in empty files.
1034 When the function `org-mode' is called interactively in an empty file, this
1035 normally means that the file name does not automatically trigger Org-mode.
1036 To ensure that the file will always be in Org-mode in the future, a
1037 line enforcing Org-mode will be inserted into the buffer, if this option
1038 has been set."
1039 :group 'org-startup
1040 :type 'boolean)
1042 (defcustom org-replace-disputed-keys nil
1043 "Non-nil means use alternative key bindings for some keys.
1044 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
1045 These keys are also used by other packages like shift-selection-mode'
1046 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1047 If you want to use Org-mode together with one of these other modes,
1048 or more generally if you would like to move some Org-mode commands to
1049 other keys, set this variable and configure the keys with the variable
1050 `org-disputed-keys'.
1052 This option is only relevant at load-time of Org-mode, and must be set
1053 *before* org.el is loaded. Changing it requires a restart of Emacs to
1054 become effective."
1055 :group 'org-startup
1056 :type 'boolean)
1058 (defcustom org-use-extra-keys nil
1059 "Non-nil means use extra key sequence definitions for certain commands.
1060 This happens automatically if you run XEmacs or if `window-system'
1061 is nil. This variable lets you do the same manually. You must
1062 set it before loading org.
1064 Example: on Carbon Emacs 22 running graphically, with an external
1065 keyboard on a Powerbook, the default way of setting M-left might
1066 not work for either Alt or ESC. Setting this variable will make
1067 it work for ESC."
1068 :group 'org-startup
1069 :type 'boolean)
1071 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1073 (defcustom org-disputed-keys
1074 '(([(shift up)] . [(meta p)])
1075 ([(shift down)] . [(meta n)])
1076 ([(shift left)] . [(meta -)])
1077 ([(shift right)] . [(meta +)])
1078 ([(control shift right)] . [(meta shift +)])
1079 ([(control shift left)] . [(meta shift -)]))
1080 "Keys for which Org-mode and other modes compete.
1081 This is an alist, cars are the default keys, second element specifies
1082 the alternative to use when `org-replace-disputed-keys' is t.
1084 Keys can be specified in any syntax supported by `define-key'.
1085 The value of this option takes effect only at Org-mode's startup,
1086 therefore you'll have to restart Emacs to apply it after changing."
1087 :group 'org-startup
1088 :type 'alist)
1090 (defun org-key (key)
1091 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1092 Or return the original if not disputed.
1093 Also apply the translations defined in `org-xemacs-key-equivalents'."
1094 (when org-replace-disputed-keys
1095 (let* ((nkey (key-description key))
1096 (x (org-find-if (lambda (x)
1097 (equal (key-description (car x)) nkey))
1098 org-disputed-keys)))
1099 (setq key (if x (cdr x) key))))
1100 (when (featurep 'xemacs)
1101 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1102 key)
1104 (defun org-find-if (predicate seq)
1105 (catch 'exit
1106 (while seq
1107 (if (funcall predicate (car seq))
1108 (throw 'exit (car seq))
1109 (pop seq)))))
1111 (defun org-defkey (keymap key def)
1112 "Define a key, possibly translated, as returned by `org-key'."
1113 (define-key keymap (org-key key) def))
1115 (defcustom org-ellipsis nil
1116 "The ellipsis to use in the Org-mode outline.
1117 When nil, just use the standard three dots.
1118 When a string, use that string instead.
1119 When a face, use the standard 3 dots, but with the specified face.
1120 The change affects only Org-mode (which will then use its own display table).
1121 Changing this requires executing \\[org-mode] in a buffer to become
1122 effective."
1123 :group 'org-startup
1124 :type '(choice (const :tag "Default" nil)
1125 (face :tag "Face" :value org-warning)
1126 (string :tag "String" :value "...#")))
1128 (defvar org-display-table nil
1129 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1131 (defgroup org-keywords nil
1132 "Keywords in Org-mode."
1133 :tag "Org Keywords"
1134 :group 'org)
1136 (defcustom org-closed-keep-when-no-todo nil
1137 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1138 :group 'org-todo
1139 :group 'org-keywords
1140 :version "24.4"
1141 :package-version '(Org . "8.0")
1142 :type 'boolean)
1144 (defgroup org-structure nil
1145 "Options concerning the general structure of Org-mode files."
1146 :tag "Org Structure"
1147 :group 'org)
1149 (defgroup org-reveal-location nil
1150 "Options about how to make context of a location visible."
1151 :tag "Org Reveal Location"
1152 :group 'org-structure)
1154 (defcustom org-show-context-detail '((isearch . lineage)
1155 (bookmark-jump . lineage)
1156 (default . ancestors))
1157 "Alist between context and visibility span when revealing a location.
1159 \\<org-mode-map>Some actions may move point into invisible
1160 locations. As a consequence, Org always expose a neighborhood
1161 around point. How much is shown depends on the initial action,
1162 or context. Valid contexts are
1164 agenda when exposing an entry from the agenda
1165 org-goto when using the command `org-goto' (\\[org-goto])
1166 occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
1167 tags-tree when constructing a sparse tree based on tags matches
1168 link-search when exposing search matches associated with a link
1169 mark-goto when exposing the jump goal of a mark
1170 bookmark-jump when exposing a bookmark location
1171 isearch when exiting from an incremental search
1172 default default for all contexts not set explicitly
1174 Allowed visibility spans are
1176 minimal show current headline; if point is not on headline,
1177 also show entry
1179 local show current headline, entry and next headline
1181 ancestors show current headline and its direct ancestors; if
1182 point is not on headline, also show entry
1184 lineage show current headline, its direct ancestors and all
1185 their children; if point is not on headline, also show
1186 entry and first child
1188 tree show current headline, its direct ancestors and all
1189 their children; if point is not on headline, also show
1190 entry and all children
1192 canonical show current headline, its direct ancestors along with
1193 their entries and children; if point is not located on
1194 the headline, also show current entry and all children
1196 As special cases, a nil or t value means show all contexts in
1197 `minimal' or `canonical' view, respectively.
1199 Some views can make displayed information very compact, but also
1200 make it harder to edit the location of the match. In such
1201 a case, use the command `org-reveal' (\\[org-reveal]) to show
1202 more context."
1203 :group 'org-reveal-location
1204 :version "25.1"
1205 :package-version '(Org . "8.3")
1206 :type '(choice
1207 (const :tag "Canonical" t)
1208 (const :tag "Minimal" nil)
1209 (repeat :greedy t :tag "Individual contexts"
1210 (cons
1211 (choice :tag "Context"
1212 (const agenda)
1213 (const org-goto)
1214 (const occur-tree)
1215 (const tags-tree)
1216 (const link-search)
1217 (const mark-goto)
1218 (const bookmark-jump)
1219 (const isearch)
1220 (const default))
1221 (choice :tag "Detail level"
1222 (const minimal)
1223 (const local)
1224 (const ancestors)
1225 (const lineage)
1226 (const tree)
1227 (const canonical))))))
1229 (defcustom org-indirect-buffer-display 'other-window
1230 "How should indirect tree buffers be displayed?
1231 This applies to indirect buffers created with the commands
1232 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1233 Valid values are:
1234 current-window Display in the current window
1235 other-window Just display in another window.
1236 dedicated-frame Create one new frame, and re-use it each time.
1237 new-frame Make a new frame each time. Note that in this case
1238 previously-made indirect buffers are kept, and you need to
1239 kill these buffers yourself."
1240 :group 'org-structure
1241 :group 'org-agenda-windows
1242 :type '(choice
1243 (const :tag "In current window" current-window)
1244 (const :tag "In current frame, other window" other-window)
1245 (const :tag "Each time a new frame" new-frame)
1246 (const :tag "One dedicated frame" dedicated-frame)))
1248 (defcustom org-use-speed-commands nil
1249 "Non-nil means activate single letter commands at beginning of a headline.
1250 This may also be a function to test for appropriate locations where speed
1251 commands should be active.
1253 For example, to activate speed commands when the point is on any
1254 star at the beginning of the headline, you can do this:
1256 (setq org-use-speed-commands
1257 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1258 :group 'org-structure
1259 :type '(choice
1260 (const :tag "Never" nil)
1261 (const :tag "At beginning of headline stars" t)
1262 (function)))
1264 (defcustom org-speed-commands-user nil
1265 "Alist of additional speed commands.
1266 This list will be checked before `org-speed-commands-default'
1267 when the variable `org-use-speed-commands' is non-nil
1268 and when the cursor is at the beginning of a headline.
1269 The car if each entry is a string with a single letter, which must
1270 be assigned to `self-insert-command' in the global map.
1271 The cdr is either a command to be called interactively, a function
1272 to be called, or a form to be evaluated.
1273 An entry that is just a list with a single string will be interpreted
1274 as a descriptive headline that will be added when listing the speed
1275 commands in the Help buffer using the `?' speed command."
1276 :group 'org-structure
1277 :type '(repeat :value ("k" . ignore)
1278 (choice :value ("k" . ignore)
1279 (list :tag "Descriptive Headline" (string :tag "Headline"))
1280 (cons :tag "Letter and Command"
1281 (string :tag "Command letter")
1282 (choice
1283 (function)
1284 (sexp))))))
1286 (defcustom org-bookmark-names-plist
1287 '(:last-capture "org-capture-last-stored"
1288 :last-refile "org-refile-last-stored"
1289 :last-capture-marker "org-capture-last-stored-marker")
1290 "Names for bookmarks automatically set by some Org commands.
1291 This can provide strings as names for a number of bookmarks Org sets
1292 automatically. The following keys are currently implemented:
1293 :last-capture
1294 :last-capture-marker
1295 :last-refile
1296 When a key does not show up in the property list, the corresponding bookmark
1297 is not set."
1298 :group 'org-structure
1299 :type 'plist)
1301 (defgroup org-cycle nil
1302 "Options concerning visibility cycling in Org-mode."
1303 :tag "Org Cycle"
1304 :group 'org-structure)
1306 (defcustom org-cycle-skip-children-state-if-no-children t
1307 "Non-nil means skip CHILDREN state in entries that don't have any."
1308 :group 'org-cycle
1309 :type 'boolean)
1311 (defcustom org-cycle-max-level nil
1312 "Maximum level which should still be subject to visibility cycling.
1313 Levels higher than this will, for cycling, be treated as text, not a headline.
1314 When `org-odd-levels-only' is set, a value of N in this variable actually
1315 means 2N-1 stars as the limiting headline.
1316 When nil, cycle all levels.
1317 Note that the limiting level of cycling is also influenced by
1318 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1319 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1320 than its value."
1321 :group 'org-cycle
1322 :type '(choice
1323 (const :tag "No limit" nil)
1324 (integer :tag "Maximum level")))
1326 (defcustom org-hide-block-startup nil
1327 "Non-nil means entering Org-mode will fold all blocks.
1328 This can also be set in on a per-file basis with
1330 #+STARTUP: hideblocks
1331 #+STARTUP: showblocks"
1332 :group 'org-startup
1333 :group 'org-cycle
1334 :type 'boolean)
1336 (defcustom org-cycle-global-at-bob nil
1337 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1338 This makes it possible to do global cycling without having to use S-TAB or
1339 \\[universal-argument] TAB. For this special case to work, the first line
1340 of the buffer must not be a headline -- it may be empty or some other text.
1341 When used in this way, `org-cycle-hook' is disabled temporarily to make
1342 sure the cursor stays at the beginning of the buffer. When this option is
1343 nil, don't do anything special at the beginning of the buffer."
1344 :group 'org-cycle
1345 :type 'boolean)
1347 (defcustom org-cycle-level-after-item/entry-creation t
1348 "Non-nil means cycle entry level or item indentation in new empty entries.
1350 When the cursor is at the end of an empty headline, i.e., with only stars
1351 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1352 and then all possible ancestor states, before returning to the original state.
1353 This makes data entry extremely fast: M-RET to create a new headline,
1354 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1356 When the cursor is at the end of an empty plain list item, one TAB will
1357 make it a subitem, two or more tabs will back up to make this an item
1358 higher up in the item hierarchy."
1359 :group 'org-cycle
1360 :type 'boolean)
1362 (defcustom org-cycle-emulate-tab t
1363 "Where should `org-cycle' emulate TAB.
1364 nil Never
1365 white Only in completely white lines
1366 whitestart Only at the beginning of lines, before the first non-white char
1367 t Everywhere except in headlines
1368 exc-hl-bol Everywhere except at the start of a headline
1369 If TAB is used in a place where it does not emulate TAB, the current subtree
1370 visibility is cycled."
1371 :group 'org-cycle
1372 :type '(choice (const :tag "Never" nil)
1373 (const :tag "Only in completely white lines" white)
1374 (const :tag "Before first char in a line" whitestart)
1375 (const :tag "Everywhere except in headlines" t)
1376 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1378 (defcustom org-cycle-separator-lines 2
1379 "Number of empty lines needed to keep an empty line between collapsed trees.
1380 If you leave an empty line between the end of a subtree and the following
1381 headline, this empty line is hidden when the subtree is folded.
1382 Org-mode will leave (exactly) one empty line visible if the number of
1383 empty lines is equal or larger to the number given in this variable.
1384 So the default 2 means at least 2 empty lines after the end of a subtree
1385 are needed to produce free space between a collapsed subtree and the
1386 following headline.
1388 If the number is negative, and the number of empty lines is at least -N,
1389 all empty lines are shown.
1391 Special case: when 0, never leave empty lines in collapsed view."
1392 :group 'org-cycle
1393 :type 'integer)
1394 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1396 (defcustom org-pre-cycle-hook nil
1397 "Hook that is run before visibility cycling is happening.
1398 The function(s) in this hook must accept a single argument which indicates
1399 the new state that will be set right after running this hook. The
1400 argument is a symbol. Before a global state change, it can have the values
1401 `overview', `content', or `all'. Before a local state change, it can have
1402 the values `folded', `children', or `subtree'."
1403 :group 'org-cycle
1404 :type 'hook)
1406 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1407 org-cycle-hide-drawers
1408 org-cycle-show-empty-lines
1409 org-optimize-window-after-visibility-change)
1410 "Hook that is run after `org-cycle' has changed the buffer visibility.
1411 The function(s) in this hook must accept a single argument which indicates
1412 the new state that was set by the most recent `org-cycle' command. The
1413 argument is a symbol. After a global state change, it can have the values
1414 `overview', `contents', or `all'. After a local state change, it can have
1415 the values `folded', `children', or `subtree'."
1416 :group 'org-cycle
1417 :type 'hook
1418 :version "25.1"
1419 :package-version '(Org . "8.3"))
1421 (defgroup org-edit-structure nil
1422 "Options concerning structure editing in Org-mode."
1423 :tag "Org Edit Structure"
1424 :group 'org-structure)
1426 (defcustom org-odd-levels-only nil
1427 "Non-nil means skip even levels and only use odd levels for the outline.
1428 This has the effect that two stars are being added/taken away in
1429 promotion/demotion commands. It also influences how levels are
1430 handled by the exporters.
1431 Changing it requires restart of `font-lock-mode' to become effective
1432 for fontification also in regions already fontified.
1433 You may also set this on a per-file basis by adding one of the following
1434 lines to the buffer:
1436 #+STARTUP: odd
1437 #+STARTUP: oddeven"
1438 :group 'org-edit-structure
1439 :group 'org-appearance
1440 :type 'boolean)
1442 (defcustom org-adapt-indentation t
1443 "Non-nil means adapt indentation to outline node level.
1445 When this variable is set, Org assumes that you write outlines by
1446 indenting text in each node to align with the headline (after the
1447 stars). The following issues are influenced by this variable:
1449 - The indentation is increased by one space in a demotion
1450 command, and decreased by one in a promotion command. However,
1451 in the latter case, if shifting some line in the entry body
1452 would alter document structure (e.g., insert a new headline),
1453 indentation is not changed at all.
1455 - Property drawers and planning information is inserted indented
1456 when this variable is set. When nil, they will not be indented.
1458 - TAB indents a line relative to current level. The lines below
1459 a headline will be indented when this variable is set.
1461 Note that this is all about true indentation, by adding and
1462 removing space characters. See also `org-indent.el' which does
1463 level-dependent indentation in a virtual way, i.e. at display
1464 time in Emacs."
1465 :group 'org-edit-structure
1466 :type 'boolean)
1468 (defcustom org-special-ctrl-a/e nil
1469 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1471 When t, `C-a' will bring back the cursor to the beginning of the
1472 headline text, i.e. after the stars and after a possible TODO
1473 keyword. In an item, this will be the position after bullet and
1474 check-box, if any. When the cursor is already at that position,
1475 another `C-a' will bring it to the beginning of the line.
1477 `C-e' will jump to the end of the headline, ignoring the presence
1478 of tags in the headline. A second `C-e' will then jump to the
1479 true end of the line, after any tags. This also means that, when
1480 this variable is non-nil, `C-e' also will never jump beyond the
1481 end of the heading of a folded section, i.e. not after the
1482 ellipses.
1484 When set to the symbol `reversed', the first `C-a' or `C-e' works
1485 normally, going to the true line boundary first. Only a directly
1486 following, identical keypress will bring the cursor to the
1487 special positions.
1489 This may also be a cons cell where the behavior for `C-a' and
1490 `C-e' is set separately."
1491 :group 'org-edit-structure
1492 :type '(choice
1493 (const :tag "off" nil)
1494 (const :tag "on: after stars/bullet and before tags first" t)
1495 (const :tag "reversed: true line boundary first" reversed)
1496 (cons :tag "Set C-a and C-e separately"
1497 (choice :tag "Special C-a"
1498 (const :tag "off" nil)
1499 (const :tag "on: after stars/bullet first" t)
1500 (const :tag "reversed: before stars/bullet first" reversed))
1501 (choice :tag "Special C-e"
1502 (const :tag "off" nil)
1503 (const :tag "on: before tags first" t)
1504 (const :tag "reversed: after tags first" reversed)))))
1505 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1507 (defcustom org-special-ctrl-k nil
1508 "Non-nil means `C-k' will behave specially in headlines.
1509 When nil, `C-k' will call the default `kill-line' command.
1510 When t, the following will happen while the cursor is in the headline:
1512 - When the cursor is at the beginning of a headline, kill the entire
1513 line and possible the folded subtree below the line.
1514 - When in the middle of the headline text, kill the headline up to the tags.
1515 - When after the headline text, kill the tags."
1516 :group 'org-edit-structure
1517 :type 'boolean)
1519 (defcustom org-ctrl-k-protect-subtree nil
1520 "Non-nil means, do not delete a hidden subtree with C-k.
1521 When set to the symbol `error', simply throw an error when C-k is
1522 used to kill (part-of) a headline that has hidden text behind it.
1523 Any other non-nil value will result in a query to the user, if it is
1524 OK to kill that hidden subtree. When nil, kill without remorse."
1525 :group 'org-edit-structure
1526 :version "24.1"
1527 :type '(choice
1528 (const :tag "Do not protect hidden subtrees" nil)
1529 (const :tag "Protect hidden subtrees with a security query" t)
1530 (const :tag "Never kill a hidden subtree with C-k" error)))
1532 (defcustom org-special-ctrl-o t
1533 "Non-nil means, make `C-o' insert a row in tables."
1534 :group 'org-edit-structure
1535 :type 'boolean)
1537 (defcustom org-catch-invisible-edits nil
1538 "Check if in invisible region before inserting or deleting a character.
1539 Valid values are:
1541 nil Do not check, so just do invisible edits.
1542 error Throw an error and do nothing.
1543 show Make point visible, and do the requested edit.
1544 show-and-error Make point visible, then throw an error and abort the edit.
1545 smart Make point visible, and do insertion/deletion if it is
1546 adjacent to visible text and the change feels predictable.
1547 Never delete a previously invisible character or add in the
1548 middle or right after an invisible region. Basically, this
1549 allows insertion and backward-delete right before ellipses.
1550 FIXME: maybe in this case we should not even show?"
1551 :group 'org-edit-structure
1552 :version "24.1"
1553 :type '(choice
1554 (const :tag "Do not check" nil)
1555 (const :tag "Throw error when trying to edit" error)
1556 (const :tag "Unhide, but do not do the edit" show-and-error)
1557 (const :tag "Show invisible part and do the edit" show)
1558 (const :tag "Be smart and do the right thing" smart)))
1560 (defcustom org-yank-folded-subtrees t
1561 "Non-nil means when yanking subtrees, fold them.
1562 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1563 it starts with a heading and all other headings in it are either children
1564 or siblings, then fold all the subtrees. However, do this only if no
1565 text after the yank would be swallowed into a folded tree by this action."
1566 :group 'org-edit-structure
1567 :type 'boolean)
1569 (defcustom org-yank-adjusted-subtrees nil
1570 "Non-nil means when yanking subtrees, adjust the level.
1571 With this setting, `org-paste-subtree' is used to insert the subtree, see
1572 this function for details."
1573 :group 'org-edit-structure
1574 :type 'boolean)
1576 (defcustom org-M-RET-may-split-line '((default . t))
1577 "Non-nil means M-RET will split the line at the cursor position.
1578 When nil, it will go to the end of the line before making a
1579 new line.
1580 You may also set this option in a different way for different
1581 contexts. Valid contexts are:
1583 headline when creating a new headline
1584 item when creating a new item
1585 table in a table field
1586 default the value to be used for all contexts not explicitly
1587 customized"
1588 :group 'org-structure
1589 :group 'org-table
1590 :type '(choice
1591 (const :tag "Always" t)
1592 (const :tag "Never" nil)
1593 (repeat :greedy t :tag "Individual contexts"
1594 (cons
1595 (choice :tag "Context"
1596 (const headline)
1597 (const item)
1598 (const table)
1599 (const default))
1600 (boolean)))))
1603 (defcustom org-insert-heading-respect-content nil
1604 "Non-nil means insert new headings after the current subtree.
1605 When nil, the new heading is created directly after the current line.
1606 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1607 this variable on for the duration of the command."
1608 :group 'org-structure
1609 :type 'boolean)
1611 (defcustom org-blank-before-new-entry '((heading . auto)
1612 (plain-list-item . auto))
1613 "Should `org-insert-heading' leave a blank line before new heading/item?
1614 The value is an alist, with `heading' and `plain-list-item' as CAR,
1615 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1616 which case Org will look at the surrounding headings/items and try to
1617 make an intelligent decision whether to insert a blank line or not."
1618 :group 'org-edit-structure
1619 :type '(list
1620 (cons (const heading)
1621 (choice (const :tag "Never" nil)
1622 (const :tag "Always" t)
1623 (const :tag "Auto" auto)))
1624 (cons (const plain-list-item)
1625 (choice (const :tag "Never" nil)
1626 (const :tag "Always" t)
1627 (const :tag "Auto" auto)))))
1629 (defcustom org-insert-heading-hook nil
1630 "Hook being run after inserting a new heading."
1631 :group 'org-edit-structure
1632 :type 'hook)
1634 (defcustom org-enable-fixed-width-editor t
1635 "Non-nil means lines starting with \":\" are treated as fixed-width.
1636 This currently only means they are never auto-wrapped.
1637 When nil, such lines will be treated like ordinary lines."
1638 :group 'org-edit-structure
1639 :type 'boolean)
1641 (defcustom org-goto-auto-isearch t
1642 "Non-nil means typing characters in `org-goto' starts incremental search.
1643 When nil, you can use these keybindings to navigate the buffer:
1645 q Quit the org-goto interface
1646 n Go to the next visible heading
1647 p Go to the previous visible heading
1648 f Go one heading forward on same level
1649 b Go one heading backward on same level
1650 u Go one heading up"
1651 :group 'org-edit-structure
1652 :type 'boolean)
1654 (defgroup org-sparse-trees nil
1655 "Options concerning sparse trees in Org-mode."
1656 :tag "Org Sparse Trees"
1657 :group 'org-structure)
1659 (defcustom org-highlight-sparse-tree-matches t
1660 "Non-nil means highlight all matches that define a sparse tree.
1661 The highlights will automatically disappear the next time the buffer is
1662 changed by an edit command."
1663 :group 'org-sparse-trees
1664 :type 'boolean)
1666 (defcustom org-remove-highlights-with-change t
1667 "Non-nil means any change to the buffer will remove temporary highlights.
1668 \\<org-mode-map>\
1669 Such highlights are created by `org-occur' and `org-clock-display'.
1670 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1671 to get rid of the highlights.
1672 The highlights created by `org-toggle-latex-fragment' always need
1673 `\\[org-toggle-latex-fragment]' to be removed."
1674 :group 'org-sparse-trees
1675 :group 'org-time
1676 :type 'boolean)
1679 (defcustom org-occur-hook '(org-first-headline-recenter)
1680 "Hook that is run after `org-occur' has constructed a sparse tree.
1681 This can be used to recenter the window to show as much of the structure
1682 as possible."
1683 :group 'org-sparse-trees
1684 :type 'hook)
1686 (defgroup org-imenu-and-speedbar nil
1687 "Options concerning imenu and speedbar in Org-mode."
1688 :tag "Org Imenu and Speedbar"
1689 :group 'org-structure)
1691 (defcustom org-imenu-depth 2
1692 "The maximum level for Imenu access to Org-mode headlines.
1693 This also applied for speedbar access."
1694 :group 'org-imenu-and-speedbar
1695 :type 'integer)
1697 (defgroup org-table nil
1698 "Options concerning tables in Org-mode."
1699 :tag "Org Table"
1700 :group 'org)
1702 (defcustom org-enable-table-editor 'optimized
1703 "Non-nil means lines starting with \"|\" are handled by the table editor.
1704 When nil, such lines will be treated like ordinary lines.
1706 When equal to the symbol `optimized', the table editor will be optimized to
1707 do the following:
1708 - Automatic overwrite mode in front of whitespace in table fields.
1709 This makes the structure of the table stay in tact as long as the edited
1710 field does not exceed the column width.
1711 - Minimize the number of realigns. Normally, the table is aligned each time
1712 TAB or RET are pressed to move to another field. With optimization this
1713 happens only if changes to a field might have changed the column width.
1714 Optimization requires replacing the functions `self-insert-command',
1715 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1716 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1717 very good at guessing when a re-align will be necessary, but you can always
1718 force one with \\[org-ctrl-c-ctrl-c].
1720 If you would like to use the optimized version in Org-mode, but the
1721 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1723 This variable can be used to turn on and off the table editor during a session,
1724 but in order to toggle optimization, a restart is required.
1726 See also the variable `org-table-auto-blank-field'."
1727 :group 'org-table
1728 :type '(choice
1729 (const :tag "off" nil)
1730 (const :tag "on" t)
1731 (const :tag "on, optimized" optimized)))
1733 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1734 (version<= emacs-version "24.1"))
1735 "Non-nil means cluster self-insert commands for undo when possible.
1736 If this is set, then, like in the Emacs command loop, 20 consecutive
1737 characters will be undone together.
1738 This is configurable, because there is some impact on typing performance."
1739 :group 'org-table
1740 :type 'boolean)
1742 (defcustom org-table-tab-recognizes-table.el t
1743 "Non-nil means TAB will automatically notice a table.el table.
1744 When it sees such a table, it moves point into it and - if necessary -
1745 calls `table-recognize-table'."
1746 :group 'org-table-editing
1747 :type 'boolean)
1749 (defgroup org-link nil
1750 "Options concerning links in Org-mode."
1751 :tag "Org Link"
1752 :group 'org)
1754 (defvar-local org-link-abbrev-alist-local nil
1755 "Buffer-local version of `org-link-abbrev-alist', which see.
1756 The value of this is taken from the #+LINK lines.")
1758 (defcustom org-link-abbrev-alist nil
1759 "Alist of link abbreviations.
1760 The car of each element is a string, to be replaced at the start of a link.
1761 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1762 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1764 [[linkkey:tag][description]]
1766 The `linkkey' must be a word word, starting with a letter, followed
1767 by letters, numbers, `-' or `_'.
1769 If REPLACE is a string, the tag will simply be appended to create the link.
1770 If the string contains \"%s\", the tag will be inserted there. If the string
1771 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1772 at that point (see the function `url-hexify-string'). If the string contains
1773 the specifier \"%(my-function)\", then the custom function `my-function' will
1774 be invoked: this function takes the tag as its only argument and must return
1775 a string.
1777 REPLACE may also be a function that will be called with the tag as the
1778 only argument to create the link, which should be returned as a string.
1780 See the manual for examples."
1781 :group 'org-link
1782 :type '(repeat
1783 (cons
1784 (string :tag "Protocol")
1785 (choice
1786 (string :tag "Format")
1787 (function)))))
1789 (defcustom org-descriptive-links t
1790 "Non-nil means Org will display descriptive links.
1791 E.g. [[http://orgmode.org][Org website]] will be displayed as
1792 \"Org Website\", hiding the link itself and just displaying its
1793 description. When set to nil, Org will display the full links
1794 literally.
1796 You can interactively set the value of this variable by calling
1797 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1798 :group 'org-link
1799 :type 'boolean)
1801 (defcustom org-link-file-path-type 'adaptive
1802 "How the path name in file links should be stored.
1803 Valid values are:
1805 relative Relative to the current directory, i.e. the directory of the file
1806 into which the link is being inserted.
1807 absolute Absolute path, if possible with ~ for home directory.
1808 noabbrev Absolute path, no abbreviation of home directory.
1809 adaptive Use relative path for files in the current directory and sub-
1810 directories of it. For other files, use an absolute path."
1811 :group 'org-link
1812 :type '(choice
1813 (const relative)
1814 (const absolute)
1815 (const noabbrev)
1816 (const adaptive)))
1818 (defvaralias 'org-activate-links 'org-highlight-links)
1819 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1820 "Types of links that should be highlighted in Org-mode files.
1822 This is a list of symbols, each one of them leading to the
1823 highlighting of a certain link type.
1825 You can still open links that are not highlighted.
1827 In principle, it does not hurt to turn on highlighting for all
1828 link types. There may be a small gain when turning off unused
1829 link types. The types are:
1831 bracket The recommended [[link][description]] or [[link]] links with hiding.
1832 angle Links in angular brackets that may contain whitespace like
1833 <bbdb:Carsten Dominik>.
1834 plain Plain links in normal text, no whitespace, like http://google.com.
1835 radio Text that is matched by a radio target, see manual for details.
1836 tag Tag settings in a headline (link to tag search).
1837 date Time stamps (link to calendar).
1838 footnote Footnote labels.
1840 If you set this variable during an Emacs session, use `org-mode-restart'
1841 in the Org buffer so that the change takes effect."
1842 :group 'org-link
1843 :group 'org-appearance
1844 :type '(set :greedy t
1845 (const :tag "Double bracket links" bracket)
1846 (const :tag "Angular bracket links" angle)
1847 (const :tag "Plain text links" plain)
1848 (const :tag "Radio target matches" radio)
1849 (const :tag "Tags" tag)
1850 (const :tag "Timestamps" date)
1851 (const :tag "Footnotes" footnote)))
1853 (defcustom org-make-link-description-function nil
1854 "Function to use for generating link descriptions from links.
1855 When nil, the link location will be used. This function must take
1856 two parameters: the first one is the link, the second one is the
1857 description generated by `org-insert-link'. The function should
1858 return the description to use."
1859 :group 'org-link
1860 :type '(choice (const nil) (function)))
1862 (defgroup org-link-store nil
1863 "Options concerning storing links in Org-mode."
1864 :tag "Org Store Link"
1865 :group 'org-link)
1867 (defcustom org-url-hexify-p t
1868 "When non-nil, hexify URL when creating a link."
1869 :type 'boolean
1870 :version "24.3"
1871 :group 'org-link-store)
1873 (defcustom org-email-link-description-format "Email %c: %.30s"
1874 "Format of the description part of a link to an email or usenet message.
1875 The following %-escapes will be replaced by corresponding information:
1877 %F full \"From\" field
1878 %f name, taken from \"From\" field, address if no name
1879 %T full \"To\" field
1880 %t first name in \"To\" field, address if no name
1881 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1882 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1883 %s subject
1884 %d date
1885 %m message-id.
1887 You may use normal field width specification between the % and the letter.
1888 This is for example useful to limit the length of the subject.
1890 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1891 :group 'org-link-store
1892 :type 'string)
1894 (defcustom org-from-is-user-regexp
1895 (let (r1 r2)
1896 (when (and user-mail-address (not (string= user-mail-address "")))
1897 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1898 (when (and user-full-name (not (string= user-full-name "")))
1899 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1900 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1901 "Regexp matched against the \"From:\" header of an email or usenet message.
1902 It should match if the message is from the user him/herself."
1903 :group 'org-link-store
1904 :type 'regexp)
1906 (defcustom org-context-in-file-links t
1907 "Non-nil means file links from `org-store-link' contain context.
1908 A search string will be added to the file name with :: as separator and
1909 used to find the context when the link is activated by the command
1910 `org-open-at-point'. When this option is t, the entire active region
1911 will be placed in the search string of the file link. If set to a
1912 positive integer, only the first n lines of context will be stored.
1914 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1915 negates this setting for the duration of the command."
1916 :group 'org-link-store
1917 :type '(choice boolean integer))
1919 (defcustom org-keep-stored-link-after-insertion nil
1920 "Non-nil means keep link in list for entire session.
1922 The command `org-store-link' adds a link pointing to the current
1923 location to an internal list. These links accumulate during a session.
1924 The command `org-insert-link' can be used to insert links into any
1925 Org-mode file (offering completion for all stored links). When this
1926 option is nil, every link which has been inserted once using \\[org-insert-link]
1927 will be removed from the list, to make completing the unused links
1928 more efficient."
1929 :group 'org-link-store
1930 :type 'boolean)
1932 (defgroup org-link-follow nil
1933 "Options concerning following links in Org-mode."
1934 :tag "Org Follow Link"
1935 :group 'org-link)
1937 (defcustom org-link-translation-function nil
1938 "Function to translate links with different syntax to Org syntax.
1939 This can be used to translate links created for example by the Planner
1940 or emacs-wiki packages to Org syntax.
1941 The function must accept two parameters, a TYPE containing the link
1942 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1943 which is everything after the link protocol. It should return a cons
1944 with possibly modified values of type and path.
1945 Org contains a function for this, so if you set this variable to
1946 `org-translate-link-from-planner', you should be able follow many
1947 links created by planner."
1948 :group 'org-link-follow
1949 :type '(choice (const nil) (function)))
1951 (defcustom org-follow-link-hook nil
1952 "Hook that is run after a link has been followed."
1953 :group 'org-link-follow
1954 :type 'hook)
1956 (defcustom org-tab-follows-link nil
1957 "Non-nil means on links TAB will follow the link.
1958 Needs to be set before org.el is loaded.
1959 This really should not be used, it does not make sense, and the
1960 implementation is bad."
1961 :group 'org-link-follow
1962 :type 'boolean)
1964 (defcustom org-return-follows-link nil
1965 "Non-nil means on links RET will follow the link.
1966 In tables, the special behavior of RET has precedence."
1967 :group 'org-link-follow
1968 :type 'boolean)
1970 (defcustom org-mouse-1-follows-link
1971 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1972 "Non-nil means mouse-1 on a link will follow the link.
1973 A longer mouse click will still set point. Does not work on XEmacs.
1974 Needs to be set before org.el is loaded."
1975 :group 'org-link-follow
1976 :version "24.4"
1977 :package-version '(Org . "8.3")
1978 :type '(choice
1979 (const :tag "A double click follows the link" double)
1980 (const :tag "Unconditionally follow the link with mouse-1" t)
1981 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1983 (defcustom org-mark-ring-length 4
1984 "Number of different positions to be recorded in the ring.
1985 Changing this requires a restart of Emacs to work correctly."
1986 :group 'org-link-follow
1987 :type 'integer)
1989 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1990 "Non-nil means internal links in Org files must exactly match a headline.
1991 When nil, the link search tries to match a phrase with all words
1992 in the search text."
1993 :group 'org-link-follow
1994 :version "24.1"
1995 :type '(choice
1996 (const :tag "Use fuzzy text search" nil)
1997 (const :tag "Match only exact headline" t)
1998 (const :tag "Match exact headline or query to create it"
1999 query-to-create)))
2001 (defcustom org-link-frame-setup
2002 '((vm . vm-visit-folder-other-frame)
2003 (vm-imap . vm-visit-imap-folder-other-frame)
2004 (gnus . org-gnus-no-new-news)
2005 (file . find-file-other-window)
2006 (wl . wl-other-frame))
2007 "Setup the frame configuration for following links.
2008 When following a link with Emacs, it may often be useful to display
2009 this link in another window or frame. This variable can be used to
2010 set this up for the different types of links.
2011 For VM, use any of
2012 `vm-visit-folder'
2013 `vm-visit-folder-other-window'
2014 `vm-visit-folder-other-frame'
2015 For Gnus, use any of
2016 `gnus'
2017 `gnus-other-frame'
2018 `org-gnus-no-new-news'
2019 For FILE, use any of
2020 `find-file'
2021 `find-file-other-window'
2022 `find-file-other-frame'
2023 For Wanderlust use any of
2024 `wl'
2025 `wl-other-frame'
2026 For the calendar, use the variable `calendar-setup'.
2027 For BBDB, it is currently only possible to display the matches in
2028 another window."
2029 :group 'org-link-follow
2030 :type '(list
2031 (cons (const vm)
2032 (choice
2033 (const vm-visit-folder)
2034 (const vm-visit-folder-other-window)
2035 (const vm-visit-folder-other-frame)))
2036 (cons (const vm-imap)
2037 (choice
2038 (const vm-visit-imap-folder)
2039 (const vm-visit-imap-folder-other-window)
2040 (const vm-visit-imap-folder-other-frame)))
2041 (cons (const gnus)
2042 (choice
2043 (const gnus)
2044 (const gnus-other-frame)
2045 (const org-gnus-no-new-news)))
2046 (cons (const file)
2047 (choice
2048 (const find-file)
2049 (const find-file-other-window)
2050 (const find-file-other-frame)))
2051 (cons (const wl)
2052 (choice
2053 (const wl)
2054 (const wl-other-frame)))))
2056 (defcustom org-display-internal-link-with-indirect-buffer nil
2057 "Non-nil means use indirect buffer to display infile links.
2058 Activating internal links (from one location in a file to another location
2059 in the same file) normally just jumps to the location. When the link is
2060 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2061 is displayed in
2062 another window. When this option is set, the other window actually displays
2063 an indirect buffer clone of the current buffer, to avoid any visibility
2064 changes to the current buffer."
2065 :group 'org-link-follow
2066 :type 'boolean)
2068 (defcustom org-open-non-existing-files nil
2069 "Non-nil means `org-open-file' will open non-existing files.
2070 When nil, an error will be generated.
2071 This variable applies only to external applications because they
2072 might choke on non-existing files. If the link is to a file that
2073 will be opened in Emacs, the variable is ignored."
2074 :group 'org-link-follow
2075 :type 'boolean)
2077 (defcustom org-open-directory-means-index-dot-org nil
2078 "Non-nil means a link to a directory really means to index.org.
2079 When nil, following a directory link will run dired or open a finder/explorer
2080 window on that directory."
2081 :group 'org-link-follow
2082 :type 'boolean)
2084 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2085 "Non-nil means ask for confirmation before executing shell links.
2086 Shell links can be dangerous: just think about a link
2088 [[shell:rm -rf ~/*][Google Search]]
2090 This link would show up in your Org-mode document as \"Google Search\",
2091 but really it would remove your entire home directory.
2092 Therefore we advise against setting this variable to nil.
2093 Just change it to `y-or-n-p' if you want to confirm with a
2094 single keystroke rather than having to type \"yes\"."
2095 :group 'org-link-follow
2096 :type '(choice
2097 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2098 (const :tag "with y-or-n (faster)" y-or-n-p)
2099 (const :tag "no confirmation (dangerous)" nil)))
2100 (put 'org-confirm-shell-link-function
2101 'safe-local-variable
2102 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2104 (defcustom org-confirm-shell-link-not-regexp ""
2105 "A regexp to skip confirmation for shell links."
2106 :group 'org-link-follow
2107 :version "24.1"
2108 :type 'regexp)
2110 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2111 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2112 Elisp links can be dangerous: just think about a link
2114 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2116 This link would show up in your Org-mode document as \"Google Search\",
2117 but really it would remove your entire home directory.
2118 Therefore we advise against setting this variable to nil.
2119 Just change it to `y-or-n-p' if you want to confirm with a
2120 single keystroke rather than having to type \"yes\"."
2121 :group 'org-link-follow
2122 :type '(choice
2123 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2124 (const :tag "with y-or-n (faster)" y-or-n-p)
2125 (const :tag "no confirmation (dangerous)" nil)))
2126 (put 'org-confirm-shell-link-function
2127 'safe-local-variable
2128 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2130 (defcustom org-confirm-elisp-link-not-regexp ""
2131 "A regexp to skip confirmation for Elisp links."
2132 :group 'org-link-follow
2133 :version "24.1"
2134 :type 'regexp)
2136 (defconst org-file-apps-defaults-gnu
2137 '((remote . emacs)
2138 (system . mailcap)
2139 (t . mailcap))
2140 "Default file applications on a UNIX or GNU/Linux system.
2141 See `org-file-apps'.")
2143 (defconst org-file-apps-defaults-macosx
2144 '((remote . emacs)
2145 (t . "open %s")
2146 (system . "open %s")
2147 ("ps.gz" . "gv %s")
2148 ("eps.gz" . "gv %s")
2149 ("dvi" . "xdvi %s")
2150 ("fig" . "xfig %s"))
2151 "Default file applications on a MacOS X system.
2152 The system \"open\" is known as a default, but we use X11 applications
2153 for some files for which the OS does not have a good default.
2154 See `org-file-apps'.")
2156 (defconst org-file-apps-defaults-windowsnt
2157 (list
2158 '(remote . emacs)
2159 (cons t
2160 (list (if (featurep 'xemacs)
2161 'mswindows-shell-execute
2162 'w32-shell-execute)
2163 "open" 'file))
2164 (cons 'system
2165 (list (if (featurep 'xemacs)
2166 'mswindows-shell-execute
2167 'w32-shell-execute)
2168 "open" 'file)))
2169 "Default file applications on a Windows NT system.
2170 The system \"open\" is used for most files.
2171 See `org-file-apps'.")
2173 (defcustom org-file-apps
2174 '((auto-mode . emacs)
2175 ("\\.mm\\'" . default)
2176 ("\\.x?html?\\'" . default)
2177 ("\\.pdf\\'" . default))
2178 "External applications for opening `file:path' items in a document.
2179 Org-mode uses system defaults for different file types, but
2180 you can use this variable to set the application for a given file
2181 extension. The entries in this list are cons cells where the car identifies
2182 files and the cdr the corresponding command. Possible values for the
2183 file identifier are
2184 \"string\" A string as a file identifier can be interpreted in different
2185 ways, depending on its contents:
2187 - Alphanumeric characters only:
2188 Match links with this file extension.
2189 Example: (\"pdf\" . \"evince %s\")
2190 to open PDFs with evince.
2192 - Regular expression: Match links where the
2193 filename matches the regexp. If you want to
2194 use groups here, use shy groups.
2196 Example: (\"\\.x?html\\\\='\" . \"firefox %s\")
2197 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2198 to open *.html and *.xhtml with firefox.
2200 - Regular expression which contains (non-shy) groups:
2201 Match links where the whole link, including \"::\", and
2202 anything after that, matches the regexp.
2203 In a custom command string, %1, %2, etc. are replaced with
2204 the parts of the link that were matched by the groups.
2205 For backwards compatibility, if a command string is given
2206 that does not use any of the group matches, this case is
2207 handled identically to the second one (i.e. match against
2208 file name only).
2209 In a custom lisp form, you can access the group matches with
2210 (match-string n link).
2212 Example: (\"\\.pdf::\\(\\d+\\)\\\\='\" . \"evince -p %1 %s\")
2213 to open [[file:document.pdf::5]] with evince at page 5.
2215 `directory' Matches a directory
2216 `remote' Matches a remote file, accessible through tramp or efs.
2217 Remote files most likely should be visited through Emacs
2218 because external applications cannot handle such paths.
2219 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2220 so all files Emacs knows how to handle. Using this with
2221 command `emacs' will open most files in Emacs. Beware that this
2222 will also open html files inside Emacs, unless you add
2223 (\"html\" . default) to the list as well.
2224 t Default for files not matched by any of the other options.
2225 `system' The system command to open files, like `open' on Windows
2226 and Mac OS X, and mailcap under GNU/Linux. This is the command
2227 that will be selected if you call `C-c C-o' with a double
2228 \\[universal-argument] \\[universal-argument] prefix.
2230 Possible values for the command are:
2231 `emacs' The file will be visited by the current Emacs process.
2232 `default' Use the default application for this file type, which is the
2233 association for t in the list, most likely in the system-specific
2234 part.
2235 This can be used to overrule an unwanted setting in the
2236 system-specific variable.
2237 `system' Use the system command for opening files, like \"open\".
2238 This command is specified by the entry whose car is `system'.
2239 Most likely, the system-specific version of this variable
2240 does define this command, but you can overrule/replace it
2241 here.
2242 string A command to be executed by a shell; %s will be replaced
2243 by the path to the file.
2244 sexp A Lisp form which will be evaluated. The file path will
2245 be available in the Lisp variable `file'.
2246 For more examples, see the system specific constants
2247 `org-file-apps-defaults-macosx'
2248 `org-file-apps-defaults-windowsnt'
2249 `org-file-apps-defaults-gnu'."
2250 :group 'org-link-follow
2251 :type '(repeat
2252 (cons (choice :value ""
2253 (string :tag "Extension")
2254 (const :tag "System command to open files" system)
2255 (const :tag "Default for unrecognized files" t)
2256 (const :tag "Remote file" remote)
2257 (const :tag "Links to a directory" directory)
2258 (const :tag "Any files that have Emacs modes"
2259 auto-mode))
2260 (choice :value ""
2261 (const :tag "Visit with Emacs" emacs)
2262 (const :tag "Use default" default)
2263 (const :tag "Use the system command" system)
2264 (string :tag "Command")
2265 (sexp :tag "Lisp form")))))
2267 (defcustom org-doi-server-url "http://dx.doi.org/"
2268 "The URL of the DOI server."
2269 :type 'string
2270 :version "24.3"
2271 :group 'org-link-follow)
2273 (defgroup org-refile nil
2274 "Options concerning refiling entries in Org-mode."
2275 :tag "Org Refile"
2276 :group 'org)
2278 (defcustom org-directory "~/org"
2279 "Directory with Org files.
2280 This is just a default location to look for Org files. There is no need
2281 at all to put your files into this directory. It is used in the
2282 following situations:
2284 1. When a capture template specifies a target file that is not an
2285 absolute path. The path will then be interpreted relative to
2286 `org-directory'
2287 2. When the value of variable `org-agenda-files' is a single file, any
2288 relative paths in this file will be taken as relative to
2289 `org-directory'."
2290 :group 'org-refile
2291 :group 'org-capture
2292 :type 'directory)
2294 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2295 "Default target for storing notes.
2296 Used as a fall back file for org-capture.el, for templates that
2297 do not specify a target file."
2298 :group 'org-refile
2299 :group 'org-capture
2300 :type 'file)
2302 (defcustom org-goto-interface 'outline
2303 "The default interface to be used for `org-goto'.
2304 Allowed values are:
2305 outline The interface shows an outline of the relevant file
2306 and the correct heading is found by moving through
2307 the outline or by searching with incremental search.
2308 outline-path-completion Headlines in the current buffer are offered via
2309 completion. This is the interface also used by
2310 the refile command."
2311 :group 'org-refile
2312 :type '(choice
2313 (const :tag "Outline" outline)
2314 (const :tag "Outline-path-completion" outline-path-completion)))
2316 (defcustom org-goto-max-level 5
2317 "Maximum target level when running `org-goto' with refile interface."
2318 :group 'org-refile
2319 :type 'integer)
2321 (defcustom org-reverse-note-order nil
2322 "Non-nil means store new notes at the beginning of a file or entry.
2323 When nil, new notes will be filed to the end of a file or entry.
2324 This can also be a list with cons cells of regular expressions that
2325 are matched against file names, and values."
2326 :group 'org-capture
2327 :group 'org-refile
2328 :type '(choice
2329 (const :tag "Reverse always" t)
2330 (const :tag "Reverse never" nil)
2331 (repeat :tag "By file name regexp"
2332 (cons regexp boolean))))
2334 (defcustom org-log-refile nil
2335 "Information to record when a task is refiled.
2337 Possible values are:
2339 nil Don't add anything
2340 time Add a time stamp to the task
2341 note Prompt for a note and add it with template `org-log-note-headings'
2343 This option can also be set with on a per-file-basis with
2345 #+STARTUP: nologrefile
2346 #+STARTUP: logrefile
2347 #+STARTUP: lognoterefile
2349 You can have local logging settings for a subtree by setting the LOGGING
2350 property to one or more of these keywords.
2352 When bulk-refiling from the agenda, the value `note' is forbidden and
2353 will temporarily be changed to `time'."
2354 :group 'org-refile
2355 :group 'org-progress
2356 :version "24.1"
2357 :type '(choice
2358 (const :tag "No logging" nil)
2359 (const :tag "Record timestamp" time)
2360 (const :tag "Record timestamp with note." note)))
2362 (defcustom org-refile-targets nil
2363 "Targets for refiling entries with \\[org-refile].
2364 This is a list of cons cells. Each cell contains:
2365 - a specification of the files to be considered, either a list of files,
2366 or a symbol whose function or variable value will be used to retrieve
2367 a file name or a list of file names. If you use `org-agenda-files' for
2368 that, all agenda files will be scanned for targets. Nil means consider
2369 headings in the current buffer.
2370 - A specification of how to find candidate refile targets. This may be
2371 any of:
2372 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2373 This tag has to be present in all target headlines, inheritance will
2374 not be considered.
2375 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2376 todo keyword.
2377 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2378 headlines that are refiling targets.
2379 - a cons cell (:level . N). Any headline of level N is considered a target.
2380 Note that, when `org-odd-levels-only' is set, level corresponds to
2381 order in hierarchy, not to the number of stars.
2382 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2383 Note that, when `org-odd-levels-only' is set, level corresponds to
2384 order in hierarchy, not to the number of stars.
2386 Each element of this list generates a set of possible targets.
2387 The union of these sets is presented (with completion) to
2388 the user by `org-refile'.
2390 You can set the variable `org-refile-target-verify-function' to a function
2391 to verify each headline found by the simple criteria above.
2393 When this variable is nil, all top-level headlines in the current buffer
2394 are used, equivalent to the value `((nil . (:level . 1))'."
2395 :group 'org-refile
2396 :type '(repeat
2397 (cons
2398 (choice :value org-agenda-files
2399 (const :tag "All agenda files" org-agenda-files)
2400 (const :tag "Current buffer" nil)
2401 (function) (variable) (file))
2402 (choice :tag "Identify target headline by"
2403 (cons :tag "Specific tag" (const :value :tag) (string))
2404 (cons :tag "TODO keyword" (const :value :todo) (string))
2405 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2406 (cons :tag "Level number" (const :value :level) (integer))
2407 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2409 (defcustom org-refile-target-verify-function nil
2410 "Function to verify if the headline at point should be a refile target.
2411 The function will be called without arguments, with point at the
2412 beginning of the headline. It should return t and leave point
2413 where it is if the headline is a valid target for refiling.
2415 If the target should not be selected, the function must return nil.
2416 In addition to this, it may move point to a place from where the search
2417 should be continued. For example, the function may decide that the entire
2418 subtree of the current entry should be excluded and move point to the end
2419 of the subtree."
2420 :group 'org-refile
2421 :type '(choice
2422 (const nil)
2423 (function)))
2425 (defcustom org-refile-use-cache nil
2426 "Non-nil means cache refile targets to speed up the process.
2427 \\<org-mode-map>\
2428 The cache for a particular file will be updated automatically when
2429 the buffer has been killed, or when any of the marker used for flagging
2430 refile targets no longer points at a live buffer.
2431 If you have added new entries to a buffer that might themselves be targets,
2432 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2433 if you find that easier, \
2434 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2435 \\[org-refile]'."
2436 :group 'org-refile
2437 :version "24.1"
2438 :type 'boolean)
2440 (defcustom org-refile-use-outline-path nil
2441 "Non-nil means provide refile targets as paths.
2442 So a level 3 headline will be available as level1/level2/level3.
2444 When the value is `file', also include the file name (without directory)
2445 into the path. In this case, you can also stop the completion after
2446 the file name, to get entries inserted as top level in the file.
2448 When `full-file-path', include the full file path."
2449 :group 'org-refile
2450 :type '(choice
2451 (const :tag "Not" nil)
2452 (const :tag "Yes" t)
2453 (const :tag "Start with file name" file)
2454 (const :tag "Start with full file path" full-file-path)))
2456 (defcustom org-outline-path-complete-in-steps t
2457 "Non-nil means complete the outline path in hierarchical steps.
2458 When Org-mode uses the refile interface to select an outline path
2459 \(see variable `org-refile-use-outline-path'), the completion of
2460 the path can be done in a single go, or it can be done in steps down
2461 the headline hierarchy. Going in steps is probably the best if you
2462 do not use a special completion package like `ido' or `icicles'.
2463 However, when using these packages, going in one step can be very
2464 fast, while still showing the whole path to the entry."
2465 :group 'org-refile
2466 :type 'boolean)
2468 (defcustom org-refile-allow-creating-parent-nodes nil
2469 "Non-nil means allow to create new nodes as refile targets.
2470 New nodes are then created by adding \"/new node name\" to the completion
2471 of an existing node. When the value of this variable is `confirm',
2472 new node creation must be confirmed by the user (recommended).
2473 When nil, the completion must match an existing entry.
2475 Note that, if the new heading is not seen by the criteria
2476 listed in `org-refile-targets', multiple instances of the same
2477 heading would be created by trying again to file under the new
2478 heading."
2479 :group 'org-refile
2480 :type '(choice
2481 (const :tag "Never" nil)
2482 (const :tag "Always" t)
2483 (const :tag "Prompt for confirmation" confirm)))
2485 (defcustom org-refile-active-region-within-subtree nil
2486 "Non-nil means also refile active region within a subtree.
2488 By default `org-refile' doesn't allow refiling regions if they
2489 don't contain a set of subtrees, but it might be convenient to
2490 do so sometimes: in that case, the first line of the region is
2491 converted to a headline before refiling."
2492 :group 'org-refile
2493 :version "24.1"
2494 :type 'boolean)
2496 (defgroup org-todo nil
2497 "Options concerning TODO items in Org-mode."
2498 :tag "Org TODO"
2499 :group 'org)
2501 (defgroup org-progress nil
2502 "Options concerning Progress logging in Org-mode."
2503 :tag "Org Progress"
2504 :group 'org-time)
2506 (defvar org-todo-interpretation-widgets
2507 '((:tag "Sequence (cycling hits every state)" sequence)
2508 (:tag "Type (cycling directly to DONE)" type))
2509 "The available interpretation symbols for customizing `org-todo-keywords'.
2510 Interested libraries should add to this list.")
2512 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2513 "List of TODO entry keyword sequences and their interpretation.
2514 \\<org-mode-map>This is a list of sequences.
2516 Each sequence starts with a symbol, either `sequence' or `type',
2517 indicating if the keywords should be interpreted as a sequence of
2518 action steps, or as different types of TODO items. The first
2519 keywords are states requiring action - these states will select a headline
2520 for inclusion into the global TODO list Org-mode produces. If one of
2521 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2522 signify that no further action is necessary. If \"|\" is not found,
2523 the last keyword is treated as the only DONE state of the sequence.
2525 The command \\[org-todo] cycles an entry through these states, and one
2526 additional state where no keyword is present. For details about this
2527 cycling, see the manual.
2529 TODO keywords and interpretation can also be set on a per-file basis with
2530 the special #+SEQ_TODO and #+TYP_TODO lines.
2532 Each keyword can optionally specify a character for fast state selection
2533 \(in combination with the variable `org-use-fast-todo-selection')
2534 and specifiers for state change logging, using the same syntax that
2535 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2536 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2537 indicates to record a time stamp each time this state is selected.
2539 Each keyword may also specify if a timestamp or a note should be
2540 recorded when entering or leaving the state, by adding additional
2541 characters in the parenthesis after the keyword. This looks like this:
2542 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2543 record only the time of the state change. With X and Y being either
2544 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2545 Y when leaving the state if and only if the *target* state does not
2546 define X. You may omit any of the fast-selection key or X or /Y,
2547 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2549 For backward compatibility, this variable may also be just a list
2550 of keywords. In this case the interpretation (sequence or type) will be
2551 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2552 :group 'org-todo
2553 :group 'org-keywords
2554 :type '(choice
2555 (repeat :tag "Old syntax, just keywords"
2556 (string :tag "Keyword"))
2557 (repeat :tag "New syntax"
2558 (cons
2559 (choice
2560 :tag "Interpretation"
2561 ;;Quick and dirty way to see
2562 ;;`org-todo-interpretations'. This takes the
2563 ;;place of item arguments
2564 :convert-widget
2565 (lambda (widget)
2566 (widget-put widget
2567 :args (mapcar
2568 (lambda (x)
2569 (widget-convert
2570 (cons 'const x)))
2571 org-todo-interpretation-widgets))
2572 widget))
2573 (repeat
2574 (string :tag "Keyword"))))))
2576 (defvar-local org-todo-keywords-1 nil
2577 "All TODO and DONE keywords active in a buffer.")
2578 (defvar org-todo-keywords-for-agenda nil)
2579 (defvar org-done-keywords-for-agenda nil)
2580 (defvar org-todo-keyword-alist-for-agenda nil)
2581 (defvar org-tag-alist-for-agenda nil
2582 "Alist of all tags from all agenda files.")
2583 (defvar org-tag-groups-alist-for-agenda nil
2584 "Alist of all groups tags from all current agenda files.")
2585 (defvar-local org-tag-groups-alist nil)
2586 (defvar org-agenda-contributing-files nil)
2587 (defvar-local org-not-done-keywords nil)
2588 (defvar-local org-done-keywords nil)
2589 (defvar-local org-todo-heads nil)
2590 (defvar-local org-todo-sets nil)
2591 (defvar-local org-todo-log-states nil)
2592 (defvar-local org-todo-kwd-alist nil)
2593 (defvar-local org-todo-key-alist nil)
2594 (defvar-local org-todo-key-trigger nil)
2596 (defcustom org-todo-interpretation 'sequence
2597 "Controls how TODO keywords are interpreted.
2598 This variable is in principle obsolete and is only used for
2599 backward compatibility, if the interpretation of todo keywords is
2600 not given already in `org-todo-keywords'. See that variable for
2601 more information."
2602 :group 'org-todo
2603 :group 'org-keywords
2604 :type '(choice (const sequence)
2605 (const type)))
2607 (defcustom org-use-fast-todo-selection t
2608 "\\<org-mode-map>\
2609 Non-nil means use the fast todo selection scheme with \\[org-todo].
2610 This variable describes if and under what circumstances the cycling
2611 mechanism for TODO keywords will be replaced by a single-key, direct
2612 selection scheme.
2614 When nil, fast selection is never used.
2616 When the symbol `prefix', it will be used when `org-todo' is called
2617 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2618 in an Org-mode buffer, and
2619 `\\[universal-argument] t' in an agenda buffer.
2621 When t, fast selection is used by default. In this case, the prefix
2622 argument forces cycling instead.
2624 In all cases, the special interface is only used if access keys have
2625 actually been assigned by the user, i.e. if keywords in the configuration
2626 are followed by a letter in parenthesis, like TODO(t)."
2627 :group 'org-todo
2628 :type '(choice
2629 (const :tag "Never" nil)
2630 (const :tag "By default" t)
2631 (const :tag "Only with C-u C-c C-t" prefix)))
2633 (defcustom org-provide-todo-statistics t
2634 "Non-nil means update todo statistics after insert and toggle.
2635 ALL-HEADLINES means update todo statistics by including headlines
2636 with no TODO keyword as well, counting them as not done.
2637 A list of TODO keywords means the same, but skip keywords that are
2638 not in this list.
2639 When set to a list of two lists, the first list contains keywords
2640 to consider as TODO keywords, the second list contains keywords
2641 to consider as DONE keywords.
2643 When this is set, todo statistics is updated in the parent of the
2644 current entry each time a todo state is changed."
2645 :group 'org-todo
2646 :type '(choice
2647 (const :tag "Yes, only for TODO entries" t)
2648 (const :tag "Yes, including all entries" all-headlines)
2649 (repeat :tag "Yes, for TODOs in this list"
2650 (string :tag "TODO keyword"))
2651 (list :tag "Yes, for TODOs and DONEs in these lists"
2652 (repeat (string :tag "TODO keyword"))
2653 (repeat (string :tag "DONE keyword")))
2654 (other :tag "No TODO statistics" nil)))
2656 (defcustom org-hierarchical-todo-statistics t
2657 "Non-nil means TODO statistics covers just direct children.
2658 When nil, all entries in the subtree are considered.
2659 This has only an effect if `org-provide-todo-statistics' is set.
2660 To set this to nil for only a single subtree, use a COOKIE_DATA
2661 property and include the word \"recursive\" into the value."
2662 :group 'org-todo
2663 :type 'boolean)
2665 (defcustom org-after-todo-state-change-hook nil
2666 "Hook which is run after the state of a TODO item was changed.
2667 The new state (a string with a TODO keyword, or nil) is available in the
2668 Lisp variable `org-state'."
2669 :group 'org-todo
2670 :type 'hook)
2672 (defvar org-blocker-hook nil
2673 "Hook for functions that are allowed to block a state change.
2675 Functions in this hook should not modify the buffer.
2676 Each function gets as its single argument a property list,
2677 see `org-trigger-hook' for more information about this list.
2679 If any of the functions in this hook returns nil, the state change
2680 is blocked.")
2682 (defvar org-trigger-hook nil
2683 "Hook for functions that are triggered by a state change.
2685 Each function gets as its single argument a property list with at
2686 least the following elements:
2688 (:type type-of-change :position pos-at-entry-start
2689 :from old-state :to new-state)
2691 Depending on the type, more properties may be present.
2693 This mechanism is currently implemented for:
2695 TODO state changes
2696 ------------------
2697 :type todo-state-change
2698 :from previous state (keyword as a string), or nil, or a symbol
2699 `todo' or `done', to indicate the general type of state.
2700 :to new state, like in :from")
2702 (defcustom org-enforce-todo-dependencies nil
2703 "Non-nil means undone TODO entries will block switching the parent to DONE.
2704 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2705 be blocked if any prior sibling is not yet done.
2706 Finally, if the parent is blocked because of ordered siblings of its own,
2707 the child will also be blocked."
2708 :set (lambda (var val)
2709 (set var val)
2710 (if val
2711 (add-hook 'org-blocker-hook
2712 'org-block-todo-from-children-or-siblings-or-parent)
2713 (remove-hook 'org-blocker-hook
2714 'org-block-todo-from-children-or-siblings-or-parent)))
2715 :group 'org-todo
2716 :type 'boolean)
2718 (defcustom org-enforce-todo-checkbox-dependencies nil
2719 "Non-nil means unchecked boxes will block switching the parent to DONE.
2720 When this is nil, checkboxes have no influence on switching TODO states.
2721 When non-nil, you first need to check off all check boxes before the TODO
2722 entry can be switched to DONE.
2723 This variable needs to be set before org.el is loaded, and you need to
2724 restart Emacs after a change to make the change effective. The only way
2725 to change is while Emacs is running is through the customize interface."
2726 :set (lambda (var val)
2727 (set var val)
2728 (if val
2729 (add-hook 'org-blocker-hook
2730 'org-block-todo-from-checkboxes)
2731 (remove-hook 'org-blocker-hook
2732 'org-block-todo-from-checkboxes)))
2733 :group 'org-todo
2734 :type 'boolean)
2736 (defcustom org-treat-insert-todo-heading-as-state-change nil
2737 "Non-nil means inserting a TODO heading is treated as state change.
2738 So when the command \\[org-insert-todo-heading] is used, state change
2739 logging will apply if appropriate. When nil, the new TODO item will
2740 be inserted directly, and no logging will take place."
2741 :group 'org-todo
2742 :type 'boolean)
2744 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2745 "Non-nil means switching TODO states with S-cursor counts as state change.
2746 This is the default behavior. However, setting this to nil allows a
2747 convenient way to select a TODO state and bypass any logging associated
2748 with that."
2749 :group 'org-todo
2750 :type 'boolean)
2752 (defcustom org-todo-state-tags-triggers nil
2753 "Tag changes that should be triggered by TODO state changes.
2754 This is a list. Each entry is
2756 (state-change (tag . flag) .......)
2758 State-change can be a string with a state, and empty string to indicate the
2759 state that has no TODO keyword, or it can be one of the symbols `todo'
2760 or `done', meaning any not-done or done state, respectively."
2761 :group 'org-todo
2762 :group 'org-tags
2763 :type '(repeat
2764 (cons (choice :tag "When changing to"
2765 (const :tag "Not-done state" todo)
2766 (const :tag "Done state" done)
2767 (string :tag "State"))
2768 (repeat
2769 (cons :tag "Tag action"
2770 (string :tag "Tag")
2771 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2773 (defcustom org-log-done nil
2774 "Information to record when a task moves to the DONE state.
2776 Possible values are:
2778 nil Don't add anything, just change the keyword
2779 time Add a time stamp to the task
2780 note Prompt for a note and add it with template `org-log-note-headings'
2782 This option can also be set with on a per-file-basis with
2784 #+STARTUP: nologdone
2785 #+STARTUP: logdone
2786 #+STARTUP: lognotedone
2788 You can have local logging settings for a subtree by setting the LOGGING
2789 property to one or more of these keywords."
2790 :group 'org-todo
2791 :group 'org-progress
2792 :type '(choice
2793 (const :tag "No logging" nil)
2794 (const :tag "Record CLOSED timestamp" time)
2795 (const :tag "Record CLOSED timestamp with note." note)))
2797 ;; Normalize old uses of org-log-done.
2798 (cond
2799 ((eq org-log-done t) (setq org-log-done 'time))
2800 ((and (listp org-log-done) (memq 'done org-log-done))
2801 (setq org-log-done 'note)))
2803 (defcustom org-log-reschedule nil
2804 "Information to record when the scheduling date of a tasks is modified.
2806 Possible values are:
2808 nil Don't add anything, just change the date
2809 time Add a time stamp to the task
2810 note Prompt for a note and add it with template `org-log-note-headings'
2812 This option can also be set with on a per-file-basis with
2814 #+STARTUP: nologreschedule
2815 #+STARTUP: logreschedule
2816 #+STARTUP: lognotereschedule"
2817 :group 'org-todo
2818 :group 'org-progress
2819 :type '(choice
2820 (const :tag "No logging" nil)
2821 (const :tag "Record timestamp" time)
2822 (const :tag "Record timestamp with note." note)))
2824 (defcustom org-log-redeadline nil
2825 "Information to record when the deadline date of a tasks is modified.
2827 Possible values are:
2829 nil Don't add anything, just change the date
2830 time Add a time stamp to the task
2831 note Prompt for a note and add it with template `org-log-note-headings'
2833 This option can also be set with on a per-file-basis with
2835 #+STARTUP: nologredeadline
2836 #+STARTUP: logredeadline
2837 #+STARTUP: lognoteredeadline
2839 You can have local logging settings for a subtree by setting the LOGGING
2840 property to one or more of these keywords."
2841 :group 'org-todo
2842 :group 'org-progress
2843 :type '(choice
2844 (const :tag "No logging" nil)
2845 (const :tag "Record timestamp" time)
2846 (const :tag "Record timestamp with note." note)))
2848 (defcustom org-log-note-clock-out nil
2849 "Non-nil means record a note when clocking out of an item.
2850 This can also be configured on a per-file basis by adding one of
2851 the following lines anywhere in the buffer:
2853 #+STARTUP: lognoteclock-out
2854 #+STARTUP: nolognoteclock-out"
2855 :group 'org-todo
2856 :group 'org-progress
2857 :type 'boolean)
2859 (defcustom org-log-done-with-time t
2860 "Non-nil means the CLOSED time stamp will contain date and time.
2861 When nil, only the date will be recorded."
2862 :group 'org-progress
2863 :type 'boolean)
2865 (defcustom org-log-note-headings
2866 '((done . "CLOSING NOTE %t")
2867 (state . "State %-12s from %-12S %t")
2868 (note . "Note taken on %t")
2869 (reschedule . "Rescheduled from %S on %t")
2870 (delschedule . "Not scheduled, was %S on %t")
2871 (redeadline . "New deadline from %S on %t")
2872 (deldeadline . "Removed deadline, was %S on %t")
2873 (refile . "Refiled on %t")
2874 (clock-out . ""))
2875 "Headings for notes added to entries.
2877 The value is an alist, with the car being a symbol indicating the
2878 note context, and the cdr is the heading to be used. The heading
2879 may also be the empty string. The following placeholders can be
2880 used:
2882 %t a time stamp.
2883 %T an active time stamp instead the default inactive one
2884 %d a short-format time stamp.
2885 %D an active short-format time stamp.
2886 %s the new TODO state or time stamp (inactive), in double quotes.
2887 %S the old TODO state or time stamp (inactive), in double quotes.
2888 %u the user name.
2889 %U full user name.
2891 In fact, it is not a good idea to change the `state' entry,
2892 because Agenda Log mode depends on the format of these entries."
2893 :group 'org-todo
2894 :group 'org-progress
2895 :type '(list :greedy t
2896 (cons (const :tag "Heading when closing an item" done) string)
2897 (cons (const :tag
2898 "Heading when changing todo state (todo sequence only)"
2899 state) string)
2900 (cons (const :tag "Heading when just taking a note" note) string)
2901 (cons (const :tag "Heading when rescheduling" reschedule) string)
2902 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2903 (cons (const :tag "Heading when changing deadline" redeadline) string)
2904 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2905 (cons (const :tag "Heading when refiling" refile) string)
2906 (cons (const :tag "Heading when clocking out" clock-out) string)))
2908 (unless (assq 'note org-log-note-headings)
2909 (push '(note . "%t") org-log-note-headings))
2911 (defcustom org-log-into-drawer nil
2912 "Non-nil means insert state change notes and time stamps into a drawer.
2913 When nil, state changes notes will be inserted after the headline and
2914 any scheduling and clock lines, but not inside a drawer.
2916 The value of this variable should be the name of the drawer to use.
2917 LOGBOOK is proposed as the default drawer for this purpose, you can
2918 also set this to a string to define the drawer of your choice.
2920 A value of t is also allowed, representing \"LOGBOOK\".
2922 A value of t or nil can also be set with on a per-file-basis with
2924 #+STARTUP: logdrawer
2925 #+STARTUP: nologdrawer
2927 If this variable is set, `org-log-state-notes-insert-after-drawers'
2928 will be ignored.
2930 You can set the property LOG_INTO_DRAWER to overrule this setting for
2931 a subtree.
2933 Do not check directly this variable in a Lisp program. Call
2934 function `org-log-into-drawer' instead."
2935 :group 'org-todo
2936 :group 'org-progress
2937 :type '(choice
2938 (const :tag "Not into a drawer" nil)
2939 (const :tag "LOGBOOK" t)
2940 (string :tag "Other")))
2942 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2944 (defun org-log-into-drawer ()
2945 "Name of the log drawer, as a string, or nil.
2946 This is the value of `org-log-into-drawer'. However, if the
2947 current entry has or inherits a LOG_INTO_DRAWER property, it will
2948 be used instead of the default value."
2949 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2950 (cond ((equal p "nil") nil)
2951 ((equal p "t") "LOGBOOK")
2952 ((stringp p) p)
2953 (p "LOGBOOK")
2954 ((stringp org-log-into-drawer) org-log-into-drawer)
2955 (org-log-into-drawer "LOGBOOK"))))
2957 (defcustom org-log-state-notes-insert-after-drawers nil
2958 "Non-nil means insert state change notes after any drawers in entry.
2959 Only the drawers that *immediately* follow the headline and the
2960 deadline/scheduled line are skipped.
2961 When nil, insert notes right after the heading and perhaps the line
2962 with deadline/scheduling if present.
2964 This variable will have no effect if `org-log-into-drawer' is
2965 set."
2966 :group 'org-todo
2967 :group 'org-progress
2968 :type 'boolean)
2970 (defcustom org-log-states-order-reversed t
2971 "Non-nil means the latest state note will be directly after heading.
2972 When nil, the state change notes will be ordered according to time.
2974 This option can also be set with on a per-file-basis with
2976 #+STARTUP: logstatesreversed
2977 #+STARTUP: nologstatesreversed"
2978 :group 'org-todo
2979 :group 'org-progress
2980 :type 'boolean)
2982 (defcustom org-todo-repeat-to-state nil
2983 "The TODO state to which a repeater should return the repeating task.
2984 By default this is the first task in a TODO sequence, or the previous state
2985 in a TODO_TYP set. But you can specify another task here.
2986 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2987 :group 'org-todo
2988 :version "24.1"
2989 :type '(choice (const :tag "Head of sequence" nil)
2990 (string :tag "Specific state")))
2992 (defcustom org-log-repeat 'time
2993 "Non-nil means record moving through the DONE state when triggering repeat.
2994 An auto-repeating task is immediately switched back to TODO when
2995 marked DONE. If you are not logging state changes (by adding \"@\"
2996 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2997 record a closing note, there will be no record of the task moving
2998 through DONE. This variable forces taking a note anyway.
3000 nil Don't force a record
3001 time Record a time stamp
3002 note Prompt for a note and add it with template `org-log-note-headings'
3004 This option can also be set with on a per-file-basis with
3006 #+STARTUP: nologrepeat
3007 #+STARTUP: logrepeat
3008 #+STARTUP: lognoterepeat
3010 You can have local logging settings for a subtree by setting the LOGGING
3011 property to one or more of these keywords."
3012 :group 'org-todo
3013 :group 'org-progress
3014 :type '(choice
3015 (const :tag "Don't force a record" nil)
3016 (const :tag "Force recording the DONE state" time)
3017 (const :tag "Force recording a note with the DONE state" note)))
3020 (defgroup org-priorities nil
3021 "Priorities in Org-mode."
3022 :tag "Org Priorities"
3023 :group 'org-todo)
3025 (defcustom org-enable-priority-commands t
3026 "Non-nil means priority commands are active.
3027 When nil, these commands will be disabled, so that you never accidentally
3028 set a priority."
3029 :group 'org-priorities
3030 :type 'boolean)
3032 (defcustom org-highest-priority ?A
3033 "The highest priority of TODO items. A character like ?A, ?B etc.
3034 Must have a smaller ASCII number than `org-lowest-priority'."
3035 :group 'org-priorities
3036 :type 'character)
3038 (defcustom org-lowest-priority ?C
3039 "The lowest priority of TODO items. A character like ?A, ?B etc.
3040 Must have a larger ASCII number than `org-highest-priority'."
3041 :group 'org-priorities
3042 :type 'character)
3044 (defcustom org-default-priority ?B
3045 "The default priority of TODO items.
3046 This is the priority an item gets if no explicit priority is given.
3047 When starting to cycle on an empty priority the first step in the cycle
3048 depends on `org-priority-start-cycle-with-default'. The resulting first
3049 step priority must not exceed the range from `org-highest-priority' to
3050 `org-lowest-priority' which means that `org-default-priority' has to be
3051 in this range exclusive or inclusive the range boundaries. Else the
3052 first step refuses to set the default and the second will fall back
3053 to (depending on the command used) the highest or lowest priority."
3054 :group 'org-priorities
3055 :type 'character)
3057 (defcustom org-priority-start-cycle-with-default t
3058 "Non-nil means start with default priority when starting to cycle.
3059 When this is nil, the first step in the cycle will be (depending on the
3060 command used) one higher or lower than the default priority.
3061 See also `org-default-priority'."
3062 :group 'org-priorities
3063 :type 'boolean)
3065 (defcustom org-get-priority-function nil
3066 "Function to extract the priority from a string.
3067 The string is normally the headline. If this is nil Org computes the
3068 priority from the priority cookie like [#A] in the headline. It returns
3069 an integer, increasing by 1000 for each priority level.
3070 The user can set a different function here, which should take a string
3071 as an argument and return the numeric priority."
3072 :group 'org-priorities
3073 :version "24.1"
3074 :type '(choice
3075 (const nil)
3076 (function)))
3078 (defgroup org-time nil
3079 "Options concerning time stamps and deadlines in Org-mode."
3080 :tag "Org Time"
3081 :group 'org)
3083 (defcustom org-time-stamp-rounding-minutes '(0 5)
3084 "Number of minutes to round time stamps to.
3085 \\<org-mode-map>\
3086 These are two values, the first applies when first creating a time stamp.
3087 The second applies when changing it with the commands `S-up' and `S-down'.
3088 When changing the time stamp, this means that it will change in steps
3089 of N minutes, as given by the second value.
3091 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3092 numbers should be factors of 60, so for example 5, 10, 15.
3094 When this is larger than 1, you can still force an exact time stamp by using
3095 a double prefix argument to a time stamp command like \
3096 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3097 and by using a prefix arg to `S-up/down' to specify the exact number
3098 of minutes to shift."
3099 :group 'org-time
3100 :get (lambda (var) ; Make sure both elements are there
3101 (if (integerp (default-value var))
3102 (list (default-value var) 5)
3103 (default-value var)))
3104 :type '(list
3105 (integer :tag "when inserting times")
3106 (integer :tag "when modifying times")))
3108 ;; Normalize old customizations of this variable.
3109 (when (integerp org-time-stamp-rounding-minutes)
3110 (setq org-time-stamp-rounding-minutes
3111 (list org-time-stamp-rounding-minutes
3112 org-time-stamp-rounding-minutes)))
3114 (defcustom org-display-custom-times nil
3115 "Non-nil means overlay custom formats over all time stamps.
3116 The formats are defined through the variable `org-time-stamp-custom-formats'.
3117 To turn this on on a per-file basis, insert anywhere in the file:
3118 #+STARTUP: customtime"
3119 :group 'org-time
3120 :set 'set-default
3121 :type 'sexp)
3122 (make-variable-buffer-local 'org-display-custom-times)
3124 (defcustom org-time-stamp-custom-formats
3125 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3126 "Custom formats for time stamps. See `format-time-string' for the syntax.
3127 These are overlaid over the default ISO format if the variable
3128 `org-display-custom-times' is set. Time like %H:%M should be at the
3129 end of the second format. The custom formats are also honored by export
3130 commands, if custom time display is turned on at the time of export."
3131 :group 'org-time
3132 :type 'sexp)
3134 (defun org-time-stamp-format (&optional long inactive)
3135 "Get the right format for a time string."
3136 (let ((f (if long (cdr org-time-stamp-formats)
3137 (car org-time-stamp-formats))))
3138 (if inactive
3139 (concat "[" (substring f 1 -1) "]")
3140 f)))
3142 (defcustom org-time-clocksum-format
3143 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3144 "The format string used when creating CLOCKSUM lines.
3145 This is also used when Org mode generates a time duration.
3147 The value can be a single format string containing two
3148 %-sequences, which will be filled with the number of hours and
3149 minutes in that order.
3151 Alternatively, the value can be a plist associating any of the
3152 keys :years, :months, :weeks, :days, :hours or :minutes with
3153 format strings. The time duration is formatted using only the
3154 time components that are needed and concatenating the results.
3155 If a time unit in absent, it falls back to the next smallest
3156 unit.
3158 The keys :require-years, :require-months, :require-days,
3159 :require-weeks, :require-hours, :require-minutes are also
3160 meaningful. A non-nil value for these keys indicates that the
3161 corresponding time component should always be included, even if
3162 its value is 0.
3165 For example,
3167 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3168 :require-minutes t)
3170 means durations longer than a day will be expressed in days,
3171 hours and minutes, and durations less than a day will always be
3172 expressed in hours and minutes (even for durations less than an
3173 hour).
3175 The value
3177 (:days \"%dd\" :minutes \"%dm\")
3179 means durations longer than a day will be expressed in days and
3180 minutes, and durations less than a day will be expressed entirely
3181 in minutes (even for durations longer than an hour)."
3182 :group 'org-time
3183 :group 'org-clock
3184 :version "24.4"
3185 :package-version '(Org . "8.0")
3186 :type '(choice (string :tag "Format string")
3187 (set :tag "Plist"
3188 (group :inline t (const :tag "Years" :years)
3189 (string :tag "Format string"))
3190 (group :inline t
3191 (const :tag "Always show years" :require-years)
3192 (const t))
3193 (group :inline t (const :tag "Months" :months)
3194 (string :tag "Format string"))
3195 (group :inline t
3196 (const :tag "Always show months" :require-months)
3197 (const t))
3198 (group :inline t (const :tag "Weeks" :weeks)
3199 (string :tag "Format string"))
3200 (group :inline t
3201 (const :tag "Always show weeks" :require-weeks)
3202 (const t))
3203 (group :inline t (const :tag "Days" :days)
3204 (string :tag "Format string"))
3205 (group :inline t
3206 (const :tag "Always show days" :require-days)
3207 (const t))
3208 (group :inline t (const :tag "Hours" :hours)
3209 (string :tag "Format string"))
3210 (group :inline t
3211 (const :tag "Always show hours" :require-hours)
3212 (const t))
3213 (group :inline t (const :tag "Minutes" :minutes)
3214 (string :tag "Format string"))
3215 (group :inline t
3216 (const :tag "Always show minutes" :require-minutes)
3217 (const t)))))
3219 (defcustom org-time-clocksum-use-fractional nil
3220 "When non-nil, \\[org-clock-display] uses fractional times.
3221 See `org-time-clocksum-format' for more on time clock formats."
3222 :group 'org-time
3223 :group 'org-clock
3224 :version "24.3"
3225 :type 'boolean)
3227 (defcustom org-time-clocksum-use-effort-durations nil
3228 "When non-nil, \\[org-clock-display] uses effort durations.
3229 E.g. by default, one day is considered to be a 8 hours effort,
3230 so a task that has been clocked for 16 hours will be displayed
3231 as during 2 days in the clock display or in the clocktable.
3233 See `org-effort-durations' on how to set effort durations
3234 and `org-time-clocksum-format' for more on time clock formats."
3235 :group 'org-time
3236 :group 'org-clock
3237 :version "24.4"
3238 :package-version '(Org . "8.0")
3239 :type 'boolean)
3241 (defcustom org-time-clocksum-fractional-format "%.2f"
3242 "The format string used when creating CLOCKSUM lines,
3243 or when Org mode generates a time duration, if
3244 `org-time-clocksum-use-fractional' is enabled.
3246 The value can be a single format string containing one
3247 %-sequence, which will be filled with the number of hours as
3248 a float.
3250 Alternatively, the value can be a plist associating any of the
3251 keys :years, :months, :weeks, :days, :hours or :minutes with
3252 a format string. The time duration is formatted using the
3253 largest time unit which gives a non-zero integer part. If all
3254 specified formats have zero integer part, the smallest time unit
3255 is used."
3256 :group 'org-time
3257 :type '(choice (string :tag "Format string")
3258 (set (group :inline t (const :tag "Years" :years)
3259 (string :tag "Format string"))
3260 (group :inline t (const :tag "Months" :months)
3261 (string :tag "Format string"))
3262 (group :inline t (const :tag "Weeks" :weeks)
3263 (string :tag "Format string"))
3264 (group :inline t (const :tag "Days" :days)
3265 (string :tag "Format string"))
3266 (group :inline t (const :tag "Hours" :hours)
3267 (string :tag "Format string"))
3268 (group :inline t (const :tag "Minutes" :minutes)
3269 (string :tag "Format string")))))
3271 (defcustom org-deadline-warning-days 14
3272 "Number of days before expiration during which a deadline becomes active.
3273 This variable governs the display in sparse trees and in the agenda.
3274 When 0 or negative, it means use this number (the absolute value of it)
3275 even if a deadline has a different individual lead time specified.
3277 Custom commands can set this variable in the options section."
3278 :group 'org-time
3279 :group 'org-agenda-daily/weekly
3280 :type 'integer)
3282 (defcustom org-scheduled-delay-days 0
3283 "Number of days before a scheduled item becomes active.
3284 This variable governs the display in sparse trees and in the agenda.
3285 The default value (i.e. 0) means: don't delay scheduled item.
3286 When negative, it means use this number (the absolute value of it)
3287 even if a scheduled item has a different individual delay time
3288 specified.
3290 Custom commands can set this variable in the options section."
3291 :group 'org-time
3292 :group 'org-agenda-daily/weekly
3293 :version "24.4"
3294 :package-version '(Org . "8.0")
3295 :type 'integer)
3297 (defcustom org-read-date-prefer-future t
3298 "Non-nil means assume future for incomplete date input from user.
3299 This affects the following situations:
3300 1. The user gives a month but not a year.
3301 For example, if it is April and you enter \"feb 2\", this will be read
3302 as Feb 2, *next* year. \"May 5\", however, will be this year.
3303 2. The user gives a day, but no month.
3304 For example, if today is the 15th, and you enter \"3\", Org-mode will
3305 read this as the third of *next* month. However, if you enter \"17\",
3306 it will be considered as *this* month.
3308 If you set this variable to the symbol `time', then also the following
3309 will work:
3311 3. If the user gives a time.
3312 If the time is before now, it will be interpreted as tomorrow.
3314 Currently none of this works for ISO week specifications.
3316 When this option is nil, the current day, month and year will always be
3317 used as defaults.
3319 See also `org-agenda-jump-prefer-future'."
3320 :group 'org-time
3321 :type '(choice
3322 (const :tag "Never" nil)
3323 (const :tag "Check month and day" t)
3324 (const :tag "Check month, day, and time" time)))
3326 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3327 "Should the agenda jump command prefer the future for incomplete dates?
3328 The default is to do the same as configured in `org-read-date-prefer-future'.
3329 But you can also set a deviating value here.
3330 This may t or nil, or the symbol `org-read-date-prefer-future'."
3331 :group 'org-agenda
3332 :group 'org-time
3333 :version "24.1"
3334 :type '(choice
3335 (const :tag "Use org-read-date-prefer-future"
3336 org-read-date-prefer-future)
3337 (const :tag "Never" nil)
3338 (const :tag "Always" t)))
3340 (defcustom org-read-date-force-compatible-dates t
3341 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3343 Depending on the system Emacs is running on, certain dates cannot
3344 be represented with the type used internally to represent time.
3345 Dates between 1970-1-1 and 2038-1-1 can always be represented
3346 correctly. Some systems allow for earlier dates, some for later,
3347 some for both. One way to find out it to insert any date into an
3348 Org buffer, putting the cursor on the year and hitting S-up and
3349 S-down to test the range.
3351 When this variable is set to t, the date/time prompt will not let
3352 you specify dates outside the 1970-2037 range, so it is certain that
3353 these dates will work in whatever version of Emacs you are
3354 running, and also that you can move a file from one Emacs implementation
3355 to another. WHenever Org is forcing the year for you, it will display
3356 a message and beep.
3358 When this variable is nil, Org will check if the date is
3359 representable in the specific Emacs implementation you are using.
3360 If not, it will force a year, usually the current year, and beep
3361 to remind you. Currently this setting is not recommended because
3362 the likelihood that you will open your Org files in an Emacs that
3363 has limited date range is not negligible.
3365 A workaround for this problem is to use diary sexp dates for time
3366 stamps outside of this range."
3367 :group 'org-time
3368 :version "24.1"
3369 :type 'boolean)
3371 (defcustom org-read-date-display-live t
3372 "Non-nil means display current interpretation of date prompt live.
3373 This display will be in an overlay, in the minibuffer."
3374 :group 'org-time
3375 :type 'boolean)
3377 (defcustom org-read-date-popup-calendar t
3378 "Non-nil means pop up a calendar when prompting for a date.
3379 In the calendar, the date can be selected with mouse-1. However, the
3380 minibuffer will also be active, and you can simply enter the date as well.
3381 When nil, only the minibuffer will be available."
3382 :group 'org-time
3383 :type 'boolean)
3384 (org-defvaralias 'org-popup-calendar-for-date-prompt
3385 'org-read-date-popup-calendar)
3387 (make-obsolete-variable
3388 'org-read-date-minibuffer-setup-hook
3389 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3390 (defcustom org-read-date-minibuffer-setup-hook nil
3391 "Hook to be used to set up keys for the date/time interface.
3392 Add key definitions to `minibuffer-local-map', which will be a
3393 temporary copy.
3395 WARNING: This option is obsolete, you should use
3396 `org-read-date-minibuffer-local-map' to set up keys."
3397 :group 'org-time
3398 :type 'hook)
3400 (defcustom org-extend-today-until 0
3401 "The hour when your day really ends. Must be an integer.
3402 This has influence for the following applications:
3403 - When switching the agenda to \"today\". It it is still earlier than
3404 the time given here, the day recognized as TODAY is actually yesterday.
3405 - When a date is read from the user and it is still before the time given
3406 here, the current date and time will be assumed to be yesterday, 23:59.
3407 Also, timestamps inserted in capture templates follow this rule.
3409 IMPORTANT: This is a feature whose implementation is and likely will
3410 remain incomplete. Really, it is only here because past midnight seems to
3411 be the favorite working time of John Wiegley :-)"
3412 :group 'org-time
3413 :type 'integer)
3415 (defcustom org-use-effective-time nil
3416 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3417 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3418 \"effective time\" of any timestamps between midnight and 8am will be
3419 23:59 of the previous day."
3420 :group 'org-time
3421 :version "24.1"
3422 :type 'boolean)
3424 (defcustom org-use-last-clock-out-time-as-effective-time nil
3425 "When non-nil, use the last clock out time for `org-todo'.
3426 Note that this option has precedence over the combined use of
3427 `org-use-effective-time' and `org-extend-today-until'."
3428 :group 'org-time
3429 :version "24.4"
3430 :package-version '(Org . "8.0")
3431 :type 'boolean)
3433 (defcustom org-edit-timestamp-down-means-later nil
3434 "Non-nil means S-down will increase the time in a time stamp.
3435 When nil, S-up will increase."
3436 :group 'org-time
3437 :type 'boolean)
3439 (defcustom org-calendar-follow-timestamp-change t
3440 "Non-nil means make the calendar window follow timestamp changes.
3441 When a timestamp is modified and the calendar window is visible, it will be
3442 moved to the new date."
3443 :group 'org-time
3444 :type 'boolean)
3446 (defgroup org-tags nil
3447 "Options concerning tags in Org-mode."
3448 :tag "Org Tags"
3449 :group 'org)
3451 (defcustom org-tag-alist nil
3452 "List of tags allowed in Org-mode files.
3453 When this list is nil, Org-mode will base TAG input on what is already in the
3454 buffer.
3455 The value of this variable is an alist, the car of each entry must be a
3456 keyword as a string, the cdr may be a character that is used to select
3457 that tag through the fast-tag-selection interface.
3458 See the manual for details."
3459 :group 'org-tags
3460 :type '(repeat
3461 (choice
3462 (cons (string :tag "Tag name")
3463 (character :tag "Access char"))
3464 (list :tag "Start radio group"
3465 (const :startgroup)
3466 (option (string :tag "Group description")))
3467 (list :tag "Start tag group, non distinct"
3468 (const :startgrouptag)
3469 (option (string :tag "Group description")))
3470 (list :tag "Group tags delimiter"
3471 (const :grouptags))
3472 (list :tag "End radio group"
3473 (const :endgroup)
3474 (option (string :tag "Group description")))
3475 (list :tag "End tag group, non distinct"
3476 (const :endgrouptag)
3477 (option (string :tag "Group description")))
3478 (const :tag "New line" (:newline)))))
3480 (defcustom org-tag-persistent-alist nil
3481 "List of tags that will always appear in all Org-mode files.
3482 This is in addition to any in buffer settings or customizations
3483 of `org-tag-alist'.
3484 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3485 The value of this variable is an alist, the car of each entry must be a
3486 keyword as a string, the cdr may be a character that is used to select
3487 that tag through the fast-tag-selection interface.
3488 See the manual for details.
3489 To disable these tags on a per-file basis, insert anywhere in the file:
3490 #+STARTUP: noptag"
3491 :group 'org-tags
3492 :type '(repeat
3493 (choice
3494 (cons (string :tag "Tag name")
3495 (character :tag "Access char"))
3496 (const :tag "Start radio group" (:startgroup))
3497 (const :tag "Group tags delimiter" (:grouptags))
3498 (const :tag "End radio group" (:endgroup))
3499 (const :tag "New line" (:newline)))))
3501 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3502 "If non-nil, always offer completion for all tags of all agenda files.
3503 Instead of customizing this variable directly, you might want to
3504 set it locally for capture buffers, because there no list of
3505 tags in that file can be created dynamically (there are none).
3507 (add-hook \\='org-capture-mode-hook
3508 (lambda ()
3509 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3510 :group 'org-tags
3511 :version "24.1"
3512 :type 'boolean)
3514 (defvar org-file-tags nil
3515 "List of tags that can be inherited by all entries in the file.
3516 The tags will be inherited if the variable `org-use-tag-inheritance'
3517 says they should be.
3518 This variable is populated from #+FILETAGS lines.")
3520 (defcustom org-use-fast-tag-selection 'auto
3521 "Non-nil means use fast tag selection scheme.
3522 This is a special interface to select and deselect tags with single keys.
3523 When nil, fast selection is never used.
3524 When the symbol `auto', fast selection is used if and only if selection
3525 characters for tags have been configured, either through the variable
3526 `org-tag-alist' or through a #+TAGS line in the buffer.
3527 When t, fast selection is always used and selection keys are assigned
3528 automatically if necessary."
3529 :group 'org-tags
3530 :type '(choice
3531 (const :tag "Always" t)
3532 (const :tag "Never" nil)
3533 (const :tag "When selection characters are configured" auto)))
3535 (defcustom org-fast-tag-selection-single-key nil
3536 "Non-nil means fast tag selection exits after first change.
3537 When nil, you have to press RET to exit it.
3538 During fast tag selection, you can toggle this flag with `C-c'.
3539 This variable can also have the value `expert'. In this case, the window
3540 displaying the tags menu is not even shown, until you press C-c again."
3541 :group 'org-tags
3542 :type '(choice
3543 (const :tag "No" nil)
3544 (const :tag "Yes" t)
3545 (const :tag "Expert" expert)))
3547 (defvar org-fast-tag-selection-include-todo nil
3548 "Non-nil means fast tags selection interface will also offer TODO states.
3549 This is an undocumented feature, you should not rely on it.")
3551 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3552 "The column to which tags should be indented in a headline.
3553 If this number is positive, it specifies the column. If it is negative,
3554 it means that the tags should be flushright to that column. For example,
3555 -80 works well for a normal 80 character screen.
3556 When 0, place tags directly after headline text, with only one space in
3557 between."
3558 :group 'org-tags
3559 :type 'integer)
3561 (defcustom org-auto-align-tags t
3562 "Non-nil keeps tags aligned when modifying headlines.
3563 Some operations (i.e. demoting) change the length of a headline and
3564 therefore shift the tags around. With this option turned on, after
3565 each such operation the tags are again aligned to `org-tags-column'."
3566 :group 'org-tags
3567 :type 'boolean)
3569 (defcustom org-use-tag-inheritance t
3570 "Non-nil means tags in levels apply also for sublevels.
3571 When nil, only the tags directly given in a specific line apply there.
3572 This may also be a list of tags that should be inherited, or a regexp that
3573 matches tags that should be inherited. Additional control is possible
3574 with the variable `org-tags-exclude-from-inheritance' which gives an
3575 explicit list of tags to be excluded from inheritance, even if the value of
3576 `org-use-tag-inheritance' would select it for inheritance.
3578 If this option is t, a match early-on in a tree can lead to a large
3579 number of matches in the subtree when constructing the agenda or creating
3580 a sparse tree. If you only want to see the first match in a tree during
3581 a search, check out the variable `org-tags-match-list-sublevels'."
3582 :group 'org-tags
3583 :type '(choice
3584 (const :tag "Not" nil)
3585 (const :tag "Always" t)
3586 (repeat :tag "Specific tags" (string :tag "Tag"))
3587 (regexp :tag "Tags matched by regexp")))
3589 (defcustom org-tags-exclude-from-inheritance nil
3590 "List of tags that should never be inherited.
3591 This is a way to exclude a few tags from inheritance. For way to do
3592 the opposite, to actively allow inheritance for selected tags,
3593 see the variable `org-use-tag-inheritance'."
3594 :group 'org-tags
3595 :type '(repeat (string :tag "Tag")))
3597 (defun org-tag-inherit-p (tag)
3598 "Check if TAG is one that should be inherited."
3599 (cond
3600 ((member tag org-tags-exclude-from-inheritance) nil)
3601 ((eq org-use-tag-inheritance t) t)
3602 ((not org-use-tag-inheritance) nil)
3603 ((stringp org-use-tag-inheritance)
3604 (string-match org-use-tag-inheritance tag))
3605 ((listp org-use-tag-inheritance)
3606 (member tag org-use-tag-inheritance))
3607 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3609 (defcustom org-tags-match-list-sublevels t
3610 "Non-nil means list also sublevels of headlines matching a search.
3611 This variable applies to tags/property searches, and also to stuck
3612 projects because this search is based on a tags match as well.
3614 When set to the symbol `indented', sublevels are indented with
3615 leading dots.
3617 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3618 the sublevels of a headline matching a tag search often also match
3619 the same search. Listing all of them can create very long lists.
3620 Setting this variable to nil causes subtrees of a match to be skipped.
3622 This variable is semi-obsolete and probably should always be true. It
3623 is better to limit inheritance to certain tags using the variables
3624 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3625 :group 'org-tags
3626 :type '(choice
3627 (const :tag "No, don't list them" nil)
3628 (const :tag "Yes, do list them" t)
3629 (const :tag "List them, indented with leading dots" indented)))
3631 (defcustom org-tags-sort-function nil
3632 "When set, tags are sorted using this function as a comparator."
3633 :group 'org-tags
3634 :type '(choice
3635 (const :tag "No sorting" nil)
3636 (const :tag "Alphabetical" string<)
3637 (const :tag "Reverse alphabetical" string>)
3638 (function :tag "Custom function" nil)))
3640 (defvar org-tags-history nil
3641 "History of minibuffer reads for tags.")
3642 (defvar org-last-tags-completion-table nil
3643 "The last used completion table for tags.")
3644 (defvar org-after-tags-change-hook nil
3645 "Hook that is run after the tags in a line have changed.")
3647 (defgroup org-properties nil
3648 "Options concerning properties in Org-mode."
3649 :tag "Org Properties"
3650 :group 'org)
3652 (defcustom org-property-format "%-10s %s"
3653 "How property key/value pairs should be formatted by `indent-line'.
3654 When `indent-line' hits a property definition, it will format the line
3655 according to this format, mainly to make sure that the values are
3656 lined-up with respect to each other."
3657 :group 'org-properties
3658 :type 'string)
3660 (defcustom org-properties-postprocess-alist nil
3661 "Alist of properties and functions to adjust inserted values.
3662 Elements of this alist must be of the form
3664 ([string] [function])
3666 where [string] must be a property name and [function] must be a
3667 lambda expression: this lambda expression must take one argument,
3668 the value to adjust, and return the new value as a string.
3670 For example, this element will allow the property \"Remaining\"
3671 to be updated wrt the relation between the \"Effort\" property
3672 and the clock summary:
3674 ((\"Remaining\" (lambda(value)
3675 (let ((clocksum (org-clock-sum-current-item))
3676 (effort (org-duration-string-to-minutes
3677 (org-entry-get (point) \"Effort\"))))
3678 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3679 :group 'org-properties
3680 :version "24.1"
3681 :type '(alist :key-type (string :tag "Property")
3682 :value-type (function :tag "Function")))
3684 (defcustom org-use-property-inheritance nil
3685 "Non-nil means properties apply also for sublevels.
3687 This setting is chiefly used during property searches. Turning it on can
3688 cause significant overhead when doing a search, which is why it is not
3689 on by default.
3691 When nil, only the properties directly given in the current entry count.
3692 When t, every property is inherited. The value may also be a list of
3693 properties that should have inheritance, or a regular expression matching
3694 properties that should be inherited.
3696 However, note that some special properties use inheritance under special
3697 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3698 and the properties ending in \"_ALL\" when they are used as descriptor
3699 for valid values of a property.
3701 Note for programmers:
3702 When querying an entry with `org-entry-get', you can control if inheritance
3703 should be used. By default, `org-entry-get' looks only at the local
3704 properties. You can request inheritance by setting the inherit argument
3705 to t (to force inheritance) or to `selective' (to respect the setting
3706 in this variable)."
3707 :group 'org-properties
3708 :type '(choice
3709 (const :tag "Not" nil)
3710 (const :tag "Always" t)
3711 (repeat :tag "Specific properties" (string :tag "Property"))
3712 (regexp :tag "Properties matched by regexp")))
3714 (defun org-property-inherit-p (property)
3715 "Check if PROPERTY is one that should be inherited."
3716 (cond
3717 ((eq org-use-property-inheritance t) t)
3718 ((not org-use-property-inheritance) nil)
3719 ((stringp org-use-property-inheritance)
3720 (string-match org-use-property-inheritance property))
3721 ((listp org-use-property-inheritance)
3722 (member property org-use-property-inheritance))
3723 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3725 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3726 "The default column format, if no other format has been defined.
3727 This variable can be set on the per-file basis by inserting a line
3729 #+COLUMNS: %25ITEM ....."
3730 :group 'org-properties
3731 :type 'string)
3733 (defcustom org-columns-ellipses ".."
3734 "The ellipses to be used when a field in column view is truncated.
3735 When this is the empty string, as many characters as possible are shown,
3736 but then there will be no visual indication that the field has been truncated.
3737 When this is a string of length N, the last N characters of a truncated
3738 field are replaced by this string. If the column is narrower than the
3739 ellipses string, only part of the ellipses string will be shown."
3740 :group 'org-properties
3741 :type 'string)
3743 (defcustom org-columns-modify-value-for-display-function nil
3744 "Function that modifies values for display in column view.
3745 For example, it can be used to cut out a certain part from a time stamp.
3746 The function must take 2 arguments:
3748 column-title The title of the column (*not* the property name)
3749 value The value that should be modified.
3751 The function should return the value that should be displayed,
3752 or nil if the normal value should be used."
3753 :group 'org-properties
3754 :type '(choice (const nil) (function)))
3756 (defconst org-global-properties-fixed
3757 '(("VISIBILITY_ALL" . "folded children content all")
3758 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3759 "List of property/value pairs that can be inherited by any entry.
3761 These are fixed values, for the preset properties. The user variable
3762 that can be used to add to this list is `org-global-properties'.
3764 The entries in this list are cons cells where the car is a property
3765 name and cdr is a string with the value. If the value represents
3766 multiple items like an \"_ALL\" property, separate the items by
3767 spaces.")
3769 (defcustom org-global-properties nil
3770 "List of property/value pairs that can be inherited by any entry.
3772 This list will be combined with the constant `org-global-properties-fixed'.
3774 The entries in this list are cons cells where the car is a property
3775 name and cdr is a string with the value.
3777 You can set buffer-local values for the same purpose in the variable
3778 `org-file-properties' this by adding lines like
3780 #+PROPERTY: NAME VALUE"
3781 :group 'org-properties
3782 :type '(repeat
3783 (cons (string :tag "Property")
3784 (string :tag "Value"))))
3786 (defvar-local org-file-properties nil
3787 "List of property/value pairs that can be inherited by any entry.
3788 Valid for the current buffer.
3789 This variable is populated from #+PROPERTY lines.")
3791 (defgroup org-agenda nil
3792 "Options concerning agenda views in Org-mode."
3793 :tag "Org Agenda"
3794 :group 'org)
3796 (defvar-local org-category nil
3797 "Variable used by org files to set a category for agenda display.
3798 Such files should use a file variable to set it, for example
3800 # -*- mode: org; org-category: \"ELisp\"
3802 or contain a special line
3804 #+CATEGORY: ELisp
3806 If the file does not specify a category, then file's base name
3807 is used instead.")
3808 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3810 (defcustom org-agenda-files nil
3811 "The files to be used for agenda display.
3812 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3813 \\[org-remove-file]. You can also use customize to edit the list.
3815 If an entry is a directory, all files in that directory that are matched by
3816 `org-agenda-file-regexp' will be part of the file list.
3818 If the value of the variable is not a list but a single file name, then
3819 the list of agenda files is actually stored and maintained in that file, one
3820 agenda file per line. In this file paths can be given relative to
3821 `org-directory'. Tilde expansion and environment variable substitution
3822 are also made."
3823 :group 'org-agenda
3824 :type '(choice
3825 (repeat :tag "List of files and directories" file)
3826 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3828 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3829 "Regular expression to match files for `org-agenda-files'.
3830 If any element in the list in that variable contains a directory instead
3831 of a normal file, all files in that directory that are matched by this
3832 regular expression will be included."
3833 :group 'org-agenda
3834 :type 'regexp)
3836 (defcustom org-agenda-text-search-extra-files nil
3837 "List of extra files to be searched by text search commands.
3838 These files will be searched in addition to the agenda files by the
3839 commands `org-search-view' (`\\[org-agenda] s') \
3840 and `org-occur-in-agenda-files'.
3841 Note that these files will only be searched for text search commands,
3842 not for the other agenda views like todo lists, tag searches or the weekly
3843 agenda. This variable is intended to list notes and possibly archive files
3844 that should also be searched by these two commands.
3845 In fact, if the first element in the list is the symbol `agenda-archives',
3846 then all archive files of all agenda files will be added to the search
3847 scope."
3848 :group 'org-agenda
3849 :type '(set :greedy t
3850 (const :tag "Agenda Archives" agenda-archives)
3851 (repeat :inline t (file))))
3853 (org-defvaralias 'org-agenda-multi-occur-extra-files
3854 'org-agenda-text-search-extra-files)
3856 (defcustom org-agenda-skip-unavailable-files nil
3857 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3858 A nil value means to remove them, after a query, from the list."
3859 :group 'org-agenda
3860 :type 'boolean)
3862 (defcustom org-calendar-to-agenda-key [?c]
3863 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3864 The command `org-calendar-goto-agenda' will be bound to this key. The
3865 default is the character `c' because then `c' can be used to switch back and
3866 forth between agenda and calendar."
3867 :group 'org-agenda
3868 :type 'sexp)
3870 (defcustom org-calendar-insert-diary-entry-key [?i]
3871 "The key to be installed in `calendar-mode-map' for adding diary entries.
3872 This option is irrelevant until `org-agenda-diary-file' has been configured
3873 to point to an Org-mode file. When that is the case, the command
3874 `org-agenda-diary-entry' will be bound to the key given here, by default
3875 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3876 if you want to continue doing this, you need to change this to a different
3877 key."
3878 :group 'org-agenda
3879 :type 'sexp)
3881 (defcustom org-agenda-diary-file 'diary-file
3882 "File to which to add new entries with the `i' key in agenda and calendar.
3883 When this is the symbol `diary-file', the functionality in the Emacs
3884 calendar will be used to add entries to the `diary-file'. But when this
3885 points to a file, `org-agenda-diary-entry' will be used instead."
3886 :group 'org-agenda
3887 :type '(choice
3888 (const :tag "The standard Emacs diary file" diary-file)
3889 (file :tag "Special Org file diary entries")))
3891 (eval-after-load "calendar"
3892 '(progn
3893 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3894 'org-calendar-goto-agenda)
3895 (add-hook 'calendar-mode-hook
3896 (lambda ()
3897 (unless (eq org-agenda-diary-file 'diary-file)
3898 (define-key calendar-mode-map
3899 org-calendar-insert-diary-entry-key
3900 'org-agenda-diary-entry))))))
3902 (defgroup org-latex nil
3903 "Options for embedding LaTeX code into Org-mode."
3904 :tag "Org LaTeX"
3905 :group 'org)
3907 (defcustom org-format-latex-options
3908 '(:foreground default :background default :scale 1.0
3909 :html-foreground "Black" :html-background "Transparent"
3910 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3911 "Options for creating images from LaTeX fragments.
3912 This is a property list with the following properties:
3913 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3914 `default' means use the foreground of the default face.
3915 `auto' means use the foreground from the text face.
3916 :background the background color, or \"Transparent\".
3917 `default' means use the background of the default face.
3918 `auto' means use the background from the text face.
3919 :scale a scaling factor for the size of the images, to get more pixels
3920 :html-foreground, :html-background, :html-scale
3921 the same numbers for HTML export.
3922 :matchers a list indicating which matchers should be used to
3923 find LaTeX fragments. Valid members of this list are:
3924 \"begin\" find environments
3925 \"$1\" find single characters surrounded by $.$
3926 \"$\" find math expressions surrounded by $...$
3927 \"$$\" find math expressions surrounded by $$....$$
3928 \"\\(\" find math expressions surrounded by \\(...\\)
3929 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3930 :group 'org-latex
3931 :type 'plist)
3933 (defcustom org-format-latex-signal-error t
3934 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3935 When nil, just push out a message."
3936 :group 'org-latex
3937 :version "24.1"
3938 :type 'boolean)
3940 (defcustom org-latex-to-mathml-jar-file nil
3941 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3942 Use this to specify additional executable file say a jar file.
3944 When using MathToWeb as the converter, specify the full-path to
3945 your mathtoweb.jar file."
3946 :group 'org-latex
3947 :version "24.1"
3948 :type '(choice
3949 (const :tag "None" nil)
3950 (file :tag "JAR file" :must-match t)))
3952 (defcustom org-latex-to-mathml-convert-command nil
3953 "Command to convert LaTeX fragments to MathML.
3954 Replace format-specifiers in the command as noted below and use
3955 `shell-command' to convert LaTeX to MathML.
3956 %j: Executable file in fully expanded form as specified by
3957 `org-latex-to-mathml-jar-file'.
3958 %I: Input LaTeX file in fully expanded form.
3959 %i: The latex fragment to be converted.
3960 %o: Output MathML file.
3962 This command is used by `org-create-math-formula'.
3964 When using MathToWeb as the converter, set this option to
3965 \"java -jar %j -unicode -force -df %o %I\".
3967 When using LaTeXML set this option to
3968 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3969 :group 'org-latex
3970 :version "24.1"
3971 :type '(choice
3972 (const :tag "None" nil)
3973 (string :tag "\nShell command")))
3975 (defcustom org-latex-create-formula-image-program 'dvipng
3976 "Program to convert LaTeX fragments with.
3978 dvipng Process the LaTeX fragments to dvi file, then convert
3979 dvi files to png files using dvipng.
3980 This will also include processing of non-math environments.
3981 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3982 to convert pdf files to png files"
3983 :group 'org-latex
3984 :version "24.1"
3985 :type '(choice
3986 (const :tag "dvipng" dvipng)
3987 (const :tag "imagemagick" imagemagick)))
3989 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3990 "Path to store latex preview images.
3991 A relative path here creates many directories relative to the
3992 processed org files paths. An absolute path puts all preview
3993 images at the same place."
3994 :group 'org-latex
3995 :version "24.3"
3996 :type 'string)
3998 (defun org-format-latex-mathml-available-p ()
3999 "Return t if `org-latex-to-mathml-convert-command' is usable."
4000 (save-match-data
4001 (when (and (boundp 'org-latex-to-mathml-convert-command)
4002 org-latex-to-mathml-convert-command)
4003 (let ((executable (car (split-string
4004 org-latex-to-mathml-convert-command))))
4005 (when (executable-find executable)
4006 (if (string-match
4007 "%j" org-latex-to-mathml-convert-command)
4008 (file-readable-p org-latex-to-mathml-jar-file)
4009 t))))))
4011 (defcustom org-format-latex-header "\\documentclass{article}
4012 \\usepackage[usenames]{color}
4013 \[PACKAGES]
4014 \[DEFAULT-PACKAGES]
4015 \\pagestyle{empty} % do not remove
4016 % The settings below are copied from fullpage.sty
4017 \\setlength{\\textwidth}{\\paperwidth}
4018 \\addtolength{\\textwidth}{-3cm}
4019 \\setlength{\\oddsidemargin}{1.5cm}
4020 \\addtolength{\\oddsidemargin}{-2.54cm}
4021 \\setlength{\\evensidemargin}{\\oddsidemargin}
4022 \\setlength{\\textheight}{\\paperheight}
4023 \\addtolength{\\textheight}{-\\headheight}
4024 \\addtolength{\\textheight}{-\\headsep}
4025 \\addtolength{\\textheight}{-\\footskip}
4026 \\addtolength{\\textheight}{-3cm}
4027 \\setlength{\\topmargin}{1.5cm}
4028 \\addtolength{\\topmargin}{-2.54cm}"
4029 "The document header used for processing LaTeX fragments.
4030 It is imperative that this header make sure that no page number
4031 appears on the page. The package defined in the variables
4032 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4033 will either replace the placeholder \"[PACKAGES]\" in this
4034 header, or they will be appended."
4035 :group 'org-latex
4036 :type 'string)
4038 (defun org-set-packages-alist (var val)
4039 "Set the packages alist and make sure it has 3 elements per entry."
4040 (set var (mapcar (lambda (x)
4041 (if (and (consp x) (= (length x) 2))
4042 (list (car x) (nth 1 x) t)
4044 val)))
4046 (defun org-get-packages-alist (var)
4047 "Get the packages alist and make sure it has 3 elements per entry."
4048 (mapcar (lambda (x)
4049 (if (and (consp x) (= (length x) 2))
4050 (list (car x) (nth 1 x) t)
4052 (default-value var)))
4054 (defcustom org-latex-default-packages-alist
4055 '(("AUTO" "inputenc" t ("pdflatex"))
4056 ("T1" "fontenc" t ("pdflatex"))
4057 ("" "graphicx" t)
4058 ("" "grffile" t)
4059 ("" "longtable" nil)
4060 ("" "wrapfig" nil)
4061 ("" "rotating" nil)
4062 ("normalem" "ulem" t)
4063 ("" "amsmath" t)
4064 ("" "textcomp" t)
4065 ("" "amssymb" t)
4066 ("" "capt-of" nil)
4067 ("" "hyperref" nil))
4068 "Alist of default packages to be inserted in the header.
4070 Change this only if one of the packages here causes an
4071 incompatibility with another package you are using.
4073 The packages in this list are needed by one part or another of
4074 Org mode to function properly:
4076 - inputenc, fontenc: for basic font and character selection
4077 - graphicx: for including images
4078 - grffile: allow periods and spaces in graphics file names
4079 - longtable: For multipage tables
4080 - wrapfig: for figure placement
4081 - rotating: for sideways figures and tables
4082 - ulem: for underline and strike-through
4083 - amsmath: for subscript and superscript and math environments
4084 - textcomp, amssymb: for various symbols used
4085 for interpreting the entities in `org-entities'. You can skip
4086 some of these packages if you don't use any of their symbols.
4087 - capt-of: for captions outside of floats
4088 - hyperref: for cross references
4090 Therefore you should not modify this variable unless you know
4091 what you are doing. The one reason to change it anyway is that
4092 you might be loading some other package that conflicts with one
4093 of the default packages. Each element is either a cell or
4094 a string.
4096 A cell is of the format
4098 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4100 If SNIPPET-FLAG is non-nil, the package also needs to be included
4101 when compiling LaTeX snippets into images for inclusion into
4102 non-LaTeX output. COMPILERS is a list of compilers that should
4103 include the package, see `org-latex-compiler'. If the document
4104 compiler is not in the list, and the list is non-nil, the package
4105 will not be inserted in the final document.
4107 A string will be inserted as-is in the header of the document."
4108 :group 'org-latex
4109 :group 'org-export-latex
4110 :set 'org-set-packages-alist
4111 :get 'org-get-packages-alist
4112 :version "25.1"
4113 :package-version '(Org . "8.3")
4114 :type '(repeat
4115 (choice
4116 (list :tag "options/package pair"
4117 (string :tag "options")
4118 (string :tag "package")
4119 (boolean :tag "Snippet"))
4120 (string :tag "A line of LaTeX"))))
4122 (defcustom org-latex-packages-alist nil
4123 "Alist of packages to be inserted in every LaTeX header.
4125 These will be inserted after `org-latex-default-packages-alist'.
4126 Each element is either a cell or a string.
4128 A cell is of the format:
4130 (\"options\" \"package\" SNIPPET-FLAG)
4132 SNIPPET-FLAG, when non-nil, indicates that this package is also
4133 needed when turning LaTeX snippets into images for inclusion into
4134 non-LaTeX output.
4136 A string will be inserted as-is in the header of the document.
4138 Make sure that you only list packages here which:
4140 - you want in every file;
4141 - do not conflict with the setup in `org-format-latex-header';
4142 - do not conflict with the default packages in
4143 `org-latex-default-packages-alist'."
4144 :group 'org-latex
4145 :group 'org-export-latex
4146 :set 'org-set-packages-alist
4147 :get 'org-get-packages-alist
4148 :type '(repeat
4149 (choice
4150 (list :tag "options/package pair"
4151 (string :tag "options")
4152 (string :tag "package")
4153 (boolean :tag "Snippet"))
4154 (string :tag "A line of LaTeX"))))
4156 (defgroup org-appearance nil
4157 "Settings for Org-mode appearance."
4158 :tag "Org Appearance"
4159 :group 'org)
4161 (defcustom org-level-color-stars-only nil
4162 "Non-nil means fontify only the stars in each headline.
4163 When nil, the entire headline is fontified.
4164 Changing it requires restart of `font-lock-mode' to become effective
4165 also in regions already fontified."
4166 :group 'org-appearance
4167 :type 'boolean)
4169 (defcustom org-hide-leading-stars nil
4170 "Non-nil means hide the first N-1 stars in a headline.
4171 This works by using the face `org-hide' for these stars. This
4172 face is white for a light background, and black for a dark
4173 background. You may have to customize the face `org-hide' to
4174 make this work.
4175 Changing it requires restart of `font-lock-mode' to become effective
4176 also in regions already fontified.
4177 You may also set this on a per-file basis by adding one of the following
4178 lines to the buffer:
4180 #+STARTUP: hidestars
4181 #+STARTUP: showstars"
4182 :group 'org-appearance
4183 :type 'boolean)
4185 (defcustom org-hidden-keywords nil
4186 "List of symbols corresponding to keywords to be hidden the org buffer.
4187 For example, a value \\='(title) for this list will make the document's title
4188 appear in the buffer without the initial #+TITLE: keyword."
4189 :group 'org-appearance
4190 :version "24.1"
4191 :type '(set (const :tag "#+AUTHOR" author)
4192 (const :tag "#+DATE" date)
4193 (const :tag "#+EMAIL" email)
4194 (const :tag "#+TITLE" title)))
4196 (defcustom org-custom-properties nil
4197 "List of properties (as strings) with a special meaning.
4198 The default use of these custom properties is to let the user
4199 hide them with `org-toggle-custom-properties-visibility'."
4200 :group 'org-properties
4201 :group 'org-appearance
4202 :version "24.3"
4203 :type '(repeat (string :tag "Property Name")))
4205 (defcustom org-fontify-done-headline nil
4206 "Non-nil means change the face of a headline if it is marked DONE.
4207 Normally, only the TODO/DONE keyword indicates the state of a headline.
4208 When this is non-nil, the headline after the keyword is set to the
4209 `org-headline-done' as an additional indication."
4210 :group 'org-appearance
4211 :type 'boolean)
4213 (defcustom org-fontify-emphasized-text t
4214 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4215 Changing this variable requires a restart of Emacs to take effect."
4216 :group 'org-appearance
4217 :type 'boolean)
4219 (defcustom org-fontify-whole-heading-line nil
4220 "Non-nil means fontify the whole line for headings.
4221 This is useful when setting a background color for the
4222 org-level-* faces."
4223 :group 'org-appearance
4224 :type 'boolean)
4226 (defcustom org-highlight-latex-and-related nil
4227 "Non-nil means highlight LaTeX related syntax in the buffer.
4228 When non nil, the value should be a list containing any of the
4229 following symbols:
4230 `latex' Highlight LaTeX snippets and environments.
4231 `script' Highlight subscript and superscript.
4232 `entities' Highlight entities."
4233 :group 'org-appearance
4234 :version "24.4"
4235 :package-version '(Org . "8.0")
4236 :type '(choice
4237 (const :tag "No highlighting" nil)
4238 (set :greedy t :tag "Highlight"
4239 (const :tag "LaTeX snippets and environments" latex)
4240 (const :tag "Subscript and superscript" script)
4241 (const :tag "Entities" entities))))
4243 (defcustom org-hide-emphasis-markers nil
4244 "Non-nil mean font-lock should hide the emphasis marker characters."
4245 :group 'org-appearance
4246 :type 'boolean)
4248 (defcustom org-hide-macro-markers nil
4249 "Non-nil mean font-lock should hide the brackets marking macro calls."
4250 :group 'org-appearance
4251 :type 'boolean)
4253 (defcustom org-pretty-entities nil
4254 "Non-nil means show entities as UTF8 characters.
4255 When nil, the \\name form remains in the buffer."
4256 :group 'org-appearance
4257 :version "24.1"
4258 :type 'boolean)
4260 (defcustom org-pretty-entities-include-sub-superscripts t
4261 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4262 :group 'org-appearance
4263 :version "24.1"
4264 :type 'boolean)
4266 (defvar org-emph-re nil
4267 "Regular expression for matching emphasis.
4268 After a match, the match groups contain these elements:
4269 0 The match of the full regular expression, including the characters
4270 before and after the proper match
4271 1 The character before the proper match, or empty at beginning of line
4272 2 The proper match, including the leading and trailing markers
4273 3 The leading marker like * or /, indicating the type of highlighting
4274 4 The text between the emphasis markers, not including the markers
4275 5 The character after the match, empty at the end of a line")
4276 (defvar org-verbatim-re nil
4277 "Regular expression for matching verbatim text.")
4278 (defvar org-emphasis-regexp-components) ; defined just below
4279 (defvar org-emphasis-alist) ; defined just below
4280 (defun org-set-emph-re (var val)
4281 "Set variable and compute the emphasis regular expression."
4282 (set var val)
4283 (when (and (boundp 'org-emphasis-alist)
4284 (boundp 'org-emphasis-regexp-components)
4285 org-emphasis-alist org-emphasis-regexp-components)
4286 (let* ((e org-emphasis-regexp-components)
4287 (pre (car e))
4288 (post (nth 1 e))
4289 (border (nth 2 e))
4290 (body (nth 3 e))
4291 (nl (nth 4 e))
4292 (body1 (concat body "*?"))
4293 (markers (mapconcat 'car org-emphasis-alist ""))
4294 (vmarkers (mapconcat
4295 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4296 org-emphasis-alist "")))
4297 ;; make sure special characters appear at the right position in the class
4298 (if (string-match "\\^" markers)
4299 (setq markers (concat (replace-match "" t t markers) "^")))
4300 (if (string-match "-" markers)
4301 (setq markers (concat (replace-match "" t t markers) "-")))
4302 (if (string-match "\\^" vmarkers)
4303 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4304 (if (string-match "-" vmarkers)
4305 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4306 (if (> nl 0)
4307 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4308 (int-to-string nl) "\\}")))
4309 ;; Make the regexp
4310 (setq org-emph-re
4311 (concat "\\([" pre "]\\|^\\)"
4312 "\\("
4313 "\\([" markers "]\\)"
4314 "\\("
4315 "[^" border "]\\|"
4316 "[^" border "]"
4317 body1
4318 "[^" border "]"
4319 "\\)"
4320 "\\3\\)"
4321 "\\([" post "]\\|$\\)"))
4322 (setq org-verbatim-re
4323 (concat "\\([" pre "]\\|^\\)"
4324 "\\("
4325 "\\([" vmarkers "]\\)"
4326 "\\("
4327 "[^" border "]\\|"
4328 "[^" border "]"
4329 body1
4330 "[^" border "]"
4331 "\\)"
4332 "\\3\\)"
4333 "\\([" post "]\\|$\\)")))))
4335 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4336 ;; set this option proved cumbersome. See this message/thread:
4337 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4338 (defvar org-emphasis-regexp-components
4339 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4340 "Components used to build the regular expression for emphasis.
4341 This is a list with five entries. Terminology: In an emphasis string
4342 like \" *strong word* \", we call the initial space PREMATCH, the final
4343 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4344 and \"trong wor\" is the body. The different components in this variable
4345 specify what is allowed/forbidden in each part:
4347 pre Chars allowed as prematch. Beginning of line will be allowed too.
4348 post Chars allowed as postmatch. End of line will be allowed too.
4349 border The chars *forbidden* as border characters.
4350 body-regexp A regexp like \".\" to match a body character. Don't use
4351 non-shy groups here, and don't allow newline here.
4352 newline The maximum number of newlines allowed in an emphasis exp.
4354 You need to reload Org or to restart Emacs after customizing this.")
4356 (defcustom org-emphasis-alist
4357 `(("*" bold)
4358 ("/" italic)
4359 ("_" underline)
4360 ("=" org-verbatim verbatim)
4361 ("~" org-code verbatim)
4362 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4363 "Alist of characters and faces to emphasize text.
4364 Text starting and ending with a special character will be emphasized,
4365 for example *bold*, _underlined_ and /italic/. This variable sets the
4366 marker characters and the face to be used by font-lock for highlighting
4367 in Org-mode Emacs buffers.
4369 You need to reload Org or to restart Emacs after customizing this."
4370 :group 'org-appearance
4371 :set 'org-set-emph-re
4372 :version "24.4"
4373 :package-version '(Org . "8.0")
4374 :type '(repeat
4375 (list
4376 (string :tag "Marker character")
4377 (choice
4378 (face :tag "Font-lock-face")
4379 (plist :tag "Face property list"))
4380 (option (const verbatim)))))
4382 (defvar org-protecting-blocks '("src" "example" "export")
4383 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4384 This is needed for font-lock setup.")
4386 ;;; Miscellaneous options
4388 (defgroup org-completion nil
4389 "Completion in Org-mode."
4390 :tag "Org Completion"
4391 :group 'org)
4393 (defcustom org-completion-use-ido nil
4394 "Non-nil means use ido completion wherever possible.
4395 Note that `ido-mode' must be active for this variable to be relevant.
4396 If you decide to turn this variable on, you might well want to turn off
4397 `org-outline-path-complete-in-steps'.
4398 See also `org-completion-use-iswitchb'."
4399 :group 'org-completion
4400 :type 'boolean)
4402 (defcustom org-completion-use-iswitchb nil
4403 "Non-nil means use iswitchb completion wherever possible.
4404 Note that `iswitchb-mode' must be active for this variable to be relevant.
4405 If you decide to turn this variable on, you might well want to turn off
4406 `org-outline-path-complete-in-steps'.
4407 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4408 :group 'org-completion
4409 :type 'boolean)
4411 (defcustom org-completion-fallback-command 'hippie-expand
4412 "The expansion command called by \\[pcomplete] in normal context.
4413 Normal means, no org-mode-specific context."
4414 :group 'org-completion
4415 :type 'function)
4417 ;;; Functions and variables from their packages
4418 ;; Declared here to avoid compiler warnings
4420 ;; XEmacs only
4421 (defvar outline-mode-menu-heading)
4422 (defvar outline-mode-menu-show)
4423 (defvar outline-mode-menu-hide)
4424 (defvar zmacs-regions) ; XEmacs regions
4426 ;; Emacs only
4427 (defvar mark-active)
4429 ;; Various packages
4430 (declare-function calc-eval "calc" (str &optional separator &rest args))
4431 (declare-function calendar-forward-day "cal-move" (arg))
4432 (declare-function calendar-goto-date "cal-move" (date))
4433 (declare-function calendar-goto-today "cal-move" ())
4434 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4435 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4436 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4437 (declare-function cdlatex-tab "ext:cdlatex" ())
4438 (declare-function dired-get-filename
4439 "dired"
4440 (&optional localp no-error-if-not-filep))
4441 (declare-function iswitchb-read-buffer
4442 "iswitchb"
4443 (prompt &optional default require-match start matches-set))
4444 (declare-function org-agenda-change-all-lines
4445 "org-agenda"
4446 (newhead hdmarker &optional fixface just-this))
4447 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4448 "org-agenda"
4449 (&optional end))
4450 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4451 (declare-function org-agenda-format-item
4452 "org-agenda"
4453 (extra txt &optional level category tags dotime noprefix
4454 remove-re habitp))
4455 (declare-function org-agenda-maybe-redo "org-agenda" ())
4456 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4457 (declare-function org-agenda-save-markers-for-cut-and-paste
4458 "org-agenda"
4459 (beg end))
4460 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4461 (declare-function org-agenda-skip "org-agenda" ())
4462 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4463 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4464 (declare-function org-indent-mode "org-indent" (&optional arg))
4465 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4466 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4467 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4468 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4469 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4470 (declare-function parse-time-string "parse-time" (string))
4471 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4472 (declare-function table--at-cell-p
4473 "table"
4474 (position &optional object at-column))
4476 (defvar align-mode-rules-list)
4477 (defvar calc-embedded-close-formula)
4478 (defvar calc-embedded-open-formula)
4479 (defvar calc-embedded-open-mode)
4480 (defvar font-lock-unfontify-region-function)
4481 (defvar iswitchb-temp-buflist)
4482 (defvar org-agenda-tags-todo-honor-ignore-options)
4483 (defvar remember-data-file)
4484 (defvar texmathp-why)
4486 ;;;###autoload
4487 (defun turn-on-orgtbl ()
4488 "Unconditionally turn on `orgtbl-mode'."
4489 (require 'org-table)
4490 (orgtbl-mode 1))
4492 (defun org-at-table-p (&optional table-type)
4493 "Non-nil if the cursor is inside an Org table.
4494 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4495 If `org-enable-table-editor' is nil, return nil unconditionally."
4496 (and
4497 org-enable-table-editor
4498 (save-excursion
4499 (beginning-of-line)
4500 (org-looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4501 (or (not (derived-mode-p 'org-mode))
4502 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4503 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4504 (define-obsolete-function-alias 'org-table-p 'org-at-table-p "Org 9.0")
4506 (defun org-at-table.el-p ()
4507 "Non-nil when point is at a table.el table."
4508 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4509 (let ((element (org-element-at-point)))
4510 (and (eq (org-element-type element) 'table)
4511 (eq (org-element-property :type element) 'table.el)))))
4513 (defun org-table-recognize-table.el ()
4514 "If there is a table.el table nearby, recognize it and move into it."
4515 (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
4516 (beginning-of-line)
4517 (unless (or (looking-at org-table-dataline-regexp)
4518 (not (looking-at org-table1-hline-regexp)))
4519 (forward-line)
4520 (when (looking-at org-table-any-border-regexp)
4521 (forward-line -2)))
4522 (if (re-search-forward "|" (org-table-end t) t)
4523 (progn
4524 (require 'table)
4525 (if (table--at-cell-p (point)) t
4526 (message "recognizing table.el table...")
4527 (table-recognize-table)
4528 (message "recognizing table.el table...done")))
4529 (error "This should not happen"))))
4530 ;;; This function is not used by org core since commit 6d1e3082, Feb 2010
4531 (make-obsolete 'org-table-recognize-table.el
4532 "please notify the org mailing list if you use this function."
4533 "Org 9.0")
4535 (defun org-at-table-hline-p ()
4536 "Non-nil when point is inside a hline in a table.
4537 Assume point is already in a table. If `org-enable-table-editor'
4538 is nil, return nil unconditionally."
4539 (and org-enable-table-editor
4540 (save-excursion
4541 (beginning-of-line)
4542 (looking-at org-table-hline-regexp))))
4544 (defun org-table-map-tables (function &optional quietly)
4545 "Apply FUNCTION to the start of all tables in the buffer."
4546 (save-excursion
4547 (save-restriction
4548 (widen)
4549 (goto-char (point-min))
4550 (while (re-search-forward org-table-any-line-regexp nil t)
4551 (unless quietly
4552 (message "Mapping tables: %d%%"
4553 (floor (* 100.0 (point)) (buffer-size))))
4554 (beginning-of-line 1)
4555 (when (and (looking-at org-table-line-regexp)
4556 ;; Exclude tables in src/example/verbatim/clocktable blocks
4557 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4558 (save-excursion (funcall function))
4559 (or (looking-at org-table-line-regexp)
4560 (forward-char 1)))
4561 (re-search-forward org-table-any-border-regexp nil 1))))
4562 (unless quietly (message "Mapping tables: done")))
4564 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4565 (declare-function org-clock-update-mode-line "org-clock" ())
4566 (declare-function org-resolve-clocks "org-clock"
4567 (&optional also-non-dangling-p prompt last-valid))
4569 (defun org-at-TBLFM-p (&optional pos)
4570 "Non-nil when point (or POS) is in #+TBLFM line."
4571 (save-excursion
4572 (goto-char (or pos (point)))
4573 (beginning-of-line)
4574 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4575 (eq (org-element-type (org-element-at-point)) 'table))))
4577 (defvar org-clock-start-time)
4578 (defvar org-clock-marker (make-marker)
4579 "Marker recording the last clock-in.")
4580 (defvar org-clock-hd-marker (make-marker)
4581 "Marker recording the last clock-in, but the headline position.")
4582 (defvar org-clock-heading ""
4583 "The heading of the current clock entry.")
4584 (defun org-clock-is-active ()
4585 "Return the buffer where the clock is currently running.
4586 Return nil if no clock is running."
4587 (marker-buffer org-clock-marker))
4589 (defun org-check-running-clock ()
4590 "Check if the current buffer contains the running clock.
4591 If yes, offer to stop it and to save the buffer with the changes."
4592 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4593 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4594 (buffer-name))))
4595 (org-clock-out)
4596 (when (y-or-n-p "Save changed buffer?")
4597 (save-buffer))))
4599 (defun org-clocktable-try-shift (dir n)
4600 "Check if this line starts a clock table, if yes, shift the time block."
4601 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4602 (org-clocktable-shift dir n)))
4604 ;;;###autoload
4605 (defun org-clock-persistence-insinuate ()
4606 "Set up hooks for clock persistence."
4607 (require 'org-clock)
4608 (add-hook 'org-mode-hook 'org-clock-load)
4609 (add-hook 'kill-emacs-hook 'org-clock-save))
4611 (defgroup org-archive nil
4612 "Options concerning archiving in Org-mode."
4613 :tag "Org Archive"
4614 :group 'org-structure)
4616 (defcustom org-archive-location "%s_archive::"
4617 "The location where subtrees should be archived.
4619 The value of this variable is a string, consisting of two parts,
4620 separated by a double-colon. The first part is a filename and
4621 the second part is a headline.
4623 When the filename is omitted, archiving happens in the same file.
4624 %s in the filename will be replaced by the current file
4625 name (without the directory part). Archiving to a different file
4626 is useful to keep archived entries from contributing to the
4627 Org-mode Agenda.
4629 The archived entries will be filed as subtrees of the specified
4630 headline. When the headline is omitted, the subtrees are simply
4631 filed away at the end of the file, as top-level entries. Also in
4632 the heading you can use %s to represent the file name, this can be
4633 useful when using the same archive for a number of different files.
4635 Here are a few examples:
4636 \"%s_archive::\"
4637 If the current file is Projects.org, archive in file
4638 Projects.org_archive, as top-level trees. This is the default.
4640 \"::* Archived Tasks\"
4641 Archive in the current file, under the top-level headline
4642 \"* Archived Tasks\".
4644 \"~/org/archive.org::\"
4645 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4647 \"~/org/archive.org::* From %s\"
4648 Archive in file ~/org/archive.org (absolute path), under headlines
4649 \"From FILENAME\" where file name is the current file name.
4651 \"~/org/datetree.org::datetree/* Finished Tasks\"
4652 The \"datetree/\" string is special, signifying to archive
4653 items to the datetree. Items are placed in either the CLOSED
4654 date of the item, or the current date if there is no CLOSED date.
4655 The heading will be a subentry to the current date. There doesn't
4656 need to be a heading, but there always needs to be a slash after
4657 datetree. For example, to store archived items directly in the
4658 datetree, use \"~/org/datetree.org::datetree/\".
4660 \"basement::** Finished Tasks\"
4661 Archive in file ./basement (relative path), as level 3 trees
4662 below the level 2 heading \"** Finished Tasks\".
4664 You may set this option on a per-file basis by adding to the buffer a
4665 line like
4667 #+ARCHIVE: basement::** Finished Tasks
4669 You may also define it locally for a subtree by setting an ARCHIVE property
4670 in the entry. If such a property is found in an entry, or anywhere up
4671 the hierarchy, it will be used."
4672 :group 'org-archive
4673 :type 'string)
4675 (defcustom org-agenda-skip-archived-trees t
4676 "Non-nil means the agenda will skip any items located in archived trees.
4677 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4678 variable is no longer recommended, you should leave it at the value t.
4679 Instead, use the key `v' to cycle the archives-mode in the agenda."
4680 :group 'org-archive
4681 :group 'org-agenda-skip
4682 :type 'boolean)
4684 (defcustom org-columns-skip-archived-trees t
4685 "Non-nil means ignore archived trees when creating column view."
4686 :group 'org-archive
4687 :group 'org-properties
4688 :type 'boolean)
4690 (defcustom org-cycle-open-archived-trees nil
4691 "Non-nil means `org-cycle' will open archived trees.
4692 An archived tree is a tree marked with the tag ARCHIVE.
4693 When nil, archived trees will stay folded. You can still open them with
4694 normal outline commands like `show-all', but not with the cycling commands."
4695 :group 'org-archive
4696 :group 'org-cycle
4697 :type 'boolean)
4699 (defcustom org-sparse-tree-open-archived-trees nil
4700 "Non-nil means sparse tree construction shows matches in archived trees.
4701 When nil, matches in these trees are highlighted, but the trees are kept in
4702 collapsed state."
4703 :group 'org-archive
4704 :group 'org-sparse-trees
4705 :type 'boolean)
4707 (defcustom org-sparse-tree-default-date-type nil
4708 "The default date type when building a sparse tree.
4709 When this is nil, a date is a scheduled or a deadline timestamp.
4710 Otherwise, these types are allowed:
4712 all: all timestamps
4713 active: only active timestamps (<...>)
4714 inactive: only inactive timestamps ([...])
4715 scheduled: only scheduled timestamps
4716 deadline: only deadline timestamps"
4717 :type '(choice (const :tag "Scheduled or deadline" nil)
4718 (const :tag "All timestamps" all)
4719 (const :tag "Only active timestamps" active)
4720 (const :tag "Only inactive timestamps" inactive)
4721 (const :tag "Only scheduled timestamps" scheduled)
4722 (const :tag "Only deadline timestamps" deadline)
4723 (const :tag "Only closed timestamps" closed))
4724 :version "25.1"
4725 :package-version '(Org . "8.3")
4726 :group 'org-sparse-trees)
4728 (defun org-cycle-hide-archived-subtrees (state)
4729 "Re-hide all archived subtrees after a visibility state change."
4730 (when (and (not org-cycle-open-archived-trees)
4731 (not (memq state '(overview folded))))
4732 (save-excursion
4733 (let* ((globalp (memq state '(contents all)))
4734 (beg (if globalp (point-min) (point)))
4735 (end (if globalp (point-max) (org-end-of-subtree t))))
4736 (org-hide-archived-subtrees beg end)
4737 (goto-char beg)
4738 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4739 (message "%s" (substitute-command-keys
4740 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4742 (defun org-force-cycle-archived ()
4743 "Cycle subtree even if it is archived."
4744 (interactive)
4745 (setq this-command 'org-cycle)
4746 (let ((org-cycle-open-archived-trees t))
4747 (call-interactively 'org-cycle)))
4749 (defun org-hide-archived-subtrees (beg end)
4750 "Re-hide all archived subtrees after a visibility state change."
4751 (org-with-wide-buffer
4752 (let ((case-fold-search nil)
4753 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4754 (goto-char beg)
4755 ;; Include headline point is currently on.
4756 (beginning-of-line)
4757 (while (and (< (point) end) (re-search-forward re end t))
4758 (when (member org-archive-tag (org-get-tags))
4759 (org-flag-subtree t)
4760 (org-end-of-subtree t))))))
4762 (declare-function outline-end-of-heading "outline" ())
4763 (declare-function outline-flag-region "outline" (from to flag))
4764 (defun org-flag-subtree (flag)
4765 (save-excursion
4766 (org-back-to-heading t)
4767 (outline-end-of-heading)
4768 (outline-flag-region (point)
4769 (progn (org-end-of-subtree t) (point))
4770 flag)))
4772 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4774 ;; Declare Column View Code
4776 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4777 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4778 (declare-function org-columns-compute "org-colview" (property))
4780 ;; Declare ID code
4782 (declare-function org-id-store-link "org-id")
4783 (declare-function org-id-locations-load "org-id")
4784 (declare-function org-id-locations-save "org-id")
4785 (defvar org-id-track-globally)
4787 ;;; Variables for pre-computed regular expressions, all buffer local
4789 (defvar-local org-todo-regexp nil
4790 "Matches any of the TODO state keywords.")
4791 (defvar-local org-not-done-regexp nil
4792 "Matches any of the TODO state keywords except the last one.")
4793 (defvar-local org-not-done-heading-regexp nil
4794 "Matches a TODO headline that is not done.")
4795 (defvar-local org-todo-line-regexp nil
4796 "Matches a headline and puts TODO state into group 2 if present.")
4797 (defvar-local org-complex-heading-regexp nil
4798 "Matches a headline and puts everything into groups:
4799 group 1: the stars
4800 group 2: The todo keyword, maybe
4801 group 3: Priority cookie
4802 group 4: True headline
4803 group 5: Tags")
4804 (defvar-local org-complex-heading-regexp-format nil
4805 "Printf format to make regexp to match an exact headline.
4806 This regexp will match the headline of any node which has the
4807 exact headline text that is put into the format, but may have any
4808 TODO state, priority and tags.")
4809 (defvar-local org-todo-line-tags-regexp nil
4810 "Matches a headline and puts TODO state into group 2 if present.
4811 Also put tags into group 4 if tags are present.")
4813 (defconst org-plain-time-of-day-regexp
4814 (concat
4815 "\\(\\<[012]?[0-9]"
4816 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4817 "\\(--?"
4818 "\\(\\<[012]?[0-9]"
4819 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4820 "\\)?")
4821 "Regular expression to match a plain time or time range.
4822 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4823 groups carry important information:
4824 0 the full match
4825 1 the first time, range or not
4826 8 the second time, if it is a range.")
4828 (defconst org-plain-time-extension-regexp
4829 (concat
4830 "\\(\\<[012]?[0-9]"
4831 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4832 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4833 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4834 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4835 groups carry important information:
4836 0 the full match
4837 7 hours of duration
4838 9 minutes of duration")
4840 (defconst org-stamp-time-of-day-regexp
4841 (concat
4842 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4843 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4844 "\\(--?"
4845 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4846 "Regular expression to match a timestamp time or time range.
4847 After a match, the following groups carry important information:
4848 0 the full match
4849 1 date plus weekday, for back referencing to make sure both times are on the same day
4850 2 the first time, range or not
4851 4 the second time, if it is a range.")
4853 (defconst org-startup-options
4854 '(("fold" org-startup-folded t)
4855 ("overview" org-startup-folded t)
4856 ("nofold" org-startup-folded nil)
4857 ("showall" org-startup-folded nil)
4858 ("showeverything" org-startup-folded showeverything)
4859 ("content" org-startup-folded content)
4860 ("indent" org-startup-indented t)
4861 ("noindent" org-startup-indented nil)
4862 ("hidestars" org-hide-leading-stars t)
4863 ("showstars" org-hide-leading-stars nil)
4864 ("odd" org-odd-levels-only t)
4865 ("oddeven" org-odd-levels-only nil)
4866 ("align" org-startup-align-all-tables t)
4867 ("noalign" org-startup-align-all-tables nil)
4868 ("inlineimages" org-startup-with-inline-images t)
4869 ("noinlineimages" org-startup-with-inline-images nil)
4870 ("latexpreview" org-startup-with-latex-preview t)
4871 ("nolatexpreview" org-startup-with-latex-preview nil)
4872 ("customtime" org-display-custom-times t)
4873 ("logdone" org-log-done time)
4874 ("lognotedone" org-log-done note)
4875 ("nologdone" org-log-done nil)
4876 ("lognoteclock-out" org-log-note-clock-out t)
4877 ("nolognoteclock-out" org-log-note-clock-out nil)
4878 ("logrepeat" org-log-repeat state)
4879 ("lognoterepeat" org-log-repeat note)
4880 ("logdrawer" org-log-into-drawer t)
4881 ("nologdrawer" org-log-into-drawer nil)
4882 ("logstatesreversed" org-log-states-order-reversed t)
4883 ("nologstatesreversed" org-log-states-order-reversed nil)
4884 ("nologrepeat" org-log-repeat nil)
4885 ("logreschedule" org-log-reschedule time)
4886 ("lognotereschedule" org-log-reschedule note)
4887 ("nologreschedule" org-log-reschedule nil)
4888 ("logredeadline" org-log-redeadline time)
4889 ("lognoteredeadline" org-log-redeadline note)
4890 ("nologredeadline" org-log-redeadline nil)
4891 ("logrefile" org-log-refile time)
4892 ("lognoterefile" org-log-refile note)
4893 ("nologrefile" org-log-refile nil)
4894 ("fninline" org-footnote-define-inline t)
4895 ("nofninline" org-footnote-define-inline nil)
4896 ("fnlocal" org-footnote-section nil)
4897 ("fnauto" org-footnote-auto-label t)
4898 ("fnprompt" org-footnote-auto-label nil)
4899 ("fnconfirm" org-footnote-auto-label confirm)
4900 ("fnplain" org-footnote-auto-label plain)
4901 ("fnadjust" org-footnote-auto-adjust t)
4902 ("nofnadjust" org-footnote-auto-adjust nil)
4903 ("constcgs" constants-unit-system cgs)
4904 ("constSI" constants-unit-system SI)
4905 ("noptag" org-tag-persistent-alist nil)
4906 ("hideblocks" org-hide-block-startup t)
4907 ("nohideblocks" org-hide-block-startup nil)
4908 ("beamer" org-startup-with-beamer-mode t)
4909 ("entitiespretty" org-pretty-entities t)
4910 ("entitiesplain" org-pretty-entities nil))
4911 "Variable associated with STARTUP options for org-mode.
4912 Each element is a list of three items: the startup options (as written
4913 in the #+STARTUP line), the corresponding variable, and the value to set
4914 this variable to if the option is found. An optional forth element PUSH
4915 means to push this value onto the list in the variable.")
4917 (defcustom org-group-tags t
4918 "When non-nil (the default), use group tags.
4919 This can be turned on/off through `org-toggle-tags-groups'."
4920 :group 'org-tags
4921 :group 'org-startup
4922 :type 'boolean)
4924 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4926 (defun org-toggle-tags-groups ()
4927 "Toggle support for group tags.
4928 Support for group tags is controlled by the option
4929 `org-group-tags', which is non-nil by default."
4930 (interactive)
4931 (setq org-group-tags (not org-group-tags))
4932 (cond ((and (derived-mode-p 'org-agenda-mode)
4933 org-group-tags)
4934 (org-agenda-redo))
4935 ((derived-mode-p 'org-mode)
4936 (let ((org-inhibit-startup t)) (org-mode))))
4937 (message "Groups tags support has been turned %s"
4938 (if org-group-tags "on" "off")))
4940 (defun org-set-regexps-and-options (&optional tags-only)
4941 "Precompute regular expressions used in the current buffer.
4942 When optional argument TAGS-ONLY is non-nil, only compute tags
4943 related expressions."
4944 (when (derived-mode-p 'org-mode)
4945 (let ((alist (org--setup-collect-keywords
4946 (org-make-options-regexp
4947 (append '("FILETAGS" "TAGS" "SETUPFILE")
4948 (and (not tags-only)
4949 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4950 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4951 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4952 (org--setup-process-tags
4953 (cdr (assq 'tags alist)) (cdr (assq 'filetags alist)))
4954 (unless tags-only
4955 ;; File properties.
4956 (setq-local org-file-properties (cdr (assq 'property alist)))
4957 ;; Archive location.
4958 (let ((archive (cdr (assq 'archive alist))))
4959 (when archive (setq-local org-archive-location archive)))
4960 ;; Category.
4961 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4962 (when cat
4963 (setq-local org-category (intern cat))
4964 (setq-local org-file-properties
4965 (org--update-property-plist
4966 "CATEGORY" cat org-file-properties))))
4967 ;; Columns.
4968 (let ((column (cdr (assq 'columns alist))))
4969 (when column (setq-local org-columns-default-format column)))
4970 ;; Constants.
4971 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4972 ;; Link abbreviations.
4973 (let ((links (cdr (assq 'link alist))))
4974 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4975 ;; Priorities.
4976 (let ((priorities (cdr (assq 'priorities alist))))
4977 (when priorities
4978 (setq-local org-highest-priority (nth 0 priorities))
4979 (setq-local org-lowest-priority (nth 1 priorities))
4980 (setq-local org-default-priority (nth 2 priorities))))
4981 ;; Scripts.
4982 (let ((scripts (assq 'scripts alist)))
4983 (when scripts
4984 (setq-local org-use-sub-superscripts (cdr scripts))))
4985 ;; Startup options.
4986 (let ((startup (cdr (assq 'startup alist))))
4987 (dolist (option startup)
4988 (let ((entry (assoc-string option org-startup-options t)))
4989 (when entry
4990 (let ((var (nth 1 entry))
4991 (val (nth 2 entry)))
4992 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4993 (unless (listp (symbol-value var))
4994 (set (make-local-variable var) nil))
4995 (add-to-list var val)))))))
4996 ;; TODO keywords.
4997 (setq-local org-todo-kwd-alist nil)
4998 (setq-local org-todo-key-alist nil)
4999 (setq-local org-todo-key-trigger nil)
5000 (setq-local org-todo-keywords-1 nil)
5001 (setq-local org-done-keywords nil)
5002 (setq-local org-todo-heads nil)
5003 (setq-local org-todo-sets nil)
5004 (setq-local org-todo-log-states nil)
5005 (let ((todo-sequences
5006 (or (nreverse (cdr (assq 'todo alist)))
5007 (let ((d (default-value 'org-todo-keywords)))
5008 (if (not (stringp (car d))) d
5009 ;; XXX: Backward compatibility code.
5010 (list (cons org-todo-interpretation d)))))))
5011 (dolist (sequence todo-sequences)
5012 (let* ((sequence (or (run-hook-with-args-until-success
5013 'org-todo-setup-filter-hook sequence)
5014 sequence))
5015 (sequence-type (car sequence))
5016 (keywords (cdr sequence))
5017 (sep (member "|" keywords))
5018 names alist)
5019 (dolist (k (remove "|" keywords))
5020 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5022 (error "Invalid TODO keyword %s" k))
5023 (let ((name (match-string 1 k))
5024 (key (match-string 2 k))
5025 (log (org-extract-log-state-settings k)))
5026 (push name names)
5027 (push (cons name (and key (string-to-char key))) alist)
5028 (when log (push log org-todo-log-states))))
5029 (let* ((names (nreverse names))
5030 (done (if sep (org-remove-keyword-keys (cdr sep))
5031 (last names)))
5032 (head (car names))
5033 (tail (list sequence-type head (car done) (org-last done))))
5034 (add-to-list 'org-todo-heads head 'append)
5035 (push names org-todo-sets)
5036 (setq org-done-keywords (append org-done-keywords done nil))
5037 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5038 (setq org-todo-key-alist
5039 (append org-todo-key-alist
5040 (and alist
5041 (append '((:startgroup))
5042 (nreverse alist)
5043 '((:endgroup))))))
5044 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5045 (setq org-todo-sets (nreverse org-todo-sets)
5046 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5047 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5048 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5049 ;; Compute the regular expressions and other local variables.
5050 ;; Using `org-outline-regexp-bol' would complicate them much,
5051 ;; because of the fixed white space at the end of that string.
5052 (unless org-done-keywords
5053 (setq org-done-keywords
5054 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5055 (setq org-not-done-keywords
5056 (org-delete-all org-done-keywords
5057 (copy-sequence org-todo-keywords-1))
5058 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5059 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5060 org-not-done-heading-regexp
5061 (format org-heading-keyword-regexp-format org-not-done-regexp)
5062 org-todo-line-regexp
5063 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5064 org-complex-heading-regexp
5065 (concat "^\\(\\*+\\)"
5066 "\\(?: +" org-todo-regexp "\\)?"
5067 "\\(?: +\\(\\[#.\\]\\)\\)?"
5068 "\\(?: +\\(.*?\\)\\)??"
5069 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5070 "[ \t]*$")
5071 org-complex-heading-regexp-format
5072 (concat "^\\(\\*+\\)"
5073 "\\(?: +" org-todo-regexp "\\)?"
5074 "\\(?: +\\(\\[#.\\]\\)\\)?"
5075 "\\(?: +"
5076 ;; Stats cookies can be stuck to body.
5077 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5078 "\\(%s\\)"
5079 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5080 "\\)"
5081 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5082 "[ \t]*$")
5083 org-todo-line-tags-regexp
5084 (concat "^\\(\\*+\\)"
5085 "\\(?: +" org-todo-regexp "\\)?"
5086 "\\(?: +\\(.*?\\)\\)??"
5087 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5088 "[ \t]*$"))
5089 (org-compute-latex-and-related-regexp)))))
5091 (defun org--setup-collect-keywords (regexp &optional files alist)
5092 "Return setup keywords values as an alist.
5094 REGEXP matches a subset of setup keywords. FILES is a list of
5095 file names already visited. It is used to avoid circular setup
5096 files. ALIST, when non-nil, is the alist computed so far.
5098 Return value contains the following keys: `archive', `category',
5099 `columns', `constants', `filetags', `link', `priorities',
5100 `property', `scripts', `startup', `tags' and `todo'."
5101 (org-with-wide-buffer
5102 (goto-char (point-min))
5103 (let ((case-fold-search t))
5104 (while (re-search-forward regexp nil t)
5105 (let ((element (org-element-at-point)))
5106 (when (eq (org-element-type element) 'keyword)
5107 (let ((key (org-element-property :key element))
5108 (value (org-element-property :value element)))
5109 (cond
5110 ((equal key "ARCHIVE")
5111 (when (org-string-nw-p value)
5112 (push (cons 'archive value) alist)))
5113 ((equal key "CATEGORY") (push (cons 'category value) alist))
5114 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5115 ((equal key "CONSTANTS")
5116 (let* ((constants (assq 'constants alist))
5117 (store (cdr constants)))
5118 (dolist (pair (org-split-string value))
5119 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5120 pair)
5121 (let* ((name (match-string 1 pair))
5122 (value (match-string 2 pair))
5123 (old (assoc name store)))
5124 (if old (setcdr old value)
5125 (push (cons name value) store)))))
5126 (if constants (setcdr constants store)
5127 (push (cons 'constants store) alist))))
5128 ((equal key "FILETAGS")
5129 (when (org-string-nw-p value)
5130 (let ((old (assq 'filetags alist))
5131 (new (apply #'nconc
5132 (mapcar (lambda (x) (org-split-string x ":"))
5133 (org-split-string value)))))
5134 (if old (setcdr old (append new (cdr old)))
5135 (push (cons 'filetags new) alist)))))
5136 ((equal key "LINK")
5137 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5138 (let ((links (assq 'link alist))
5139 (pair (cons (org-match-string-no-properties 1 value)
5140 (org-match-string-no-properties 2 value))))
5141 (if links (push pair (cdr links))
5142 (push (list 'link pair) alist)))))
5143 ((equal key "OPTIONS")
5144 (when (and (org-string-nw-p value)
5145 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5146 (push (cons 'scripts (read (match-string 1 value))) alist)))
5147 ((equal key "PRIORITIES")
5148 (push (cons 'priorities
5149 (let ((prio (org-split-string value)))
5150 (if (< (length prio) 3) '(?A ?C ?B)
5151 (mapcar #'string-to-char prio))))
5152 alist))
5153 ((equal key "PROPERTY")
5154 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5155 (let* ((property (assq 'property alist))
5156 (value (org--update-property-plist
5157 (org-match-string-no-properties 1 value)
5158 (org-match-string-no-properties 2 value)
5159 (cdr property))))
5160 (if property (setcdr property value)
5161 (push (cons 'property value) alist)))))
5162 ((equal key "STARTUP")
5163 (let ((startup (assq 'startup alist)))
5164 (if startup
5165 (setcdr startup
5166 (append (cdr startup) (org-split-string value)))
5167 (push (cons 'startup (org-split-string value)) alist))))
5168 ((equal key "TAGS")
5169 (let ((tag-cell (assq 'tags alist)))
5170 (if tag-cell
5171 (setcdr tag-cell
5172 (append (cdr tag-cell)
5173 '("\\n")
5174 (org-split-string value)))
5175 (push (cons 'tags (org-split-string value)) alist))))
5176 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5177 (let ((todo (assq 'todo alist))
5178 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5179 (org-split-string value))))
5180 (if todo (push value (cdr todo))
5181 (push (list 'todo value) alist))))
5182 ((equal key "SETUPFILE")
5183 (unless buffer-read-only ; Do not check in Gnus messages.
5184 (let ((f (and (org-string-nw-p value)
5185 (expand-file-name
5186 (org-remove-double-quotes value)))))
5187 (when (and f (file-readable-p f) (not (member f files)))
5188 (with-temp-buffer
5189 (setq default-directory (file-name-directory f))
5190 (insert-file-contents f)
5191 (setq alist
5192 ;; Fake Org mode to benefit from cache
5193 ;; without recurring needlessly.
5194 (let ((major-mode 'org-mode))
5195 (org--setup-collect-keywords
5196 regexp (cons f files) alist)))))))))))))))
5197 alist)
5199 (defun org--setup-process-tags (tags filetags)
5200 "Precompute variables used for tags.
5201 TAGS is a list of tags and tag group symbols, as strings.
5202 FILETAGS is a list of tags, as strings."
5203 ;; Process the file tags.
5204 (setq-local org-file-tags
5205 (mapcar #'org-add-prop-inherited filetags))
5206 ;; Provide default tags if no local tags are found.
5207 (when (and (not tags) org-tag-alist)
5208 (setq tags
5209 (mapcar (lambda (tag)
5210 (cl-case (car tag)
5211 (:startgroup "{")
5212 (:endgroup "}")
5213 (:startgrouptag "[")
5214 (:endgrouptag "]")
5215 (:grouptags ":")
5216 (:newline "\\n")
5217 (otherwise (concat (car tag)
5218 (and (characterp (cdr tag))
5219 (format "(%c)" (cdr tag)))))))
5220 org-tag-alist)))
5221 ;; Process the tags.
5222 (setq-local org-tag-groups-alist nil)
5223 (setq-local org-tag-alist nil)
5224 (let (group-flag)
5225 (while tags
5226 (let ((e (car tags)))
5227 (setq tags (cdr tags))
5228 (cond
5229 ((equal e "{")
5230 (push '(:startgroup) org-tag-alist)
5231 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5232 ((equal e "}")
5233 (push '(:endgroup) org-tag-alist)
5234 (setq group-flag nil))
5235 ((equal e "[")
5236 (push '(:startgrouptag) org-tag-alist)
5237 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5238 ((equal e "]")
5239 (push '(:endgrouptag) org-tag-alist)
5240 (setq group-flag nil))
5241 ((equal e ":")
5242 (push '(:grouptags) org-tag-alist)
5243 (setq group-flag 'append))
5244 ((equal e "\\n") (push '(:newline) org-tag-alist))
5245 ((string-match
5246 (org-re (concat "\\`\\([[:alnum:]_@#%]+"
5247 "\\|{.+?}\\)" ; regular expression
5248 "\\(?:(\\(.\\))\\)?\\'")) e)
5249 (let ((tag (match-string 1 e))
5250 (key (and (match-beginning 2)
5251 (string-to-char (match-string 2 e)))))
5252 (cond ((eq group-flag 'append)
5253 (setcar org-tag-groups-alist
5254 (append (car org-tag-groups-alist) (list tag))))
5255 (group-flag (push (list tag) org-tag-groups-alist)))
5256 ;; Push all tags in groups, no matter if they already exist.
5257 (unless (and (not group-flag) (assoc tag org-tag-alist))
5258 (push (cons tag key) org-tag-alist))))))))
5259 (setq org-tag-alist (nreverse org-tag-alist)))
5261 (defun org-file-contents (file &optional noerror)
5262 "Return the contents of FILE, as a string."
5263 (if (and file (file-readable-p file))
5264 (with-temp-buffer
5265 (insert-file-contents file)
5266 (buffer-string))
5267 (funcall (if noerror 'message 'error)
5268 "Cannot read file \"%s\"%s"
5269 file
5270 (let ((from (buffer-file-name (buffer-base-buffer))))
5271 (if from (concat " (referenced in file \"" from "\")") "")))))
5273 (defun org-extract-log-state-settings (x)
5274 "Extract the log state setting from a TODO keyword string.
5275 This will extract info from a string like \"WAIT(w@/!)\"."
5276 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5277 (let ((kw (match-string 1 x))
5278 (log1 (and (match-end 3) (match-string 3 x)))
5279 (log2 (and (match-end 4) (match-string 4 x))))
5280 (and (or log1 log2)
5281 (list kw
5282 (and log1 (if (equal log1 "!") 'time 'note))
5283 (and log2 (if (equal log2 "!") 'time 'note)))))))
5285 (defun org-remove-keyword-keys (list)
5286 "Remove a pair of parenthesis at the end of each string in LIST."
5287 (mapcar (lambda (x)
5288 (if (string-match "(.*)$" x)
5289 (substring x 0 (match-beginning 0))
5291 list))
5293 (defun org-assign-fast-keys (alist)
5294 "Assign fast keys to a keyword-key alist.
5295 Respect keys that are already there."
5296 (let (new e (alt ?0))
5297 (while (setq e (pop alist))
5298 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5299 (cdr e)) ;; Key already assigned.
5300 (push e new)
5301 (let ((clist (string-to-list (downcase (car e))))
5302 (used (append new alist)))
5303 (when (= (car clist) ?@)
5304 (pop clist))
5305 (while (and clist (rassoc (car clist) used))
5306 (pop clist))
5307 (unless clist
5308 (while (rassoc alt used)
5309 (cl-incf alt)))
5310 (push (cons (car e) (or (car clist) alt)) new))))
5311 (nreverse new)))
5313 ;;; Some variables used in various places
5315 (defvar org-window-configuration nil
5316 "Used in various places to store a window configuration.")
5317 (defvar org-selected-window nil
5318 "Used in various places to store a window configuration.")
5319 (defvar org-finish-function nil
5320 "Function to be called when `C-c C-c' is used.
5321 This is for getting out of special buffers like capture.")
5322 (defvar org-last-state)
5324 ;; Defined somewhere in this file, but used before definition.
5325 (defvar org-entities) ;; defined in org-entities.el
5326 (defvar org-struct-menu)
5327 (defvar org-org-menu)
5328 (defvar org-tbl-menu)
5330 ;;;; Define the Org-mode
5332 ;; We use a before-change function to check if a table might need
5333 ;; an update.
5334 (defvar org-table-may-need-update t
5335 "Indicates that a table might need an update.
5336 This variable is set by `org-before-change-function'.
5337 `org-table-align' sets it back to nil.")
5338 (defun org-before-change-function (_beg _end)
5339 "Every change indicates that a table might need an update."
5340 (setq org-table-may-need-update t))
5341 (defvar org-mode-map)
5342 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5343 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5344 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5345 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5346 (defvar org-table-buffer-is-an nil)
5348 (defvar bidi-paragraph-direction)
5349 (defvar buffer-face-mode-face)
5351 (require 'outline)
5352 (when (and (not (keymapp outline-mode-map)) (featurep 'allout))
5353 (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"))
5354 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5356 ;; Other stuff we need.
5357 (require 'time-date)
5358 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5359 (require 'easymenu)
5360 (autoload 'easy-menu-add "easymenu")
5361 (require 'overlay)
5363 ;; (require 'org-macs) moved higher up in the file before it is first used
5364 (require 'org-entities)
5365 ;; (require 'org-compat) moved higher up in the file before it is first used
5366 (require 'org-faces)
5367 (require 'org-list)
5368 (require 'org-pcomplete)
5369 (require 'org-src)
5370 (require 'org-footnote)
5371 (require 'org-macro)
5373 ;; babel
5374 (require 'ob)
5376 ;;;###autoload
5377 (define-derived-mode org-mode outline-mode "Org"
5378 "Outline-based notes management and organizer, alias
5379 \"Carsten's outline-mode for keeping track of everything.\"
5381 Org-mode develops organizational tasks around a NOTES file which
5382 contains information about projects as plain text. Org-mode is
5383 implemented on top of outline-mode, which is ideal to keep the content
5384 of large files well structured. It supports ToDo items, deadlines and
5385 time stamps, which magically appear in the diary listing of the Emacs
5386 calendar. Tables are easily created with a built-in table editor.
5387 Plain text URL-like links connect to websites, emails (VM), Usenet
5388 messages (Gnus), BBDB entries, and any files related to the project.
5389 For printing and sharing of notes, an Org-mode file (or a part of it)
5390 can be exported as a structured ASCII or HTML file.
5392 The following commands are available:
5394 \\{org-mode-map}"
5396 ;; Get rid of Outline menus, they are not needed
5397 ;; Need to do this here because define-derived-mode sets up
5398 ;; the keymap so late. Still, it is a waste to call this each time
5399 ;; we switch another buffer into org-mode.
5400 (if (featurep 'xemacs)
5401 (when (boundp 'outline-mode-menu-heading)
5402 ;; Assume this is Greg's port, it uses easymenu
5403 (easy-menu-remove outline-mode-menu-heading)
5404 (easy-menu-remove outline-mode-menu-show)
5405 (easy-menu-remove outline-mode-menu-hide))
5406 (define-key org-mode-map [menu-bar headings] 'undefined)
5407 (define-key org-mode-map [menu-bar hide] 'undefined)
5408 (define-key org-mode-map [menu-bar show] 'undefined))
5410 (org-load-modules-maybe)
5411 (when (featurep 'xemacs)
5412 (easy-menu-add org-org-menu)
5413 (easy-menu-add org-tbl-menu))
5414 (org-install-agenda-files-menu)
5415 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5416 (add-to-invisibility-spec '(org-cwidth))
5417 (add-to-invisibility-spec '(org-hide-block . t))
5418 (when (featurep 'xemacs)
5419 (setq-local line-move-ignore-invisible t))
5420 (setq-local outline-regexp org-outline-regexp)
5421 (setq-local outline-level 'org-outline-level)
5422 (setq bidi-paragraph-direction 'left-to-right)
5423 (when (and org-ellipsis
5424 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5425 (fboundp 'make-glyph-code))
5426 (unless org-display-table
5427 (setq org-display-table (make-display-table)))
5428 (set-display-table-slot
5429 org-display-table 4
5430 (vconcat (mapcar
5431 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5432 org-ellipsis)))
5433 (if (stringp org-ellipsis) org-ellipsis "..."))))
5434 (setq buffer-display-table org-display-table))
5435 (org-set-regexps-and-options)
5436 (org-set-font-lock-defaults)
5437 (when (and org-tag-faces (not org-tags-special-faces-re))
5438 ;; tag faces set outside customize.... force initialization.
5439 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5440 ;; Calc embedded
5441 (setq-local calc-embedded-open-mode "# ")
5442 ;; Modify a few syntax entries
5443 (modify-syntax-entry ?@ "w")
5444 (modify-syntax-entry ?\" "\"")
5445 (modify-syntax-entry ?\\ "_")
5446 (modify-syntax-entry ?~ "_")
5447 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5448 ;; Activate before-change-function
5449 (setq-local org-table-may-need-update t)
5450 (org-add-hook 'before-change-functions 'org-before-change-function nil 'local)
5451 ;; Check for running clock before killing a buffer
5452 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5453 ;; Initialize macros templates.
5454 (org-macro-initialize-templates)
5455 ;; Initialize radio targets.
5456 (org-update-radio-target-regexp)
5457 ;; Indentation.
5458 (setq-local indent-line-function 'org-indent-line)
5459 (setq-local indent-region-function 'org-indent-region)
5460 ;; Filling and auto-filling.
5461 (org-setup-filling)
5462 ;; Comments.
5463 (org-setup-comments-handling)
5464 ;; Initialize cache.
5465 (org-element-cache-reset)
5466 ;; Beginning/end of defun
5467 (setq-local beginning-of-defun-function 'org-backward-element)
5468 (setq-local end-of-defun-function
5469 (lambda ()
5470 (if (not (org-at-heading-p))
5471 (org-forward-element)
5472 (org-forward-element)
5473 (forward-char -1))))
5474 ;; Next error for sparse trees
5475 (setq-local next-error-function 'org-occur-next-match)
5476 ;; Make sure dependence stuff works reliably, even for users who set it
5477 ;; too late :-(
5478 (if org-enforce-todo-dependencies
5479 (add-hook 'org-blocker-hook
5480 'org-block-todo-from-children-or-siblings-or-parent)
5481 (remove-hook 'org-blocker-hook
5482 'org-block-todo-from-children-or-siblings-or-parent))
5483 (if org-enforce-todo-checkbox-dependencies
5484 (add-hook 'org-blocker-hook
5485 'org-block-todo-from-checkboxes)
5486 (remove-hook 'org-blocker-hook
5487 'org-block-todo-from-checkboxes))
5489 ;; Align options lines
5490 (setq-local
5491 align-mode-rules-list
5492 '((org-in-buffer-settings
5493 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5494 (modes . '(org-mode)))))
5496 ;; Imenu
5497 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5499 ;; Make isearch reveal context
5500 (if (or (featurep 'xemacs)
5501 (not (boundp 'outline-isearch-open-invisible-function)))
5502 ;; Emacs 21 and XEmacs make use of the hook
5503 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5504 ;; Emacs 22 deals with this through a special variable
5505 (setq-local outline-isearch-open-invisible-function
5506 (lambda (&rest _) (org-show-context 'isearch))))
5508 ;; Setup the pcomplete hooks
5509 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5510 (setq-local pcomplete-command-name-function 'org-command-at-point)
5511 (setq-local pcomplete-default-completion-function 'ignore)
5512 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5513 (setq-local pcomplete-termination-string "")
5514 (setq-local buffer-face-mode-face 'org-default)
5516 ;; If empty file that did not turn on Org mode automatically, make
5517 ;; it to.
5518 (when (and org-insert-mode-line-in-empty-file
5519 (org-called-interactively-p 'any)
5520 (= (point-min) (point-max)))
5521 (insert "# -*- mode: org -*-\n\n"))
5522 (unless org-inhibit-startup
5523 (org-unmodified
5524 (when org-startup-with-beamer-mode (org-beamer-mode))
5525 (when org-startup-align-all-tables
5526 (org-table-map-tables #'org-table-align t))
5527 (when org-startup-with-inline-images (org-display-inline-images))
5528 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5529 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5530 (when org-startup-truncated (setq truncate-lines t))
5531 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5532 (org-refresh-effort-properties)))
5533 ;; Try to set `org-hide' face correctly.
5534 (let ((foreground (org-find-invisible-foreground)))
5535 (when foreground
5536 (set-face-foreground 'org-hide foreground))))
5538 ;; Update `customize-package-emacs-version-alist'
5539 (add-to-list 'customize-package-emacs-version-alist
5540 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5541 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5542 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5544 (defvar org-mode-transpose-word-syntax-table
5545 (let ((st (make-syntax-table text-mode-syntax-table)))
5546 (dolist (c org-emphasis-alist st)
5547 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5549 (when (fboundp 'abbrev-table-put)
5550 (abbrev-table-put org-mode-abbrev-table
5551 :parents (list text-mode-abbrev-table)))
5553 (defun org-find-invisible-foreground ()
5554 (let ((candidates (remove
5555 "unspecified-bg"
5556 (nconc
5557 (list (face-background 'default)
5558 (face-background 'org-default))
5559 (mapcar
5560 (lambda (alist)
5561 (when (boundp alist)
5562 (cdr (assoc 'background-color (symbol-value alist)))))
5563 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5564 (list (face-foreground 'org-hide))))))
5565 (car (remove nil candidates))))
5567 (defun org-current-time (&optional rounding-minutes past)
5568 "Current time, possibly rounded to ROUNDING-MINUTES.
5569 When ROUNDING-MINUTES is not an integer, fall back on the car of
5570 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5571 the rounding returns a past time."
5572 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5573 (car org-time-stamp-rounding-minutes)))
5574 (time (decode-time)) res)
5575 (if (< r 1)
5576 (current-time)
5577 (setq res
5578 (apply 'encode-time
5579 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5580 (nthcdr 2 time))))
5581 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5582 (seconds-to-time (- (org-float-time res) (* r 60)))
5583 res))))
5585 (defun org-today ()
5586 "Return today date, considering `org-extend-today-until'."
5587 (time-to-days
5588 (time-subtract (current-time)
5589 (list 0 (* 3600 org-extend-today-until) 0))))
5591 ;;;; Font-Lock stuff, including the activators
5593 (defvar org-mouse-map (make-sparse-keymap))
5594 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5595 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5596 (when org-mouse-1-follows-link
5597 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5598 (when org-tab-follows-link
5599 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5600 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5602 (require 'font-lock)
5604 (defconst org-non-link-chars "]\t\n\r<>")
5605 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5606 "file+sys" "news" "shell" "elisp" "doi" "message"
5607 "help"))
5608 (defvar org-link-types-re nil
5609 "Matches a link that has a url-like prefix like \"http:\"")
5610 (defvar org-link-re-with-space nil
5611 "Matches a link with spaces, optional angular brackets around it.")
5612 (defvar org-link-re-with-space2 nil
5613 "Matches a link with spaces, optional angular brackets around it.")
5614 (defvar org-link-re-with-space3 nil
5615 "Matches a link with spaces, only for internal part in bracket links.")
5616 (defvar org-angle-link-re nil
5617 "Matches link with angular brackets, spaces are allowed.")
5618 (defvar org-plain-link-re nil
5619 "Matches plain link, without spaces.")
5620 (defvar org-bracket-link-regexp nil
5621 "Matches a link in double brackets.")
5622 (defvar org-bracket-link-analytic-regexp nil
5623 "Regular expression used to analyze links.
5624 Here is what the match groups contain after a match:
5625 1: http:
5626 2: http
5627 3: path
5628 4: [desc]
5629 5: desc")
5630 (defvar org-bracket-link-analytic-regexp++ nil
5631 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5632 (defvar org-any-link-re nil
5633 "Regular expression matching any link.")
5635 (defconst org-match-sexp-depth 3
5636 "Number of stacked braces for sub/superscript matching.")
5638 (defun org-create-multibrace-regexp (left right n)
5639 "Create a regular expression which will match a balanced sexp.
5640 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5641 as single character strings.
5642 The regexp returned will match the entire expression including the
5643 delimiters. It will also define a single group which contains the
5644 match except for the outermost delimiters. The maximum depth of
5645 stacked delimiters is N. Escaping delimiters is not possible."
5646 (let* ((nothing (concat "[^" left right "]*?"))
5647 (or "\\|")
5648 (re nothing)
5649 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5650 (while (> n 1)
5651 (setq n (1- n)
5652 re (concat re or next)
5653 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5654 (concat left "\\(" re "\\)" right)))
5656 (defconst org-match-substring-regexp
5657 (concat
5658 "\\(\\S-\\)\\([_^]\\)\\("
5659 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5660 "\\|"
5661 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5662 "\\|"
5663 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5664 "The regular expression matching a sub- or superscript.")
5666 (defconst org-match-substring-with-braces-regexp
5667 (concat
5668 "\\(\\S-\\)\\([_^]\\)"
5669 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5670 "The regular expression matching a sub- or superscript, forcing braces.")
5672 (defun org-make-link-regexps ()
5673 "Update the link regular expressions.
5674 This should be called after the variable `org-link-types' has changed."
5675 (let ((types-re (regexp-opt org-link-types t)))
5676 (setq org-link-types-re
5677 (concat "\\`" types-re ":")
5678 org-link-re-with-space
5679 (concat "<?" types-re ":"
5680 "\\([^" org-non-link-chars " ]"
5681 "[^" org-non-link-chars "]*"
5682 "[^" org-non-link-chars " ]\\)>?")
5683 org-link-re-with-space2
5684 (concat "<?" types-re ":"
5685 "\\([^" org-non-link-chars " ]"
5686 "[^\t\n\r]*"
5687 "[^" org-non-link-chars " ]\\)>?")
5688 org-link-re-with-space3
5689 (concat "<?" types-re ":"
5690 "\\([^" org-non-link-chars " ]"
5691 "[^\t\n\r]*\\)")
5692 org-angle-link-re
5693 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5694 types-re)
5695 org-plain-link-re
5696 (concat
5697 "\\<" types-re ":"
5698 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5699 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5700 org-bracket-link-regexp
5701 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5702 org-bracket-link-analytic-regexp
5703 (concat
5704 "\\[\\["
5705 "\\(" types-re ":\\)?"
5706 "\\([^]]+\\)"
5707 "\\]"
5708 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5709 "\\]")
5710 org-bracket-link-analytic-regexp++
5711 (concat
5712 "\\[\\["
5713 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5714 "\\([^]]+\\)"
5715 "\\]"
5716 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5717 "\\]")
5718 org-any-link-re
5719 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5720 org-angle-link-re "\\)\\|\\("
5721 org-plain-link-re "\\)"))))
5723 (org-make-link-regexps)
5725 (defvar org-emph-face nil)
5727 (defun org-do-emphasis-faces (limit)
5728 "Run through the buffer and emphasize strings."
5729 (let (rtn a)
5730 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5731 (let* ((border (char-after (match-beginning 3)))
5732 (bre (regexp-quote (char-to-string border))))
5733 (when (and (not (= border (char-after (match-beginning 4))))
5734 (not (string-match-p (concat bre ".*" bre)
5735 (replace-regexp-in-string
5736 "\n" " "
5737 (substring (match-string 2) 1 -1)))))
5738 (setq rtn t)
5739 (setq a (assoc (match-string 3) org-emphasis-alist))
5740 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5741 'face
5742 (nth 1 a))
5743 (and (nth 2 a)
5744 (org-remove-flyspell-overlays-in
5745 (match-beginning 0) (match-end 0)))
5746 (add-text-properties (match-beginning 2) (match-end 2)
5747 '(font-lock-multiline t org-emphasis t))
5748 (when org-hide-emphasis-markers
5749 (add-text-properties (match-end 4) (match-beginning 5)
5750 '(invisible org-link))
5751 (add-text-properties (match-beginning 3) (match-end 3)
5752 '(invisible org-link)))))
5753 (goto-char (1+ (match-beginning 0))))
5754 rtn))
5756 (defun org-emphasize (&optional char)
5757 "Insert or change an emphasis, i.e. a font like bold or italic.
5758 If there is an active region, change that region to a new emphasis.
5759 If there is no region, just insert the marker characters and position
5760 the cursor between them.
5761 CHAR should be the marker character. If it is a space, it means to
5762 remove the emphasis of the selected region.
5763 If CHAR is not given (for example in an interactive call) it will be
5764 prompted for."
5765 (interactive)
5766 (let ((erc org-emphasis-regexp-components)
5767 (string "") beg end move s)
5768 (if (org-region-active-p)
5769 (setq beg (region-beginning)
5770 end (region-end)
5771 string (buffer-substring beg end))
5772 (setq move t))
5774 (unless char
5775 (message "Emphasis marker or tag: [%s]"
5776 (mapconcat #'car org-emphasis-alist ""))
5777 (setq char (read-char-exclusive)))
5778 (if (equal char ?\s)
5779 (setq s ""
5780 move nil)
5781 (unless (assoc (char-to-string char) org-emphasis-alist)
5782 (user-error "No such emphasis marker: \"%c\"" char))
5783 (setq s (char-to-string char)))
5784 (while (and (> (length string) 1)
5785 (equal (substring string 0 1) (substring string -1))
5786 (assoc (substring string 0 1) org-emphasis-alist))
5787 (setq string (substring string 1 -1)))
5788 (setq string (concat s string s))
5789 (when beg (delete-region beg end))
5790 (unless (or (bolp)
5791 (string-match (concat "[" (nth 0 erc) "\n]")
5792 (char-to-string (char-before (point)))))
5793 (insert " "))
5794 (unless (or (eobp)
5795 (string-match (concat "[" (nth 1 erc) "\n]")
5796 (char-to-string (char-after (point)))))
5797 (insert " ") (backward-char 1))
5798 (insert string)
5799 (and move (backward-char 1))))
5801 (defconst org-nonsticky-props
5802 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5804 (defsubst org-rear-nonsticky-at (pos)
5805 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5807 (defun org-activate-plain-links (limit)
5808 "Add link properties for plain links."
5809 (let (f hl)
5810 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5811 (not (member 'org-tag
5812 (get-text-property (1- (match-beginning 0)) 'face)))
5813 (not (org-in-src-block-p)))
5814 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5815 (setq f (get-text-property (match-beginning 0) 'face))
5816 (setq hl (org-match-string-no-properties 0))
5817 (unless (or (eq f 'org-tag)
5818 (and (listp f) (memq 'org-tag f)))
5819 (add-text-properties (match-beginning 0) (match-end 0)
5820 (list 'mouse-face 'highlight
5821 'face 'org-link
5822 'htmlize-link `(:uri ,hl)
5823 'keymap org-mouse-map))
5824 (org-rear-nonsticky-at (match-end 0)))
5825 t)))
5827 (defun org-activate-code (limit)
5828 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5829 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5830 (remove-text-properties (match-beginning 0) (match-end 0)
5831 '(display t invisible t intangible t))
5834 (defcustom org-src-fontify-natively t
5835 "When non-nil, fontify code in code blocks."
5836 :type 'boolean
5837 :version "24.4"
5838 :package-version '(Org . "8.3")
5839 :group 'org-appearance
5840 :group 'org-babel)
5842 (defcustom org-allow-promoting-top-level-subtree nil
5843 "When non-nil, allow promoting a top level subtree.
5844 The leading star of the top level headline will be replaced
5845 by a #."
5846 :type 'boolean
5847 :version "24.1"
5848 :group 'org-appearance)
5850 (defun org-fontify-meta-lines-and-blocks (limit)
5851 (condition-case nil
5852 (org-fontify-meta-lines-and-blocks-1 limit)
5853 (error (message "org-mode fontification error"))))
5855 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5856 "Fontify #+ lines and blocks."
5857 (let ((case-fold-search t))
5858 (when (re-search-forward
5859 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5860 limit t)
5861 (let ((beg (match-beginning 0))
5862 (block-start (match-end 0))
5863 (block-end nil)
5864 (lang (match-string 7))
5865 (beg1 (line-beginning-position 2))
5866 (dc1 (downcase (match-string 2)))
5867 (dc3 (downcase (match-string 3)))
5868 end end1 quoting block-type)
5869 (cond
5870 ((and (match-end 4) (equal dc3 "+begin"))
5871 ;; Truly a block
5872 (setq block-type (downcase (match-string 5))
5873 quoting (member block-type org-protecting-blocks))
5874 (when (re-search-forward
5875 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5876 nil t) ;; on purpose, we look further than LIMIT
5877 (setq end (min (point-max) (match-end 0))
5878 end1 (min (point-max) (1- (match-beginning 0))))
5879 (setq block-end (match-beginning 0))
5880 (when quoting
5881 (org-remove-flyspell-overlays-in beg1 end1)
5882 (remove-text-properties beg end
5883 '(display t invisible t intangible t)))
5884 (add-text-properties
5885 beg end '(font-lock-fontified t font-lock-multiline t))
5886 (add-text-properties beg beg1 '(face org-meta-line))
5887 (org-remove-flyspell-overlays-in beg beg1)
5888 (add-text-properties ; For end_src
5889 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5890 (org-remove-flyspell-overlays-in end1 end)
5891 (cond
5892 ((and lang (not (string= lang "")) org-src-fontify-natively)
5893 (org-src-font-lock-fontify-block lang block-start block-end)
5894 (add-text-properties beg1 block-end '(src-block t)))
5895 (quoting
5896 (add-text-properties beg1 (min (point-max) (1+ end1))
5897 '(face org-block))) ; end of source block
5898 ((not org-fontify-quote-and-verse-blocks))
5899 ((string= block-type "quote")
5900 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5901 ((string= block-type "verse")
5902 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5903 (add-text-properties beg beg1 '(face org-block-begin-line))
5904 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5905 '(face org-block-end-line))
5907 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5908 (org-remove-flyspell-overlays-in
5909 (match-beginning 0)
5910 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5911 (add-text-properties
5912 beg (match-end 3)
5913 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5914 '(font-lock-fontified t invisible t)
5915 '(font-lock-fontified t face org-document-info-keyword)))
5916 (add-text-properties
5917 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5918 (if (string-equal dc1 "+title:")
5919 '(font-lock-fontified t face org-document-title)
5920 '(font-lock-fontified t face org-document-info))))
5921 ((equal dc1 "+caption:")
5922 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5923 (remove-text-properties (match-beginning 0) (match-end 0)
5924 '(display t invisible t intangible t))
5925 (add-text-properties (match-beginning 1) (match-end 3)
5926 '(font-lock-fontified t face org-meta-line))
5927 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5928 '(font-lock-fontified t face org-block))
5930 ((member dc3 '(" " ""))
5931 (org-remove-flyspell-overlays-in beg (match-end 0))
5932 (add-text-properties
5933 beg (match-end 0)
5934 '(font-lock-fontified t face font-lock-comment-face)))
5935 (t ;; just any other in-buffer setting, but not indented
5936 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5937 (remove-text-properties (match-beginning 0) (match-end 0)
5938 '(display t invisible t intangible t))
5939 (add-text-properties beg (match-end 0)
5940 '(font-lock-fontified t face org-meta-line))
5941 t))))))
5943 (defun org-fontify-drawers (limit)
5944 "Fontify drawers."
5945 (when (re-search-forward org-drawer-regexp limit t)
5946 (add-text-properties
5947 (match-beginning 0) (match-end 0)
5948 '(font-lock-fontified t face org-special-keyword))
5949 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5952 (defun org-fontify-macros (limit)
5953 "Fontify macros."
5954 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5955 (add-text-properties
5956 (match-beginning 0) (match-end 0)
5957 '(font-lock-fontified t face org-macro))
5958 (when org-hide-macro-markers
5959 (add-text-properties (match-end 2) (match-beginning 2)
5960 '(invisible t))
5961 (add-text-properties (match-beginning 1) (match-end 1)
5962 '(invisible t)))
5963 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5966 (defun org-activate-angle-links (limit)
5967 "Add text properties for angle links."
5968 (when (and (re-search-forward org-angle-link-re limit t)
5969 (not (org-in-src-block-p)))
5970 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5971 (add-text-properties (match-beginning 0) (match-end 0)
5972 (list 'mouse-face 'highlight
5973 'keymap org-mouse-map
5974 'font-lock-multiline t))
5975 (org-rear-nonsticky-at (match-end 0))
5978 (defun org-activate-footnote-links (limit)
5979 "Add text properties for footnotes."
5980 (let ((fn (org-footnote-next-reference-or-definition limit)))
5981 (when fn
5982 (let* ((beg (nth 1 fn))
5983 (end (nth 2 fn))
5984 (label (car fn))
5985 (referencep (/= (line-beginning-position) beg)))
5986 (when (and referencep (nth 3 fn))
5987 (save-excursion
5988 (goto-char beg)
5989 (search-forward (or label "fn:"))
5990 (org-remove-flyspell-overlays-in beg (match-end 0))))
5991 (add-text-properties beg end
5992 (list 'mouse-face 'highlight
5993 'keymap org-mouse-map
5994 'help-echo
5995 (if referencep "Footnote reference"
5996 "Footnote definition")
5997 'font-lock-fontified t
5998 'font-lock-multiline t
5999 'face 'org-footnote))))))
6001 (defun org-activate-bracket-links (limit)
6002 "Add text properties for bracketed links."
6003 (when (and (re-search-forward org-bracket-link-regexp limit t)
6004 (not (org-in-src-block-p)))
6005 (let* ((hl (org-match-string-no-properties 1))
6006 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6007 (ip (org-maybe-intangible
6008 (list 'invisible 'org-link
6009 'keymap org-mouse-map 'mouse-face 'highlight
6010 'font-lock-multiline t 'help-echo help
6011 'htmlize-link `(:uri ,hl))))
6012 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6013 'font-lock-multiline t 'help-echo help
6014 'htmlize-link `(:uri ,hl))))
6015 ;; We need to remove the invisible property here. Table narrowing
6016 ;; may have made some of this invisible.
6017 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6018 (remove-text-properties (match-beginning 0) (match-end 0)
6019 '(invisible nil))
6020 (if (match-end 3)
6021 (progn
6022 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6023 (org-rear-nonsticky-at (match-beginning 3))
6024 (add-text-properties (match-beginning 3) (match-end 3) vp)
6025 (org-rear-nonsticky-at (match-end 3))
6026 (add-text-properties (match-end 3) (match-end 0) ip)
6027 (org-rear-nonsticky-at (match-end 0)))
6028 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6029 (org-rear-nonsticky-at (match-beginning 1))
6030 (add-text-properties (match-beginning 1) (match-end 1) vp)
6031 (org-rear-nonsticky-at (match-end 1))
6032 (add-text-properties (match-end 1) (match-end 0) ip)
6033 (org-rear-nonsticky-at (match-end 0)))
6034 t)))
6036 (defun org-activate-dates (limit)
6037 "Add text properties for dates."
6038 (when (and (re-search-forward org-tsr-regexp-both limit t)
6039 (not (equal (char-before (match-beginning 0)) 91)))
6040 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6041 (add-text-properties (match-beginning 0) (match-end 0)
6042 (list 'mouse-face 'highlight
6043 'keymap org-mouse-map))
6044 (org-rear-nonsticky-at (match-end 0))
6045 (when org-display-custom-times
6046 (if (match-end 3)
6047 (org-display-custom-time (match-beginning 3) (match-end 3))
6048 (org-display-custom-time (match-beginning 1) (match-end 1))))
6051 (defvar-local org-target-link-regexp nil
6052 "Regular expression matching radio targets in plain text.")
6054 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6055 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6056 border border border))
6057 "Regular expression matching a link target.")
6059 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6060 "Regular expression matching a radio target.")
6062 (defconst org-any-target-regexp
6063 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6064 "Regular expression matching any target.")
6066 (defun org-activate-target-links (limit)
6067 "Add text properties for target matches."
6068 (when org-target-link-regexp
6069 (let ((case-fold-search t))
6070 (when (re-search-forward org-target-link-regexp limit t)
6071 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6072 (add-text-properties (match-beginning 1) (match-end 1)
6073 (list 'mouse-face 'highlight
6074 'keymap org-mouse-map
6075 'help-echo "Radio target link"
6076 'org-linked-text t))
6077 (org-rear-nonsticky-at (match-end 1))
6078 t))))
6080 (defun org-update-radio-target-regexp ()
6081 "Find all radio targets in this file and update the regular expression.
6082 Also refresh fontification if needed."
6083 (interactive)
6084 (let ((old-regexp org-target-link-regexp)
6085 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6086 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6087 (targets
6088 (org-with-wide-buffer
6089 (goto-char (point-min))
6090 (let (rtn)
6091 (while (re-search-forward org-radio-target-regexp nil t)
6092 ;; Make sure point is really within the object.
6093 (backward-char)
6094 (let ((obj (org-element-context)))
6095 (when (eq (org-element-type obj) 'radio-target)
6096 (cl-pushnew (org-element-property :value obj) rtn
6097 :test #'equal))))
6098 rtn))))
6099 (setq org-target-link-regexp
6100 (and targets
6101 (concat before-re
6102 (mapconcat
6103 (lambda (x)
6104 (replace-regexp-in-string
6105 " +" "\\s-+" (regexp-quote x) t t))
6106 targets
6107 "\\|")
6108 after-re)))
6109 (unless (equal old-regexp org-target-link-regexp)
6110 ;; Clean-up cache.
6111 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6112 ((not org-target-link-regexp) old-regexp)
6114 (concat before-re
6115 (mapconcat
6116 (lambda (re)
6117 (substring re (length before-re)
6118 (- (length after-re))))
6119 (list old-regexp org-target-link-regexp)
6120 "\\|")
6121 after-re)))))
6122 (org-with-wide-buffer
6123 (goto-char (point-min))
6124 (while (re-search-forward regexp nil t)
6125 (org-element-cache-refresh (match-beginning 1)))))
6126 ;; Re fontify buffer.
6127 (when (memq 'radio org-highlight-links)
6128 (org-restart-font-lock)))))
6130 (defun org-hide-wide-columns (limit)
6131 (let (s e)
6132 (setq s (text-property-any (point) (or limit (point-max))
6133 'org-cwidth t))
6134 (when s
6135 (setq e (next-single-property-change s 'org-cwidth))
6136 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6137 (goto-char e)
6138 t)))
6140 (defvar org-latex-and-related-regexp nil
6141 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6143 (defun org-compute-latex-and-related-regexp ()
6144 "Compute regular expression for LaTeX, entities and sub/superscript.
6145 Result depends on variable `org-highlight-latex-and-related'."
6146 (setq-local
6147 org-latex-and-related-regexp
6148 (let* ((re-sub
6149 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6150 ((eq org-use-sub-superscripts '{})
6151 (list org-match-substring-with-braces-regexp))
6152 (org-use-sub-superscripts (list org-match-substring-regexp))))
6153 (re-latex
6154 (when (memq 'latex org-highlight-latex-and-related)
6155 (let ((matchers (plist-get org-format-latex-options :matchers)))
6156 (delq nil
6157 (mapcar (lambda (x)
6158 (and (member (car x) matchers) (nth 1 x)))
6159 org-latex-regexps)))))
6160 (re-entities
6161 (when (memq 'entities org-highlight-latex-and-related)
6162 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6163 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6165 (defun org-do-latex-and-related (limit)
6166 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6167 LIMIT bounds the search for syntax to highlight. Stop at first
6168 highlighted object, if any. Return t if some highlighting was
6169 done, nil otherwise."
6170 (when (org-string-nw-p org-latex-and-related-regexp)
6171 (catch 'found
6172 (while (re-search-forward org-latex-and-related-regexp limit t)
6173 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6174 'face))
6175 '(org-code org-verbatim underline))
6176 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6177 '(?_ ?^))
6179 0)))
6180 (font-lock-prepend-text-property
6181 (+ offset (match-beginning 0)) (match-end 0)
6182 'face 'org-latex-and-related)
6183 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6184 '(font-lock-multiline t)))
6185 (throw 'found t)))
6186 nil)))
6188 (defun org-restart-font-lock ()
6189 "Restart `font-lock-mode', to force refontification."
6190 (when (and (boundp 'font-lock-mode) font-lock-mode)
6191 (font-lock-mode -1)
6192 (font-lock-mode 1)))
6194 (defun org-activate-tags (limit)
6195 (when (re-search-forward
6196 (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$") limit t)
6197 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6198 (add-text-properties (match-beginning 1) (match-end 1)
6199 (list 'mouse-face 'highlight
6200 'keymap org-mouse-map))
6201 (org-rear-nonsticky-at (match-end 1))
6204 (defun org-outline-level ()
6205 "Compute the outline level of the heading at point.
6207 If this is called at a normal headline, the level is the number
6208 of stars. Use `org-reduced-level' to remove the effect of
6209 `org-odd-levels'. Unlike to `org-current-level', this function
6210 takes into consideration inlinetasks."
6211 (org-with-wide-buffer
6212 (end-of-line)
6213 (if (re-search-backward org-outline-regexp-bol nil t)
6214 (1- (- (match-end 0) (match-beginning 0)))
6215 0)))
6217 (defvar org-font-lock-keywords nil)
6219 (defsubst org-re-property (property &optional literal allow-null value)
6220 "Return a regexp matching a PROPERTY line.
6222 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6223 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6224 non-nil, match properties even without a value.
6226 Match group 3 is set to the value when it exists. If there is no
6227 value and ALLOW-NULL is non-nil, it is set to the empty string.
6229 With optional argument VALUE, match only property lines with
6230 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6231 unless LITERAL is non-nil."
6232 (concat
6233 "^\\(?4:[ \t]*\\)"
6234 (format "\\(?1::\\(?2:%s\\):\\)"
6235 (if literal property (regexp-quote property)))
6236 (cond (value
6237 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6238 (if literal value (regexp-quote value))))
6239 (allow-null
6240 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6242 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6244 (defconst org-property-re
6245 (org-re-property "\\S-+" 'literal t)
6246 "Regular expression matching a property line.
6247 There are four matching groups:
6248 1: :PROPKEY: including the leading and trailing colon,
6249 2: PROPKEY without the leading and trailing colon,
6250 3: PROPVAL without leading or trailing spaces,
6251 4: the indentation of the current line,
6252 5: trailing whitespace.")
6254 (defvar org-font-lock-hook nil
6255 "Functions to be called for special font lock stuff.")
6257 (defvar org-font-lock-set-keywords-hook nil
6258 "Functions that can manipulate `org-font-lock-extra-keywords'.
6259 This is called after `org-font-lock-extra-keywords' is defined, but before
6260 it is installed to be used by font lock. This can be useful if something
6261 needs to be inserted at a specific position in the font-lock sequence.")
6263 (defun org-font-lock-hook (limit)
6264 "Run `org-font-lock-hook' within LIMIT."
6265 (run-hook-with-args 'org-font-lock-hook limit))
6267 (defun org-set-font-lock-defaults ()
6268 "Set font lock defaults for the current buffer."
6269 (let* ((em org-fontify-emphasized-text)
6270 (lk org-highlight-links)
6271 (org-font-lock-extra-keywords
6272 (list
6273 ;; Call the hook
6274 '(org-font-lock-hook)
6275 ;; Headlines
6276 `(,(if org-fontify-whole-heading-line
6277 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6278 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6279 (1 (org-get-level-face 1))
6280 (2 (org-get-level-face 2))
6281 (3 (org-get-level-face 3)))
6282 ;; Table lines
6283 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6284 (1 'org-table t))
6285 ;; Table internals
6286 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6287 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6288 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6289 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6290 ;; Drawers
6291 '(org-fontify-drawers)
6292 ;; Properties
6293 (list org-property-re
6294 '(1 'org-special-keyword t)
6295 '(3 'org-property-value t))
6296 ;; Links
6297 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6298 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6299 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6300 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6301 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6302 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6303 (when (memq 'footnote lk) '(org-activate-footnote-links))
6304 ;; Targets.
6305 (list org-any-target-regexp '(0 'org-target t))
6306 ;; Diary sexps.
6307 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6308 ;; Macro
6309 '(org-fontify-macros)
6310 '(org-hide-wide-columns (0 nil append))
6311 ;; TODO keyword
6312 (list (format org-heading-keyword-regexp-format
6313 org-todo-regexp)
6314 '(2 (org-get-todo-face 2) t))
6315 ;; DONE
6316 (if org-fontify-done-headline
6317 (list (format org-heading-keyword-regexp-format
6318 (concat
6319 "\\(?:"
6320 (mapconcat 'regexp-quote org-done-keywords "\\|")
6321 "\\)"))
6322 '(2 'org-headline-done t))
6323 nil)
6324 ;; Priorities
6325 '(org-font-lock-add-priority-faces)
6326 ;; Tags
6327 '(org-font-lock-add-tag-faces)
6328 ;; Tags groups
6329 (when (and org-group-tags org-tag-groups-alist)
6330 (list (concat org-outline-regexp-bol ".+\\(:"
6331 (regexp-opt (mapcar 'car org-tag-groups-alist))
6332 ":\\).*$")
6333 '(1 'org-tag-group prepend)))
6334 ;; Special keywords
6335 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6336 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6337 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6338 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6339 ;; Emphasis
6340 (when em
6341 (if (featurep 'xemacs)
6342 '(org-do-emphasis-faces (0 nil append))
6343 '(org-do-emphasis-faces)))
6344 ;; Checkboxes
6345 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6346 1 'org-checkbox prepend)
6347 (when (cdr (assq 'checkbox org-list-automatic-rules))
6348 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6349 (0 (org-get-checkbox-statistics-face) t)))
6350 ;; Description list items
6351 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6352 1 'org-list-dt prepend)
6353 ;; ARCHIVEd headings
6354 (list (concat
6355 org-outline-regexp-bol
6356 "\\(.*:" org-archive-tag ":.*\\)")
6357 '(1 'org-archived prepend))
6358 ;; Specials
6359 '(org-do-latex-and-related)
6360 '(org-fontify-entities)
6361 '(org-raise-scripts)
6362 ;; Code
6363 '(org-activate-code (1 'org-code t))
6364 ;; COMMENT
6365 (list (format
6366 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6367 org-todo-regexp
6368 org-comment-string)
6369 '(9 'org-special-keyword t))
6370 ;; Blocks and meta lines
6371 '(org-fontify-meta-lines-and-blocks))))
6372 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6373 (run-hooks 'org-font-lock-set-keywords-hook)
6374 ;; Now set the full font-lock-keywords
6375 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6376 (setq-local font-lock-defaults
6377 '(org-font-lock-keywords t nil nil backward-paragraph))
6378 (kill-local-variable 'font-lock-keywords) nil))
6380 (defun org-toggle-pretty-entities ()
6381 "Toggle the composition display of entities as UTF8 characters."
6382 (interactive)
6383 (setq-local org-pretty-entities (not org-pretty-entities))
6384 (org-restart-font-lock)
6385 (if org-pretty-entities
6386 (message "Entities are now displayed as UTF8 characters")
6387 (save-restriction
6388 (widen)
6389 (org-decompose-region (point-min) (point-max))
6390 (message "Entities are now displayed as plain text"))))
6392 (defvar-local org-custom-properties-overlays nil
6393 "List of overlays used for custom properties.")
6395 (defun org-toggle-custom-properties-visibility ()
6396 "Display or hide properties in `org-custom-properties'."
6397 (interactive)
6398 (if org-custom-properties-overlays
6399 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6400 (setq org-custom-properties-overlays nil))
6401 (when org-custom-properties
6402 (org-with-wide-buffer
6403 (goto-char (point-min))
6404 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6405 (while (re-search-forward regexp nil t)
6406 (let ((end (cdr (save-match-data (org-get-property-block)))))
6407 (when (and end (< (point) end))
6408 ;; Hide first custom property in current drawer.
6409 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6410 (overlay-put o 'invisible t)
6411 (overlay-put o 'org-custom-property t)
6412 (push o org-custom-properties-overlays))
6413 ;; Hide additional custom properties in the same drawer.
6414 (while (re-search-forward regexp end t)
6415 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6416 (overlay-put o 'invisible t)
6417 (overlay-put o 'org-custom-property t)
6418 (push o org-custom-properties-overlays)))))
6419 ;; Each entry is limited to a single property drawer.
6420 (outline-next-heading)))))))
6422 (defun org-fontify-entities (limit)
6423 "Find an entity to fontify."
6424 (let (ee)
6425 (when org-pretty-entities
6426 (catch 'match
6427 ;; "\_ "-family is left out on purpose. Only the first one,
6428 ;; i.e., "\_ ", could be fontified anyway, and it would be
6429 ;; confusing when adding a second white space character.
6430 (while (re-search-forward
6431 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6432 limit t)
6433 (when (and (not (org-at-comment-p))
6434 (setq ee (org-entity-get (match-string 1)))
6435 (= (length (nth 6 ee)) 1))
6436 (let* ((end (if (equal (match-string 2) "{}")
6437 (match-end 2)
6438 (match-end 1))))
6439 (add-text-properties
6440 (match-beginning 0) end
6441 (list 'font-lock-fontified t))
6442 (compose-region (match-beginning 0) end
6443 (nth 6 ee) nil)
6444 (backward-char 1)
6445 (throw 'match t))))
6446 nil))))
6448 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6449 "Fontify string S like in Org-mode."
6450 (with-temp-buffer
6451 (insert s)
6452 (let ((org-odd-levels-only odd-levels))
6453 (org-mode)
6454 (font-lock-ensure)
6455 (buffer-string))))
6457 (defvar org-m nil)
6458 (defvar org-l nil)
6459 (defvar org-f nil)
6460 (defun org-get-level-face (n)
6461 "Get the right face for match N in font-lock matching of headlines."
6462 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6463 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6464 (if org-cycle-level-faces
6465 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6466 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6467 (cond
6468 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6469 ((eq n 2) org-f)
6470 (t (unless org-level-color-stars-only org-f))))
6472 (defun org-face-from-face-or-color (context inherit face-or-color)
6473 "Create a face list that inherits INHERIT, but sets the foreground color.
6474 When FACE-OR-COLOR is not a string, just return it."
6475 (if (stringp face-or-color)
6476 (list :inherit inherit
6477 (cdr (assoc context org-faces-easy-properties))
6478 face-or-color)
6479 face-or-color))
6481 (defun org-get-todo-face (kwd)
6482 "Get the right face for a TODO keyword KWD.
6483 If KWD is a number, get the corresponding match group."
6484 (when (numberp kwd) (setq kwd (match-string kwd)))
6485 (or (org-face-from-face-or-color
6486 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6487 (and (member kwd org-done-keywords) 'org-done)
6488 'org-todo))
6490 (defun org-get-priority-face (priority)
6491 "Get the right face for PRIORITY.
6492 PRIORITY is a character."
6493 (or (org-face-from-face-or-color
6494 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6495 'org-priority))
6497 (defun org-get-tag-face (tag)
6498 "Get the right face for TAG.
6499 If TAG is a number, get the corresponding match group."
6500 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6501 (or (org-face-from-face-or-color
6502 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6503 'org-tag)))
6505 (defun org-font-lock-add-priority-faces (limit)
6506 "Add the special priority faces."
6507 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6508 (add-text-properties
6509 (match-beginning 1) (match-end 1)
6510 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6511 'font-lock-fontified t))))
6513 (defun org-font-lock-add-tag-faces (limit)
6514 "Add the special tag faces."
6515 (when (and org-tag-faces org-tags-special-faces-re)
6516 (while (re-search-forward org-tags-special-faces-re limit t)
6517 (add-text-properties (match-beginning 1) (match-end 1)
6518 (list 'face (org-get-tag-face 1)
6519 'font-lock-fontified t))
6520 (backward-char 1))))
6522 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6523 "Remove fontification and activation overlays from links."
6524 (font-lock-default-unfontify-region beg end)
6525 (let* ((buffer-undo-list t)
6526 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6527 (inhibit-modification-hooks t)
6528 deactivate-mark buffer-file-name buffer-file-truename)
6529 (org-decompose-region beg end)
6530 (remove-text-properties beg end
6531 '(mouse-face t keymap t org-linked-text t
6532 invisible t intangible t
6533 org-emphasis t))
6534 (org-remove-font-lock-display-properties beg end)))
6536 (defconst org-script-display '(((raise -0.3) (height 0.7))
6537 ((raise 0.3) (height 0.7))
6538 ((raise -0.5))
6539 ((raise 0.5)))
6540 "Display properties for showing superscripts and subscripts.")
6542 (defun org-remove-font-lock-display-properties (beg end)
6543 "Remove specific display properties that have been added by font lock.
6544 The will remove the raise properties that are used to show superscripts
6545 and subscripts."
6546 (let (next prop)
6547 (while (< beg end)
6548 (setq next (next-single-property-change beg 'display nil end)
6549 prop (get-text-property beg 'display))
6550 (when (member prop org-script-display)
6551 (put-text-property beg next 'display nil))
6552 (setq beg next))))
6554 (defun org-raise-scripts (limit)
6555 "Add raise properties to sub/superscripts."
6556 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6557 (re-search-forward
6558 (if (eq org-use-sub-superscripts t)
6559 org-match-substring-regexp
6560 org-match-substring-with-braces-regexp)
6561 limit t))
6562 (let* ((pos (point)) table-p comment-p
6563 (mpos (match-beginning 3))
6564 (emph-p (get-text-property mpos 'org-emphasis))
6565 (link-p (get-text-property mpos 'mouse-face))
6566 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6567 (goto-char (point-at-bol))
6568 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6569 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6570 (goto-char pos)
6571 ;; Handle a_b^c
6572 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6573 (unless (or comment-p emph-p link-p keyw-p)
6574 (put-text-property (match-beginning 3) (match-end 0)
6575 'display
6576 (if (equal (char-after (match-beginning 2)) ?^)
6577 (nth (if table-p 3 1) org-script-display)
6578 (nth (if table-p 2 0) org-script-display)))
6579 (add-text-properties (match-beginning 2) (match-end 2)
6580 (list 'invisible t
6581 'org-dwidth t 'org-dwidth-n 1))
6582 (if (and (eq (char-after (match-beginning 3)) ?{)
6583 (eq (char-before (match-end 3)) ?}))
6584 (progn
6585 (add-text-properties
6586 (match-beginning 3) (1+ (match-beginning 3))
6587 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6588 (add-text-properties
6589 (1- (match-end 3)) (match-end 3)
6590 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6591 t)))
6593 ;;;; Visibility cycling, including org-goto and indirect buffer
6595 ;;; Cycling
6597 (defvar-local org-cycle-global-status nil)
6598 (put 'org-cycle-global-status 'org-state t)
6599 (defvar-local org-cycle-subtree-status nil)
6600 (put 'org-cycle-subtree-status 'org-state t)
6602 (defvar org-inlinetask-min-level)
6604 (defun org-unlogged-message (&rest args)
6605 "Display a message, but avoid logging it in the *Messages* buffer."
6606 (let ((message-log-max nil))
6607 (apply 'message args)))
6609 ;;;###autoload
6610 (defun org-cycle (&optional arg)
6611 "TAB-action and visibility cycling for Org-mode.
6613 This is the command invoked in Org-mode by the TAB key. Its main purpose
6614 is outline visibility cycling, but it also invokes other actions
6615 in special contexts.
6617 - When this function is called with a prefix argument, rotate the entire
6618 buffer through 3 states (global cycling)
6619 1. OVERVIEW: Show only top-level headlines.
6620 2. CONTENTS: Show all headlines of all levels, but no body text.
6621 3. SHOW ALL: Show everything.
6622 With a double \\[universal-argument] prefix argument, \
6623 switch to the startup visibility,
6624 determined by the variable `org-startup-folded', and by any VISIBILITY
6625 properties in the buffer.
6626 With a triple \\[universal-argument] prefix argument, \
6627 show the entire buffer, including any drawers.
6629 - When inside a table, re-align the table and move to the next field.
6631 - When point is at the beginning of a headline, rotate the subtree started
6632 by this line through 3 different states (local cycling)
6633 1. FOLDED: Only the main headline is shown.
6634 2. CHILDREN: The main headline and the direct children are shown.
6635 From this state, you can move to one of the children
6636 and zoom in further.
6637 3. SUBTREE: Show the entire subtree, including body text.
6638 If there is no subtree, switch directly from CHILDREN to FOLDED.
6640 - When point is at the beginning of an empty headline and the variable
6641 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6642 of the headline by demoting and promoting it to likely levels. This
6643 speeds up creation document structure by pressing TAB once or several
6644 times right after creating a new headline.
6646 - When there is a numeric prefix, go up to a heading with level ARG, do
6647 a `show-subtree' and return to the previous cursor position. If ARG
6648 is negative, go up that many levels.
6650 - When point is not at the beginning of a headline, execute the global
6651 binding for TAB, which is re-indenting the line. See the option
6652 `org-cycle-emulate-tab' for details.
6654 - Special case: if point is at the beginning of the buffer and there is
6655 no headline in line 1, this function will act as if called with prefix arg
6656 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6657 But only if also the variable `org-cycle-global-at-bob' is t."
6658 (interactive "P")
6659 (org-load-modules-maybe)
6660 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6661 (and org-cycle-level-after-item/entry-creation
6662 (or (org-cycle-level)
6663 (org-cycle-item-indentation))))
6664 (let* ((limit-level
6665 (or org-cycle-max-level
6666 (and (boundp 'org-inlinetask-min-level)
6667 org-inlinetask-min-level
6668 (1- org-inlinetask-min-level))))
6669 (nstars (and limit-level
6670 (if org-odd-levels-only
6671 (and limit-level (1- (* limit-level 2)))
6672 limit-level)))
6673 (org-outline-regexp
6674 (if (not (derived-mode-p 'org-mode))
6675 outline-regexp
6676 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6677 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6678 (not (looking-at org-outline-regexp))))
6679 (org-cycle-hook
6680 (if bob-special
6681 (delq 'org-optimize-window-after-visibility-change
6682 (copy-sequence org-cycle-hook))
6683 org-cycle-hook))
6684 (pos (point)))
6686 (when (or bob-special (equal arg '(4)))
6687 ;; special case: use global cycling
6688 (setq arg t))
6690 (cond
6692 ((equal arg '(16))
6693 (setq last-command 'dummy)
6694 (org-set-startup-visibility)
6695 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6697 ((equal arg '(64))
6698 (outline-show-all)
6699 (org-unlogged-message "Entire buffer visible, including drawers"))
6701 ;; Try cdlatex TAB completion
6702 ((org-try-cdlatex-tab))
6704 ;; Table: enter it or move to the next field.
6705 ((org-at-table-p 'any)
6706 (if (org-at-table.el-p)
6707 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6708 Use \\[org-edit-special] to edit table.el tables"))
6709 (if arg (org-table-edit-field t)
6710 (org-table-justify-field-maybe)
6711 (call-interactively 'org-table-next-field))))
6713 ((run-hook-with-args-until-success
6714 'org-tab-after-check-for-table-hook))
6716 ;; Global cycling: delegate to `org-cycle-internal-global'.
6717 ((eq arg t) (org-cycle-internal-global))
6719 ;; Drawers: delegate to `org-flag-drawer'.
6720 ((save-excursion
6721 (beginning-of-line 1)
6722 (looking-at org-drawer-regexp))
6723 (org-flag-drawer ; toggle block visibility
6724 (not (get-char-property (match-end 0) 'invisible))))
6726 ;; Show-subtree, ARG levels up from here.
6727 ((integerp arg)
6728 (save-excursion
6729 (org-back-to-heading)
6730 (outline-up-heading (if (< arg 0) (- arg)
6731 (- (funcall outline-level) arg)))
6732 (org-show-subtree)))
6734 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6735 ((and (featurep 'org-inlinetask)
6736 (org-inlinetask-at-task-p)
6737 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6738 (org-inlinetask-toggle-visibility))
6740 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6741 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6742 (save-excursion (move-beginning-of-line 1)
6743 (looking-at org-outline-regexp)))
6744 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6745 (org-cycle-internal-local))
6747 ;; From there: TAB emulation and template completion.
6748 (buffer-read-only (org-back-to-heading))
6750 ((run-hook-with-args-until-success
6751 'org-tab-after-check-for-cycling-hook))
6753 ((org-try-structure-completion))
6755 ((run-hook-with-args-until-success
6756 'org-tab-before-tab-emulation-hook))
6758 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6759 (or (not (bolp))
6760 (not (looking-at org-outline-regexp))))
6761 (call-interactively (global-key-binding "\t")))
6763 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6764 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6765 (or (and (eq org-cycle-emulate-tab 'white)
6766 (= (match-end 0) (point-at-eol)))
6767 (and (eq org-cycle-emulate-tab 'whitestart)
6768 (>= (match-end 0) pos))))
6770 (eq org-cycle-emulate-tab t))
6771 (call-interactively (global-key-binding "\t")))
6773 (t (save-excursion
6774 (org-back-to-heading)
6775 (org-cycle)))))))
6777 (defun org-cycle-internal-global ()
6778 "Do the global cycling action."
6779 ;; Hack to avoid display of messages for .org attachments in Gnus
6780 (let ((ga (string-match "\\*fontification" (buffer-name))))
6781 (cond
6782 ((and (eq last-command this-command)
6783 (eq org-cycle-global-status 'overview))
6784 ;; We just created the overview - now do table of contents
6785 ;; This can be slow in very large buffers, so indicate action
6786 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6787 (unless ga (org-unlogged-message "CONTENTS..."))
6788 (org-content)
6789 (unless ga (org-unlogged-message "CONTENTS...done"))
6790 (setq org-cycle-global-status 'contents)
6791 (run-hook-with-args 'org-cycle-hook 'contents))
6793 ((and (eq last-command this-command)
6794 (eq org-cycle-global-status 'contents))
6795 ;; We just showed the table of contents - now show everything
6796 (run-hook-with-args 'org-pre-cycle-hook 'all)
6797 (outline-show-all)
6798 (unless ga (org-unlogged-message "SHOW ALL"))
6799 (setq org-cycle-global-status 'all)
6800 (run-hook-with-args 'org-cycle-hook 'all))
6803 ;; Default action: go to overview
6804 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6805 (org-overview)
6806 (unless ga (org-unlogged-message "OVERVIEW"))
6807 (setq org-cycle-global-status 'overview)
6808 (run-hook-with-args 'org-cycle-hook 'overview)))))
6810 (defvar org-called-with-limited-levels nil
6811 "Non-nil when `org-with-limited-levels' is currently active.")
6813 (defun org-cycle-internal-local ()
6814 "Do the local cycling action."
6815 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6816 ;; First, determine end of headline (EOH), end of subtree or item
6817 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6818 (save-excursion
6819 (if (org-at-item-p)
6820 (progn
6821 (beginning-of-line)
6822 (setq struct (org-list-struct))
6823 (setq eoh (point-at-eol))
6824 (setq eos (org-list-get-item-end-before-blank (point) struct))
6825 (setq has-children (org-list-has-child-p (point) struct)))
6826 (org-back-to-heading)
6827 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6828 (setq eos (save-excursion (org-end-of-subtree t t)
6829 (when (bolp) (backward-char)) (point)))
6830 (setq has-children
6831 (or (save-excursion
6832 (let ((level (funcall outline-level)))
6833 (outline-next-heading)
6834 (and (org-at-heading-p t)
6835 (> (funcall outline-level) level))))
6836 (save-excursion
6837 (org-list-search-forward (org-item-beginning-re) eos t)))))
6838 ;; Determine end invisible part of buffer (EOL)
6839 (beginning-of-line 2)
6840 ;; XEmacs doesn't have `next-single-char-property-change'
6841 (if (featurep 'xemacs)
6842 (while (and (not (eobp)) ;; this is like `next-line'
6843 (get-char-property (1- (point)) 'invisible))
6844 (beginning-of-line 2))
6845 (while (and (not (eobp)) ;; this is like `next-line'
6846 (get-char-property (1- (point)) 'invisible))
6847 (goto-char (next-single-char-property-change (point) 'invisible))
6848 (and (eolp) (beginning-of-line 2))))
6849 (setq eol (point)))
6850 ;; Find out what to do next and set `this-command'
6851 (cond
6852 ((= eos eoh)
6853 ;; Nothing is hidden behind this heading
6854 (unless (org-before-first-heading-p)
6855 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6856 (org-unlogged-message "EMPTY ENTRY")
6857 (setq org-cycle-subtree-status nil)
6858 (save-excursion
6859 (goto-char eos)
6860 (outline-next-heading)
6861 (when (outline-invisible-p) (org-flag-heading nil))))
6862 ((and (or (>= eol eos)
6863 (not (string-match "\\S-" (buffer-substring eol eos))))
6864 (or has-children
6865 (not (setq children-skipped
6866 org-cycle-skip-children-state-if-no-children))))
6867 ;; Entire subtree is hidden in one line: children view
6868 (unless (org-before-first-heading-p)
6869 (run-hook-with-args 'org-pre-cycle-hook 'children))
6870 (if (org-at-item-p)
6871 (org-list-set-item-visibility (point-at-bol) struct 'children)
6872 (org-show-entry)
6873 (org-with-limited-levels (org-show-children))
6874 ;; FIXME: This slows down the func way too much.
6875 ;; How keep drawers hidden in subtree anyway?
6876 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6877 ;; (org-cycle-hide-drawers 'subtree))
6879 ;; Fold every list in subtree to top-level items.
6880 (when (eq org-cycle-include-plain-lists 'integrate)
6881 (save-excursion
6882 (org-back-to-heading)
6883 (while (org-list-search-forward (org-item-beginning-re) eos t)
6884 (beginning-of-line 1)
6885 (let* ((struct (org-list-struct))
6886 (prevs (org-list-prevs-alist struct))
6887 (end (org-list-get-bottom-point struct)))
6888 (dolist (e (org-list-get-all-items (point) struct prevs))
6889 (org-list-set-item-visibility e struct 'folded))
6890 (goto-char (if (< end eos) end eos)))))))
6891 (org-unlogged-message "CHILDREN")
6892 (save-excursion
6893 (goto-char eos)
6894 (outline-next-heading)
6895 (when (outline-invisible-p) (org-flag-heading nil)))
6896 (setq org-cycle-subtree-status 'children)
6897 (unless (org-before-first-heading-p)
6898 (run-hook-with-args 'org-cycle-hook 'children)))
6899 ((or children-skipped
6900 (and (eq last-command this-command)
6901 (eq org-cycle-subtree-status 'children)))
6902 ;; We just showed the children, or no children are there,
6903 ;; now show everything.
6904 (unless (org-before-first-heading-p)
6905 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6906 (outline-flag-region eoh eos nil)
6907 (org-unlogged-message
6908 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6909 (setq org-cycle-subtree-status 'subtree)
6910 (unless (org-before-first-heading-p)
6911 (run-hook-with-args 'org-cycle-hook 'subtree)))
6913 ;; Default action: hide the subtree.
6914 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6915 (outline-flag-region eoh eos t)
6916 (org-unlogged-message "FOLDED")
6917 (setq org-cycle-subtree-status 'folded)
6918 (unless (org-before-first-heading-p)
6919 (run-hook-with-args 'org-cycle-hook 'folded))))))
6921 ;;;###autoload
6922 (defun org-global-cycle (&optional arg)
6923 "Cycle the global visibility. For details see `org-cycle'.
6924 With \\[universal-argument] prefix arg, switch to startup visibility.
6925 With a numeric prefix, show all headlines up to that level."
6926 (interactive "P")
6927 (let ((org-cycle-include-plain-lists
6928 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6929 (cond
6930 ((integerp arg)
6931 (outline-show-all)
6932 (outline-hide-sublevels arg)
6933 (setq org-cycle-global-status 'contents))
6934 ((equal arg '(4))
6935 (org-set-startup-visibility)
6936 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6938 (org-cycle '(4))))))
6940 (defun org-set-startup-visibility ()
6941 "Set the visibility required by startup options and properties."
6942 (cond
6943 ((eq org-startup-folded t)
6944 (org-overview))
6945 ((eq org-startup-folded 'content)
6946 (org-content))
6947 ((or (eq org-startup-folded 'showeverything)
6948 (eq org-startup-folded nil))
6949 (outline-show-all)))
6950 (unless (eq org-startup-folded 'showeverything)
6951 (when org-hide-block-startup (org-hide-block-all))
6952 (org-set-visibility-according-to-property 'no-cleanup)
6953 (org-cycle-hide-archived-subtrees 'all)
6954 (org-cycle-hide-drawers 'all)
6955 (org-cycle-show-empty-lines t)))
6957 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6958 "Switch subtree visibilities according to :VISIBILITY: property."
6959 (interactive)
6960 (org-with-wide-buffer
6961 (goto-char (point-min))
6962 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6963 (if (not (org-at-property-p)) (outline-next-heading)
6964 (let ((state (match-string 3)))
6965 (save-excursion
6966 (org-back-to-heading t)
6967 (outline-hide-subtree)
6968 (org-reveal)
6969 (cond
6970 ((equal state "folded")
6971 (outline-hide-subtree))
6972 ((equal state "children")
6973 (org-show-hidden-entry)
6974 (org-show-children))
6975 ((equal state "content")
6976 (save-excursion
6977 (save-restriction
6978 (org-narrow-to-subtree)
6979 (org-content))))
6980 ((member state '("all" "showall"))
6981 (outline-show-subtree)))))))
6982 (unless no-cleanup
6983 (org-cycle-hide-archived-subtrees 'all)
6984 (org-cycle-hide-drawers 'all)
6985 (org-cycle-show-empty-lines 'all))))
6987 ;; This function uses outline-regexp instead of the more fundamental
6988 ;; org-outline-regexp so that org-cycle-global works outside of Org
6989 ;; buffers, where outline-regexp is needed.
6990 (defun org-overview ()
6991 "Switch to overview mode, showing only top-level headlines.
6992 This shows all headlines with a level equal or greater than the level
6993 of the first headline in the buffer. This is important, because if the
6994 first headline is not level one, then (hide-sublevels 1) gives confusing
6995 results."
6996 (interactive)
6997 (save-excursion
6998 (let ((level
6999 (save-excursion
7000 (goto-char (point-min))
7001 (when (re-search-forward (concat "^" outline-regexp) nil t)
7002 (goto-char (match-beginning 0))
7003 (funcall outline-level)))))
7004 (and level (outline-hide-sublevels level)))))
7006 (defun org-content (&optional arg)
7007 "Show all headlines in the buffer, like a table of contents.
7008 With numerical argument N, show content up to level N."
7009 (interactive "P")
7010 (org-overview)
7011 (save-excursion
7012 ;; Visit all headings and show their offspring
7013 (and (integerp arg) (org-overview))
7014 (goto-char (point-max))
7015 (catch 'exit
7016 (while (and (progn (condition-case nil
7017 (outline-previous-visible-heading 1)
7018 (error (goto-char (point-min))))
7020 (looking-at org-outline-regexp))
7021 (if (integerp arg)
7022 (org-show-children (1- arg))
7023 (outline-show-branches))
7024 (when (bobp) (throw 'exit nil))))))
7026 (defun org-optimize-window-after-visibility-change (state)
7027 "Adjust the window after a change in outline visibility.
7028 This function is the default value of the hook `org-cycle-hook'."
7029 (when (get-buffer-window (current-buffer))
7030 (cond
7031 ((eq state 'content) nil)
7032 ((eq state 'all) nil)
7033 ((eq state 'folded) nil)
7034 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7035 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7037 (defun org-remove-empty-overlays-at (pos)
7038 "Remove outline overlays that do not contain non-white stuff."
7039 (dolist (o (overlays-at pos))
7040 (and (eq 'outline (overlay-get o 'invisible))
7041 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7042 (overlay-end o))))
7043 (delete-overlay o))))
7045 (defun org-clean-visibility-after-subtree-move ()
7046 "Fix visibility issues after moving a subtree."
7047 ;; First, find a reasonable region to look at:
7048 ;; Start two siblings above, end three below
7049 (let* ((beg (save-excursion
7050 (and (org-get-last-sibling)
7051 (org-get-last-sibling))
7052 (point)))
7053 (end (save-excursion
7054 (and (org-get-next-sibling)
7055 (org-get-next-sibling)
7056 (org-get-next-sibling))
7057 (if (org-at-heading-p)
7058 (point-at-eol)
7059 (point))))
7060 (level (looking-at "\\*+"))
7061 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7062 (save-excursion
7063 (save-restriction
7064 (narrow-to-region beg end)
7065 (when re
7066 ;; Properly fold already folded siblings
7067 (goto-char (point-min))
7068 (while (re-search-forward re nil t)
7069 (when (and (not (outline-invisible-p))
7070 (save-excursion
7071 (goto-char (point-at-eol)) (outline-invisible-p)))
7072 (outline-hide-entry))))
7073 (org-cycle-show-empty-lines 'overview)
7074 (org-cycle-hide-drawers 'overview)))))
7076 (defun org-cycle-show-empty-lines (state)
7077 "Show empty lines above all visible headlines.
7078 The region to be covered depends on STATE when called through
7079 `org-cycle-hook'. Lisp program can use t for STATE to get the
7080 entire buffer covered. Note that an empty line is only shown if there
7081 are at least `org-cycle-separator-lines' empty lines before the headline."
7082 (when (/= org-cycle-separator-lines 0)
7083 (save-excursion
7084 (let* ((n (abs org-cycle-separator-lines))
7085 (re (cond
7086 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7087 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7088 (t (let ((ns (number-to-string (- n 2))))
7089 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7090 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7091 beg end)
7092 (cond
7093 ((memq state '(overview contents t))
7094 (setq beg (point-min) end (point-max)))
7095 ((memq state '(children folded))
7096 (setq beg (point)
7097 end (progn (org-end-of-subtree t t)
7098 (line-beginning-position 2)))))
7099 (when beg
7100 (goto-char beg)
7101 (while (re-search-forward re end t)
7102 (unless (get-char-property (match-end 1) 'invisible)
7103 (let ((e (match-end 1))
7104 (b (if (>= org-cycle-separator-lines 0)
7105 (match-beginning 1)
7106 (save-excursion
7107 (goto-char (match-beginning 0))
7108 (skip-chars-backward " \t\n")
7109 (line-end-position)))))
7110 (outline-flag-region b e nil))))))))
7111 ;; Never hide empty lines at the end of the file.
7112 (save-excursion
7113 (goto-char (point-max))
7114 (outline-previous-heading)
7115 (outline-end-of-heading)
7116 (when (and (looking-at "[ \t\n]+")
7117 (= (match-end 0) (point-max)))
7118 (outline-flag-region (point) (match-end 0) nil))))
7120 (defun org-show-empty-lines-in-parent ()
7121 "Move to the parent and re-show empty lines before visible headlines."
7122 (save-excursion
7123 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7124 (org-cycle-show-empty-lines context))))
7126 (defun org-files-list ()
7127 "Return `org-agenda-files' list, plus all open org-mode files.
7128 This is useful for operations that need to scan all of a user's
7129 open and agenda-wise Org files."
7130 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7131 (dolist (buf (buffer-list))
7132 (with-current-buffer buf
7133 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7134 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7135 files))
7137 (defsubst org-entry-beginning-position ()
7138 "Return the beginning position of the current entry."
7139 (save-excursion (outline-back-to-heading t) (point)))
7141 (defsubst org-entry-end-position ()
7142 "Return the end position of the current entry."
7143 (save-excursion (outline-next-heading) (point)))
7145 (defun org-cycle-hide-drawers (state &optional exceptions)
7146 "Re-hide all drawers after a visibility state change.
7147 When non-nil, optional argument EXCEPTIONS is a list of strings
7148 specifying which drawers should not be hidden."
7149 (when (and (derived-mode-p 'org-mode)
7150 (not (memq state '(overview folded contents))))
7151 (save-excursion
7152 (let* ((globalp (memq state '(contents all)))
7153 (beg (if globalp (point-min) (point)))
7154 (end (if globalp (point-max)
7155 (if (eq state 'children)
7156 (save-excursion (outline-next-heading) (point))
7157 (org-end-of-subtree t)))))
7158 (goto-char beg)
7159 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7160 (unless (member-ignore-case (match-string 1) exceptions)
7161 (let ((drawer (org-element-at-point)))
7162 (when (memq (org-element-type drawer) '(drawer property-drawer))
7163 (org-flag-drawer t drawer)
7164 ;; Make sure to skip drawer entirely or we might flag
7165 ;; it another time when matching its ending line with
7166 ;; `org-drawer-regexp'.
7167 (goto-char (org-element-property :end drawer))))))))))
7169 (defun org-flag-drawer (flag &optional element)
7170 "When FLAG is non-nil, hide the drawer we are at.
7171 Otherwise make it visible. When optional argument ELEMENT is
7172 a parsed drawer, as returned by `org-element-at-point', hide or
7173 show that drawer instead."
7174 (when (save-excursion
7175 (beginning-of-line)
7176 (org-looking-at-p org-drawer-regexp))
7177 (let ((drawer (or element (org-element-at-point))))
7178 (when (memq (org-element-type drawer) '(drawer property-drawer))
7179 (let ((post (org-element-property :post-affiliated drawer)))
7180 (save-excursion
7181 (outline-flag-region
7182 (progn (goto-char post) (line-end-position))
7183 (progn (goto-char (org-element-property :end drawer))
7184 (skip-chars-backward " \r\t\n")
7185 (line-end-position))
7186 flag))
7187 ;; When the drawer is hidden away, make sure point lies in
7188 ;; a visible part of the buffer.
7189 (when (and flag (> (line-beginning-position) post))
7190 (goto-char post)))))))
7192 (defun org-subtree-end-visible-p ()
7193 "Is the end of the current subtree visible?"
7194 (pos-visible-in-window-p
7195 (save-excursion (org-end-of-subtree t) (point))))
7197 (defun org-first-headline-recenter ()
7198 "Move cursor to the first headline and recenter the headline."
7199 (goto-char (point-min))
7200 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7201 (set-window-start (selected-window) (point-at-bol))))
7203 ;;; Saving and restoring visibility
7205 (defun org-outline-overlay-data (&optional use-markers)
7206 "Return a list of the locations of all outline overlays.
7207 These are overlays with the `invisible' property value `outline'.
7208 The return value is a list of cons cells, with start and stop
7209 positions for each overlay.
7210 If USE-MARKERS is set, return the positions as markers."
7211 (let (beg end)
7212 (save-excursion
7213 (save-restriction
7214 (widen)
7215 (delq nil
7216 (mapcar (lambda (o)
7217 (when (eq (overlay-get o 'invisible) 'outline)
7218 (setq beg (overlay-start o)
7219 end (overlay-end o))
7220 (and beg end (> end beg)
7221 (if use-markers
7222 (cons (copy-marker beg)
7223 (copy-marker end t))
7224 (cons beg end)))))
7225 (overlays-in (point-min) (point-max))))))))
7227 (defun org-set-outline-overlay-data (data)
7228 "Create visibility overlays for all positions in DATA.
7229 DATA should have been made by `org-outline-overlay-data'."
7230 (org-with-wide-buffer
7231 (outline-show-all)
7232 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7234 ;;; Folding of blocks
7236 (defvar-local org-hide-block-overlays nil
7237 "Overlays hiding blocks.")
7239 (defun org-block-map (function &optional start end)
7240 "Call FUNCTION at the head of all source blocks in the current buffer.
7241 Optional arguments START and END can be used to limit the range."
7242 (let ((start (or start (point-min)))
7243 (end (or end (point-max))))
7244 (save-excursion
7245 (goto-char start)
7246 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7247 (save-excursion
7248 (save-match-data
7249 (goto-char (match-beginning 0))
7250 (funcall function)))))))
7252 (defun org-hide-block-toggle-all ()
7253 "Toggle the visibility of all blocks in the current buffer."
7254 (org-block-map 'org-hide-block-toggle))
7256 (defun org-hide-block-all ()
7257 "Fold all blocks in the current buffer."
7258 (interactive)
7259 (org-show-block-all)
7260 (org-block-map 'org-hide-block-toggle-maybe))
7262 (defun org-show-block-all ()
7263 "Unfold all blocks in the current buffer."
7264 (interactive)
7265 (mapc #'delete-overlay org-hide-block-overlays)
7266 (setq org-hide-block-overlays nil))
7268 (defun org-hide-block-toggle-maybe ()
7269 "Toggle visibility of block at point.
7270 Unlike to `org-hide-block-toggle', this function does not throw
7271 an error. Return a non-nil value when toggling is successful."
7272 (interactive)
7273 (ignore-errors (org-hide-block-toggle)))
7275 (defun org-hide-block-toggle (&optional force)
7276 "Toggle the visibility of the current block.
7277 When optional argument FORCE is `off', make block visible. If it
7278 is non-nil, hide it unconditionally. Throw an error when not at
7279 a block. Return a non-nil value when toggling is successful."
7280 (interactive)
7281 (let ((element (org-element-at-point)))
7282 (unless (memq (org-element-type element)
7283 '(center-block comment-block dynamic-block example-block
7284 export-block quote-block special-block
7285 src-block verse-block))
7286 (user-error "Not at a block"))
7287 (let* ((start (save-excursion
7288 (goto-char (org-element-property :post-affiliated element))
7289 (line-end-position)))
7290 (end (save-excursion
7291 (goto-char (org-element-property :end element))
7292 (skip-chars-backward " \r\t\n")
7293 (line-end-position)))
7294 (overlays (overlays-at start)))
7295 (cond
7296 ;; Do nothing when not before or at the block opening line or
7297 ;; at the block closing line.
7298 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7299 ((and (not (eq force 'off))
7300 (not (memq t (mapcar
7301 (lambda (o)
7302 (eq (overlay-get o 'invisible) 'org-hide-block))
7303 overlays))))
7304 (let ((ov (make-overlay start end)))
7305 (overlay-put ov 'invisible 'org-hide-block)
7306 ;; Make the block accessible to `isearch'.
7307 (overlay-put
7308 ov 'isearch-open-invisible
7309 (lambda (ov)
7310 (when (memq ov org-hide-block-overlays)
7311 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7312 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7313 (delete-overlay ov))))
7314 (push ov org-hide-block-overlays)
7315 ;; When the block is hidden away, make sure point is left in
7316 ;; a visible part of the buffer.
7317 (when (> (line-beginning-position) start)
7318 (goto-char start)
7319 (beginning-of-line))
7320 ;; Signal successful toggling.
7322 ((or (not force) (eq force 'off))
7323 (dolist (ov overlays t)
7324 (when (memq ov org-hide-block-overlays)
7325 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7326 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7327 (delete-overlay ov))))))))
7329 ;; org-tab-after-check-for-cycling-hook
7330 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7331 ;; Remove overlays when changing major mode
7332 (add-hook 'org-mode-hook
7333 (lambda () (org-add-hook 'change-major-mode-hook
7334 'org-show-block-all 'append 'local)))
7336 ;;; Org-goto
7338 (defvar org-goto-window-configuration nil)
7339 (defvar org-goto-marker nil)
7340 (defvar org-goto-map)
7341 (defun org-goto-map ()
7342 "Set the keymap `org-goto'."
7343 (setq org-goto-map
7344 (let ((map (make-sparse-keymap)))
7345 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7346 mouse-drag-region universal-argument org-occur)))
7347 (dolist (cmd cmds)
7348 (substitute-key-definition cmd cmd map global-map)))
7349 (suppress-keymap map)
7350 (org-defkey map "\C-m" 'org-goto-ret)
7351 (org-defkey map [(return)] 'org-goto-ret)
7352 (org-defkey map [(left)] 'org-goto-left)
7353 (org-defkey map [(right)] 'org-goto-right)
7354 (org-defkey map [(control ?g)] 'org-goto-quit)
7355 (org-defkey map "\C-i" 'org-cycle)
7356 (org-defkey map [(tab)] 'org-cycle)
7357 (org-defkey map [(down)] 'outline-next-visible-heading)
7358 (org-defkey map [(up)] 'outline-previous-visible-heading)
7359 (if org-goto-auto-isearch
7360 (if (fboundp 'define-key-after)
7361 (define-key-after map [t] 'org-goto-local-auto-isearch)
7362 nil)
7363 (org-defkey map "q" 'org-goto-quit)
7364 (org-defkey map "n" 'outline-next-visible-heading)
7365 (org-defkey map "p" 'outline-previous-visible-heading)
7366 (org-defkey map "f" 'outline-forward-same-level)
7367 (org-defkey map "b" 'outline-backward-same-level)
7368 (org-defkey map "u" 'outline-up-heading))
7369 (org-defkey map "/" 'org-occur)
7370 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7371 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7372 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7373 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7374 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7375 map)))
7377 (defconst org-goto-help
7378 "Browse buffer copy, to find location or copy text.%s
7379 RET=jump to location C-g=quit and return to previous location
7380 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7382 (defvar org-goto-start-pos) ; dynamically scoped parameter
7384 (defun org-goto (&optional alternative-interface)
7385 "Look up a different location in the current file, keeping current visibility.
7387 When you want look-up or go to a different location in a
7388 document, the fastest way is often to fold the entire buffer and
7389 then dive into the tree. This method has the disadvantage, that
7390 the previous location will be folded, which may not be what you
7391 want.
7393 This command works around this by showing a copy of the current
7394 buffer in an indirect buffer, in overview mode. You can dive
7395 into the tree in that copy, use org-occur and incremental search
7396 to find a location. When pressing RET or `Q', the command
7397 returns to the original buffer in which the visibility is still
7398 unchanged. After RET it will also jump to the location selected
7399 in the indirect buffer and expose the headline hierarchy above.
7401 With a prefix argument, use the alternative interface: e.g., if
7402 `org-goto-interface' is `outline' use `outline-path-completion'."
7403 (interactive "P")
7404 (org-goto-map)
7405 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7406 (org-refile-use-outline-path t)
7407 (org-refile-target-verify-function nil)
7408 (interface
7409 (if (not alternative-interface)
7410 org-goto-interface
7411 (if (eq org-goto-interface 'outline)
7412 'outline-path-completion
7413 'outline)))
7414 (org-goto-start-pos (point))
7415 (selected-point
7416 (if (eq interface 'outline)
7417 (car (org-get-location (current-buffer) org-goto-help))
7418 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7419 (org-refile-check-position pa)
7420 (nth 3 pa)))))
7421 (if selected-point
7422 (progn
7423 (org-mark-ring-push org-goto-start-pos)
7424 (goto-char selected-point)
7425 (when (or (outline-invisible-p) (org-invisible-p2))
7426 (org-show-context 'org-goto)))
7427 (message "Quit"))))
7429 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7430 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7431 (defvar org-goto-local-auto-isearch-map) ; defined below
7433 (defun org-get-location (_buf help)
7434 "Let the user select a location in current buffer.
7435 This function uses a recursive edit. It returns the selected position
7436 or nil."
7437 (org-no-popups
7438 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7439 (isearch-hide-immediately nil)
7440 (isearch-search-fun-function
7441 (lambda () 'org-goto-local-search-headings))
7442 (org-goto-selected-point org-goto-exit-command))
7443 (save-excursion
7444 (save-window-excursion
7445 (delete-other-windows)
7446 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7447 (org-pop-to-buffer-same-window
7448 (condition-case nil
7449 (make-indirect-buffer (current-buffer) "*org-goto*")
7450 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7451 (with-output-to-temp-buffer "*Org Help*"
7452 (princ (format help (if org-goto-auto-isearch
7453 " Just type for auto-isearch."
7454 " n/p/f/b/u to navigate, q to quit."))))
7455 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7456 (setq buffer-read-only nil)
7457 (let ((org-startup-truncated t)
7458 (org-startup-folded nil)
7459 (org-startup-align-all-tables nil))
7460 (org-mode)
7461 (org-overview))
7462 (setq buffer-read-only t)
7463 (if (and (boundp 'org-goto-start-pos)
7464 (integer-or-marker-p org-goto-start-pos))
7465 (progn (goto-char org-goto-start-pos)
7466 (when (outline-invisible-p)
7467 (org-show-set-visibility 'lineage)))
7468 (goto-char (point-min)))
7469 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7470 (message "Select location and press RET")
7471 (use-local-map org-goto-map)
7472 (recursive-edit)))
7473 (kill-buffer "*org-goto*")
7474 (cons org-goto-selected-point org-goto-exit-command))))
7476 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7477 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7478 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7479 (if (fboundp 'isearch-other-control-char)
7480 (progn
7481 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7482 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7483 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7484 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7485 (define-key org-goto-local-auto-isearch-map [return] nil))
7487 (defun org-goto-local-search-headings (string bound noerror)
7488 "Search and make sure that any matches are in headlines."
7489 (catch 'return
7490 (while (if isearch-forward
7491 (search-forward string bound noerror)
7492 (search-backward string bound noerror))
7493 (when (save-match-data
7494 (and (save-excursion
7495 (beginning-of-line)
7496 (looking-at org-complex-heading-regexp))
7497 (or (not (match-beginning 5))
7498 (< (point) (match-beginning 5)))))
7499 (throw 'return (point))))))
7501 (defun org-goto-local-auto-isearch ()
7502 "Start isearch."
7503 (interactive)
7504 (goto-char (point-min))
7505 (let ((keys (this-command-keys)))
7506 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7507 (isearch-mode t)
7508 (isearch-process-search-char (string-to-char keys)))))
7510 (defun org-goto-ret (&optional _arg)
7511 "Finish `org-goto' by going to the new location."
7512 (interactive "P")
7513 (setq org-goto-selected-point (point))
7514 (setq org-goto-exit-command 'return)
7515 (throw 'exit nil))
7517 (defun org-goto-left ()
7518 "Finish `org-goto' by going to the new location."
7519 (interactive)
7520 (if (org-at-heading-p)
7521 (progn
7522 (beginning-of-line 1)
7523 (setq org-goto-selected-point (point)
7524 org-goto-exit-command 'left)
7525 (throw 'exit nil))
7526 (user-error "Not on a heading")))
7528 (defun org-goto-right ()
7529 "Finish `org-goto' by going to the new location."
7530 (interactive)
7531 (if (org-at-heading-p)
7532 (progn
7533 (setq org-goto-selected-point (point)
7534 org-goto-exit-command 'right)
7535 (throw 'exit nil))
7536 (user-error "Not on a heading")))
7538 (defun org-goto-quit ()
7539 "Finish `org-goto' without cursor motion."
7540 (interactive)
7541 (setq org-goto-selected-point nil)
7542 (setq org-goto-exit-command 'quit)
7543 (throw 'exit nil))
7545 ;;; Indirect buffer display of subtrees
7547 (defvar org-indirect-dedicated-frame nil
7548 "This is the frame being used for indirect tree display.")
7549 (defvar org-last-indirect-buffer nil)
7551 (defun org-tree-to-indirect-buffer (&optional arg)
7552 "Create indirect buffer and narrow it to current subtree.
7553 With a numerical prefix ARG, go up to this level and then take that tree.
7554 If ARG is negative, go up that many levels.
7556 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7557 indirect buffer previously made with this command, to avoid proliferation of
7558 indirect buffers. However, when you call the command with a \
7559 \\[universal-argument] prefix, or
7560 when `org-indirect-buffer-display' is `new-frame', the last buffer
7561 is kept so that you can work with several indirect buffers at the same time.
7562 If `org-indirect-buffer-display' is `dedicated-frame', the \
7563 \\[universal-argument] prefix also
7564 requests that a new frame be made for the new buffer, so that the dedicated
7565 frame is not changed."
7566 (interactive "P")
7567 (let ((cbuf (current-buffer))
7568 (cwin (selected-window))
7569 (pos (point))
7570 beg end level heading ibuf)
7571 (save-excursion
7572 (org-back-to-heading t)
7573 (when (numberp arg)
7574 (setq level (org-outline-level))
7575 (when (< arg 0) (setq arg (+ level arg)))
7576 (while (> (setq level (org-outline-level)) arg)
7577 (org-up-heading-safe)))
7578 (setq beg (point)
7579 heading (org-get-heading 'no-tags))
7580 (org-end-of-subtree t t)
7581 (when (org-at-heading-p) (backward-char 1))
7582 (setq end (point)))
7583 (when (and (buffer-live-p org-last-indirect-buffer)
7584 (not (eq org-indirect-buffer-display 'new-frame))
7585 (not arg))
7586 (kill-buffer org-last-indirect-buffer))
7587 (setq ibuf (org-get-indirect-buffer cbuf heading)
7588 org-last-indirect-buffer ibuf)
7589 (cond
7590 ((or (eq org-indirect-buffer-display 'new-frame)
7591 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7592 (select-frame (make-frame))
7593 (delete-other-windows)
7594 (org-pop-to-buffer-same-window ibuf)
7595 (org-set-frame-title heading))
7596 ((eq org-indirect-buffer-display 'dedicated-frame)
7597 (raise-frame
7598 (select-frame (or (and org-indirect-dedicated-frame
7599 (frame-live-p org-indirect-dedicated-frame)
7600 org-indirect-dedicated-frame)
7601 (setq org-indirect-dedicated-frame (make-frame)))))
7602 (delete-other-windows)
7603 (org-pop-to-buffer-same-window ibuf)
7604 (org-set-frame-title (concat "Indirect: " heading)))
7605 ((eq org-indirect-buffer-display 'current-window)
7606 (org-pop-to-buffer-same-window ibuf))
7607 ((eq org-indirect-buffer-display 'other-window)
7608 (pop-to-buffer ibuf))
7609 (t (error "Invalid value")))
7610 (when (featurep 'xemacs)
7611 (save-excursion (org-mode) (turn-on-font-lock)))
7612 (narrow-to-region beg end)
7613 (outline-show-all)
7614 (goto-char pos)
7615 (run-hook-with-args 'org-cycle-hook 'all)
7616 (and (window-live-p cwin) (select-window cwin))))
7618 (defun org-get-indirect-buffer (&optional buffer heading)
7619 (setq buffer (or buffer (current-buffer)))
7620 (let ((n 1) (base (buffer-name buffer)) bname)
7621 (while (buffer-live-p
7622 (get-buffer
7623 (setq bname
7624 (concat base "-"
7625 (if heading (concat heading "-" (number-to-string n))
7626 (number-to-string n))))))
7627 (setq n (1+ n)))
7628 (condition-case nil
7629 (make-indirect-buffer buffer bname 'clone)
7630 (error (make-indirect-buffer buffer bname)))))
7632 (defun org-set-frame-title (title)
7633 "Set the title of the current frame to the string TITLE."
7634 ;; FIXME: how to name a single frame in XEmacs???
7635 (unless (featurep 'xemacs)
7636 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7638 ;;;; Structure editing
7640 ;;; Inserting headlines
7642 (defun org--line-empty-p (n)
7643 "Is the Nth next line empty?
7645 Counts the current line as N = 1 and the previous line as N = 0;
7646 see `beginning-of-line'."
7647 (save-excursion
7648 (and (not (bobp))
7649 (or (beginning-of-line n) t)
7650 (save-match-data
7651 (looking-at "[ \t]*$")))))
7653 (defun org-previous-line-empty-p ()
7654 "Is the previous line a blank line?
7655 When NEXT is non-nil, check the next line instead."
7656 (org--line-empty-p 0))
7658 (defun org-next-line-empty-p ()
7659 "Is the previous line a blank line?
7660 When NEXT is non-nil, check the next line instead."
7661 (org--line-empty-p 2))
7663 (defun org-insert-heading (&optional arg invisible-ok top)
7664 "Insert a new heading or an item with the same depth at point.
7666 If point is at the beginning of a heading or a list item, insert
7667 a new heading or a new item above the current one. If point is
7668 at the beginning of a normal line, turn the line into a heading.
7670 If point is in the middle of a headline or a list item, split the
7671 headline or the item and create a new headline/item with the text
7672 in the current line after point \(see `org-M-RET-may-split-line'
7673 on how to modify this behavior).
7675 With one universal prefix argument, set the user option
7676 `org-insert-heading-respect-content' to t for the duration of
7677 the command. This modifies the behavior described above in this
7678 ways: on list items and at the beginning of normal lines, force
7679 the insertion of a heading after the current subtree.
7681 With two universal prefix arguments, insert the heading at the
7682 end of the grandparent subtree. For example, if point is within
7683 a 2nd-level heading, then it will insert a 2nd-level heading at
7684 the end of the 1st-level parent heading.
7686 If point is at the beginning of a headline, insert a sibling
7687 before the current headline. If point is not at the beginning,
7688 split the line and create a new headline with the text in the
7689 current line after point \(see `org-M-RET-may-split-line' on how
7690 to modify this behavior).
7692 If point is at the beginning of a normal line, turn this line
7693 into a heading.
7695 When INVISIBLE-OK is set, stop at invisible headlines when going
7696 back. This is important for non-interactive uses of the
7697 command.
7699 When optional argument TOP is non-nil, insert a level 1 heading,
7700 unconditionally."
7701 (interactive "P")
7702 (when (org-called-interactively-p 'any) (org-reveal))
7703 (let ((itemp (and (not top) (org-in-item-p)))
7704 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7705 (respect-content (or org-insert-heading-respect-content
7706 (equal arg '(4))))
7707 (initial-content ""))
7709 (cond
7711 ((or (= (buffer-size) 0)
7712 (and (not (save-excursion
7713 (and (ignore-errors (org-back-to-heading invisible-ok))
7714 (org-at-heading-p))))
7715 (or arg (not itemp))))
7716 ;; At beginning of buffer or so high up that only a heading
7717 ;; makes sense.
7718 (cond ((and (bolp) (not respect-content)) (insert "* "))
7719 ((not respect-content)
7720 (unless may-split (end-of-line))
7721 (insert "\n* "))
7722 ((re-search-forward org-outline-regexp-bol nil t)
7723 (beginning-of-line)
7724 (insert "* \n")
7725 (backward-char))
7726 (t (goto-char (point-max))
7727 (insert "\n* ")))
7728 (run-hooks 'org-insert-heading-hook))
7730 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7733 ;; Maybe move at the end of the subtree
7734 (when (equal arg '(16))
7735 (org-up-heading-safe)
7736 (org-end-of-subtree t))
7737 ;; Insert a heading
7738 (save-restriction
7739 (widen)
7740 (let* ((level nil)
7741 (on-heading (org-at-heading-p))
7742 (empty-line-p (if on-heading
7743 (org-previous-line-empty-p)
7744 ;; We will decide later
7745 nil))
7746 ;; Get a level string to fall back on.
7747 (fix-level
7748 (if (org-before-first-heading-p) "*"
7749 (save-excursion
7750 (org-back-to-heading t)
7751 (when (org-previous-line-empty-p) (setq empty-line-p t))
7752 (looking-at org-outline-regexp)
7753 (make-string (1- (length (match-string 0))) ?*))))
7754 (stars
7755 (save-excursion
7756 (condition-case nil
7757 (if top "* "
7758 (org-back-to-heading invisible-ok)
7759 (when (and (not on-heading)
7760 (featurep 'org-inlinetask)
7761 (integerp org-inlinetask-min-level)
7762 (>= (length (match-string 0))
7763 org-inlinetask-min-level))
7764 ;; Find a heading level before the inline
7765 ;; task.
7766 (while (and (setq level (org-up-heading-safe))
7767 (>= level org-inlinetask-min-level)))
7768 (if (org-at-heading-p)
7769 (org-back-to-heading invisible-ok)
7770 (error "This should not happen")))
7771 (unless (and (save-excursion
7772 (save-match-data
7773 (org-backward-heading-same-level
7774 1 invisible-ok))
7775 (= (point) (match-beginning 0)))
7776 (not (org-next-line-empty-p)))
7777 (setq empty-line-p (or empty-line-p
7778 (org-previous-line-empty-p))))
7779 (match-string 0))
7780 (error (or fix-level "* ")))))
7781 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7782 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7784 ;; If we insert after content, move there and clean up
7785 ;; whitespace.
7786 (when (and respect-content
7787 (not (org-looking-at-p org-outline-regexp-bol)))
7788 (if (not (org-before-first-heading-p))
7789 (org-end-of-subtree nil t)
7790 (re-search-forward org-outline-regexp-bol)
7791 (beginning-of-line 0))
7792 (skip-chars-backward " \r\t\n")
7793 (and (not (org-looking-back "^\\*+" (line-beginning-position)))
7794 (looking-at "[ \t]+") (replace-match ""))
7795 (unless (eobp) (forward-char 1))
7796 (when (looking-at "^\\*")
7797 (unless (bobp) (backward-char 1))
7798 (insert "\n")))
7800 ;; If we are splitting, grab the text that should be moved
7801 ;; to the new headline.
7802 (when may-split
7803 (if (org-at-heading-p)
7804 ;; This is a heading: split intelligently (keeping
7805 ;; tags).
7806 (let ((pos (point)))
7807 (beginning-of-line)
7808 (unless (looking-at org-complex-heading-regexp)
7809 (error "This should not happen"))
7810 (when (and (match-beginning 4)
7811 (> pos (match-beginning 4))
7812 (< pos (match-end 4)))
7813 (setq initial-content (buffer-substring pos (match-end 4)))
7814 (goto-char pos)
7815 (delete-region (point) (match-end 4))
7816 (if (looking-at "[ \t]*$")
7817 (replace-match "")
7818 (insert (make-string (length initial-content) ?\s)))
7819 (setq initial-content (org-trim initial-content)))
7820 (goto-char pos))
7821 ;; A normal line.
7822 (setq initial-content
7823 (org-trim
7824 (delete-and-extract-region (point) (line-end-position))))))
7826 ;; If we are at the beginning of the line, insert before it.
7827 ;; Otherwise, after it.
7828 (cond
7829 ((and (bolp) (looking-at "[ \t]*$")))
7830 ((bolp) (save-excursion (insert "\n")))
7831 (t (end-of-line)
7832 (insert "\n")))
7834 ;; Insert the new heading
7835 (insert stars)
7836 (just-one-space)
7837 (insert initial-content)
7838 (unless (and blank (org-previous-line-empty-p))
7839 (org-N-empty-lines-before-current (if blank 1 0)))
7840 ;; Adjust visibility, which may be messed up if we removed
7841 ;; blank lines while previous entry was hidden.
7842 (let ((bol (line-beginning-position)))
7843 (dolist (o (overlays-at (1- bol)))
7844 (when (and (eq (overlay-get o 'invisible) 'outline)
7845 (eq (overlay-end o) bol))
7846 (move-overlay o (overlay-start o) (1- bol)))))
7847 (run-hooks 'org-insert-heading-hook)))))))
7849 (defun org-N-empty-lines-before-current (N)
7850 "Make the number of empty lines before current exactly N.
7851 So this will delete or add empty lines."
7852 (save-excursion
7853 (beginning-of-line)
7854 (let ((p (point)))
7855 (skip-chars-backward " \r\t\n")
7856 (unless (bolp) (forward-line))
7857 (delete-region (point) p))
7858 (when (> N 0) (insert (make-string N ?\n)))))
7860 (defun org-get-heading (&optional no-tags no-todo)
7861 "Return the heading of the current entry, without the stars.
7862 When NO-TAGS is non-nil, don't include tags.
7863 When NO-TODO is non-nil, don't include TODO keywords."
7864 (save-excursion
7865 (org-back-to-heading t)
7866 (cond
7867 ((and no-tags no-todo)
7868 (looking-at org-complex-heading-regexp)
7869 (match-string 4))
7870 (no-tags
7871 (looking-at (concat org-outline-regexp
7872 "\\(.*?\\)"
7873 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7874 (match-string 1))
7875 (no-todo
7876 (looking-at org-todo-line-regexp)
7877 (match-string 3))
7878 (t (looking-at org-heading-regexp)
7879 (match-string 2)))))
7881 (defvar orgstruct-mode) ; defined below
7883 (defun org-heading-components ()
7884 "Return the components of the current heading.
7885 This is a list with the following elements:
7886 - the level as an integer
7887 - the reduced level, different if `org-odd-levels-only' is set.
7888 - the TODO keyword, or nil
7889 - the priority character, like ?A, or nil if no priority is given
7890 - the headline text itself, or the tags string if no headline text
7891 - the tags string, or nil."
7892 (save-excursion
7893 (org-back-to-heading t)
7894 (when (let (case-fold-search)
7895 (looking-at
7896 (if orgstruct-mode
7897 org-heading-regexp
7898 org-complex-heading-regexp)))
7899 (if orgstruct-mode
7900 (list (length (match-string 1))
7901 (org-reduced-level (length (match-string 1)))
7904 (match-string 2)
7905 nil)
7906 (list (length (match-string 1))
7907 (org-reduced-level (length (match-string 1)))
7908 (org-match-string-no-properties 2)
7909 (and (match-end 3) (aref (match-string 3) 2))
7910 (org-match-string-no-properties 4)
7911 (org-match-string-no-properties 5))))))
7913 (defun org-get-entry ()
7914 "Get the entry text, after heading, entire subtree."
7915 (save-excursion
7916 (org-back-to-heading t)
7917 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7919 (defun org-insert-heading-after-current ()
7920 "Insert a new heading with same level as current, after current subtree."
7921 (interactive)
7922 (org-back-to-heading)
7923 (org-insert-heading)
7924 (org-move-subtree-down)
7925 (end-of-line 1))
7927 (defun org-insert-heading-respect-content (&optional invisible-ok)
7928 "Insert heading with `org-insert-heading-respect-content' set to t."
7929 (interactive)
7930 (org-insert-heading '(4) invisible-ok))
7932 (defun org-insert-todo-heading-respect-content (&optional force-state)
7933 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7934 (interactive)
7935 (org-insert-todo-heading force-state '(4)))
7937 (defun org-insert-todo-heading (arg &optional force-heading)
7938 "Insert a new heading with the same level and TODO state as current heading.
7939 If the heading has no TODO state, or if the state is DONE, use the first
7940 state (TODO by default). Also with one prefix arg, force first state. With
7941 two prefix args, force inserting at the end of the parent subtree."
7942 (interactive "P")
7943 (when (or force-heading (not (org-insert-item 'checkbox)))
7944 (org-insert-heading (or (and (equal arg '(16)) '(16))
7945 force-heading))
7946 (save-excursion
7947 (org-back-to-heading)
7948 (outline-previous-heading)
7949 (looking-at org-todo-line-regexp))
7950 (let*
7951 ((new-mark-x
7952 (if (or (equal arg '(4))
7953 (not (match-beginning 2))
7954 (member (match-string 2) org-done-keywords))
7955 (car org-todo-keywords-1)
7956 (match-string 2)))
7957 (new-mark
7959 (run-hook-with-args-until-success
7960 'org-todo-get-default-hook new-mark-x nil)
7961 new-mark-x)))
7962 (beginning-of-line 1)
7963 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7964 (if org-treat-insert-todo-heading-as-state-change
7965 (org-todo new-mark)
7966 (insert new-mark " "))))
7967 (when org-provide-todo-statistics
7968 (org-update-parent-todo-statistics))))
7970 (defun org-insert-subheading (arg)
7971 "Insert a new subheading and demote it.
7972 Works for outline headings and for plain lists alike."
7973 (interactive "P")
7974 (org-insert-heading arg)
7975 (cond
7976 ((org-at-heading-p) (org-do-demote))
7977 ((org-at-item-p) (org-indent-item))))
7979 (defun org-insert-todo-subheading (arg)
7980 "Insert a new subheading with TODO keyword or checkbox and demote it.
7981 Works for outline headings and for plain lists alike."
7982 (interactive "P")
7983 (org-insert-todo-heading arg)
7984 (cond
7985 ((org-at-heading-p) (org-do-demote))
7986 ((org-at-item-p) (org-indent-item))))
7988 ;;; Promotion and Demotion
7990 (defvar org-after-demote-entry-hook nil
7991 "Hook run after an entry has been demoted.
7992 The cursor will be at the beginning of the entry.
7993 When a subtree is being demoted, the hook will be called for each node.")
7995 (defvar org-after-promote-entry-hook nil
7996 "Hook run after an entry has been promoted.
7997 The cursor will be at the beginning of the entry.
7998 When a subtree is being promoted, the hook will be called for each node.")
8000 (defun org-promote-subtree ()
8001 "Promote the entire subtree.
8002 See also `org-promote'."
8003 (interactive)
8004 (save-excursion
8005 (org-with-limited-levels (org-map-tree 'org-promote)))
8006 (org-fix-position-after-promote))
8008 (defun org-demote-subtree ()
8009 "Demote the entire subtree.
8010 See `org-demote' and `org-promote'."
8011 (interactive)
8012 (save-excursion
8013 (org-with-limited-levels (org-map-tree 'org-demote)))
8014 (org-fix-position-after-promote))
8016 (defun org-do-promote ()
8017 "Promote the current heading higher up the tree.
8018 If the region is active in `transient-mark-mode', promote all
8019 headings in the region."
8020 (interactive)
8021 (save-excursion
8022 (if (org-region-active-p)
8023 (org-map-region 'org-promote (region-beginning) (region-end))
8024 (org-promote)))
8025 (org-fix-position-after-promote))
8027 (defun org-do-demote ()
8028 "Demote the current heading lower down the tree.
8029 If the region is active in `transient-mark-mode', demote all
8030 headings in the region."
8031 (interactive)
8032 (save-excursion
8033 (if (org-region-active-p)
8034 (org-map-region 'org-demote (region-beginning) (region-end))
8035 (org-demote)))
8036 (org-fix-position-after-promote))
8038 (defun org-fix-position-after-promote ()
8039 "Fix cursor position and indentation after demoting/promoting."
8040 (let ((pos (point)))
8041 (when (save-excursion
8042 (beginning-of-line 1)
8043 (looking-at org-todo-line-regexp)
8044 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8045 (cond ((eobp) (insert " "))
8046 ((eolp) (insert " "))
8047 ((equal (char-after) ?\ ) (forward-char 1))))))
8049 (defun org-current-level ()
8050 "Return the level of the current entry, or nil if before the first headline.
8051 The level is the number of stars at the beginning of the
8052 headline. Use `org-reduced-level' to remove the effect of
8053 `org-odd-levels'. Unlike to `org-outline-level', this function
8054 ignores inlinetasks."
8055 (let ((level (org-with-limited-levels (org-outline-level))))
8056 (and (> level 0) level)))
8058 (defun org-get-previous-line-level ()
8059 "Return the outline depth of the last headline before the current line.
8060 Returns 0 for the first headline in the buffer, and nil if before the
8061 first headline."
8062 (and (org-current-level)
8063 (or (and (/= (line-beginning-position) (point-min))
8064 (save-excursion (beginning-of-line 0) (org-current-level)))
8065 0)))
8067 (defun org-reduced-level (l)
8068 "Compute the effective level of a heading.
8069 This takes into account the setting of `org-odd-levels-only'."
8070 (cond
8071 ((zerop l) 0)
8072 (org-odd-levels-only (1+ (floor (/ l 2))))
8073 (t l)))
8075 (defun org-level-increment ()
8076 "Return the number of stars that will be added or removed at a
8077 time to headlines when structure editing, based on the value of
8078 `org-odd-levels-only'."
8079 (if org-odd-levels-only 2 1))
8081 (defun org-get-valid-level (level &optional change)
8082 "Rectify a level change under the influence of `org-odd-levels-only'
8083 LEVEL is a current level, CHANGE is by how much the level should be
8084 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8085 even level numbers will become the next higher odd number."
8086 (if org-odd-levels-only
8087 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8088 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8089 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8090 (max 1 (+ level (or change 0)))))
8091 (define-obsolete-function-alias 'org-get-legal-level 'org-get-valid-level "23.1")
8093 (defun org-promote ()
8094 "Promote the current heading higher up the tree."
8095 (org-with-wide-buffer
8096 (org-back-to-heading t)
8097 (let* ((after-change-functions (remq 'flyspell-after-change-function
8098 after-change-functions))
8099 (level (save-match-data (funcall outline-level)))
8100 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8101 (diff (abs (- level (length up-head) -1))))
8102 (cond
8103 ((and (= level 1) org-allow-promoting-top-level-subtree)
8104 (replace-match "# " nil t))
8105 ((= level 1)
8106 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8107 (t (replace-match up-head nil t)))
8108 (unless (= level 1)
8109 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8110 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8111 (run-hooks 'org-after-promote-entry-hook))))
8113 (defun org-demote ()
8114 "Demote the current heading lower down the tree."
8115 (org-with-wide-buffer
8116 (org-back-to-heading t)
8117 (let* ((after-change-functions (remq 'flyspell-after-change-function
8118 after-change-functions))
8119 (level (save-match-data (funcall outline-level)))
8120 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8121 (diff (abs (- level (length down-head) -1))))
8122 (replace-match down-head nil t)
8123 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8124 (when org-adapt-indentation (org-fixup-indentation diff))
8125 (run-hooks 'org-after-demote-entry-hook))))
8127 (defun org-cycle-level ()
8128 "Cycle the level of an empty headline through possible states.
8129 This goes first to child, then to parent, level, then up the hierarchy.
8130 After top level, it switches back to sibling level."
8131 (interactive)
8132 (let ((org-adapt-indentation nil))
8133 (when (org-point-at-end-of-empty-headline)
8134 (setq this-command 'org-cycle-level) ; Only needed for caching
8135 (let ((cur-level (org-current-level))
8136 (prev-level (org-get-previous-line-level)))
8137 (cond
8138 ;; If first headline in file, promote to top-level.
8139 ((= prev-level 0)
8140 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8141 do (org-do-promote)))
8142 ;; If same level as prev, demote one.
8143 ((= prev-level cur-level)
8144 (org-do-demote))
8145 ;; If parent is top-level, promote to top level if not already.
8146 ((= prev-level 1)
8147 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8148 do (org-do-promote)))
8149 ;; If top-level, return to prev-level.
8150 ((= cur-level 1)
8151 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8152 do (org-do-demote)))
8153 ;; If less than prev-level, promote one.
8154 ((< cur-level prev-level)
8155 (org-do-promote))
8156 ;; If deeper than prev-level, promote until higher than
8157 ;; prev-level.
8158 ((> cur-level prev-level)
8159 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8160 do (org-do-promote))))
8161 t))))
8163 (defun org-map-tree (fun)
8164 "Call FUN for every heading underneath the current one."
8165 (org-back-to-heading)
8166 (let ((level (funcall outline-level)))
8167 (save-excursion
8168 (funcall fun)
8169 (while (and (progn
8170 (outline-next-heading)
8171 (> (funcall outline-level) level))
8172 (not (eobp)))
8173 (funcall fun)))))
8175 (defun org-map-region (fun beg end)
8176 "Call FUN for every heading between BEG and END."
8177 (let ((org-ignore-region t))
8178 (save-excursion
8179 (setq end (copy-marker end))
8180 (goto-char beg)
8181 (when (and (re-search-forward org-outline-regexp-bol nil t)
8182 (< (point) end))
8183 (funcall fun))
8184 (while (and (progn
8185 (outline-next-heading)
8186 (< (point) end))
8187 (not (eobp)))
8188 (funcall fun)))))
8190 (defun org-fixup-indentation (diff)
8191 "Change the indentation in the current entry by DIFF.
8193 DIFF is an integer. Indentation is done according to the
8194 following rules:
8196 - Planning information and property drawers are always indented
8197 according to the new level of the headline;
8199 - Footnote definitions and their contents are ignored;
8201 - Inlinetasks' boundaries are not shifted;
8203 - Empty lines are ignored;
8205 - Other lines' indentation are shifted by DIFF columns, unless
8206 it would introduce a structural change in the document, in
8207 which case no shifting is done at all.
8209 Assume point is at a heading or an inlinetask beginning."
8210 (org-with-wide-buffer
8211 (narrow-to-region (line-beginning-position)
8212 (save-excursion
8213 (if (org-with-limited-levels (org-at-heading-p))
8214 (org-with-limited-levels (outline-next-heading))
8215 (org-inlinetask-goto-end))
8216 (point)))
8217 (forward-line)
8218 ;; Indent properly planning info and property drawer.
8219 (when (org-looking-at-p org-planning-line-re)
8220 (org-indent-line)
8221 (forward-line))
8222 (when (looking-at org-property-drawer-re)
8223 (goto-char (match-end 0))
8224 (forward-line)
8225 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8226 (catch 'no-shift
8227 (when (zerop diff) (throw 'no-shift nil))
8228 ;; If DIFF is negative, first check if a shift is possible at all
8229 ;; (e.g., it doesn't break structure). This can only happen if
8230 ;; some contents are not properly indented.
8231 (let ((case-fold-search t))
8232 (when (< diff 0)
8233 (let ((diff (- diff))
8234 (forbidden-re (concat org-outline-regexp
8235 "\\|"
8236 (substring org-footnote-definition-re 1))))
8237 (save-excursion
8238 (while (not (eobp))
8239 (cond
8240 ((org-looking-at-p "[ \t]*$") (forward-line))
8241 ((and (org-looking-at-p org-footnote-definition-re)
8242 (let ((e (org-element-at-point)))
8243 (and (eq (org-element-type e) 'footnote-definition)
8244 (goto-char (org-element-property :end e))))))
8245 ((org-looking-at-p org-outline-regexp) (forward-line))
8246 ;; Give up if shifting would move before column 0 or
8247 ;; if it would introduce a headline or a footnote
8248 ;; definition.
8250 (skip-chars-forward " \t")
8251 (let ((ind (current-column)))
8252 (when (or (< ind diff)
8253 (and (= ind diff) (org-looking-at-p forbidden-re)))
8254 (throw 'no-shift nil)))
8255 ;; Ignore contents of example blocks and source
8256 ;; blocks if their indentation is meant to be
8257 ;; preserved. Jump to block's closing line.
8258 (beginning-of-line)
8259 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8260 (let ((e (org-element-at-point)))
8261 (and (memq (org-element-type e)
8262 '(example-block src-block))
8263 (or org-src-preserve-indentation
8264 (org-element-property :preserve-indent e))
8265 (goto-char (org-element-property :end e))
8266 (progn (skip-chars-backward " \r\t\n")
8267 (beginning-of-line)
8268 t))))
8269 (forward-line))))))))
8270 ;; Shift lines but footnote definitions, inlinetasks boundaries
8271 ;; by DIFF. Also skip contents of source or example blocks
8272 ;; when indentation is meant to be preserved.
8273 (while (not (eobp))
8274 (cond
8275 ((and (org-looking-at-p org-footnote-definition-re)
8276 (let ((e (org-element-at-point)))
8277 (and (eq (org-element-type e) 'footnote-definition)
8278 (goto-char (org-element-property :end e))))))
8279 ((org-looking-at-p org-outline-regexp) (forward-line))
8280 ((org-looking-at-p "[ \t]*$") (forward-line))
8282 (org-indent-line-to (+ (org-get-indentation) diff))
8283 (beginning-of-line)
8284 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8285 (let ((e (org-element-at-point)))
8286 (and (memq (org-element-type e)
8287 '(example-block src-block))
8288 (or org-src-preserve-indentation
8289 (org-element-property :preserve-indent e))
8290 (goto-char (org-element-property :end e))
8291 (progn (skip-chars-backward " \r\t\n")
8292 (beginning-of-line)
8293 t))))
8294 (forward-line)))))))))
8296 (defun org-convert-to-odd-levels ()
8297 "Convert an org-mode file with all levels allowed to one with odd levels.
8298 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8299 level 5 etc."
8300 (interactive)
8301 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8302 (let ((outline-level 'org-outline-level)
8303 (org-odd-levels-only nil) n)
8304 (save-excursion
8305 (goto-char (point-min))
8306 (while (re-search-forward "^\\*\\*+ " nil t)
8307 (setq n (- (length (match-string 0)) 2))
8308 (while (>= (setq n (1- n)) 0)
8309 (org-demote))
8310 (end-of-line 1))))))
8312 (defun org-convert-to-oddeven-levels ()
8313 "Convert an org-mode file with only odd levels to one with odd/even levels.
8314 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8315 file contains a section with an even level, conversion would
8316 destroy the structure of the file. An error is signaled in this
8317 case."
8318 (interactive)
8319 (goto-char (point-min))
8320 ;; First check if there are no even levels
8321 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8322 (org-show-set-visibility 'canonical)
8323 (error "Not all levels are odd in this file. Conversion not possible"))
8324 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8325 (let ((outline-regexp org-outline-regexp)
8326 (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 (/ (1- (length (match-string 0))) 2))
8332 (while (>= (setq n (1- n)) 0)
8333 (org-promote))
8334 (end-of-line 1))))))
8336 (defun org-tr-level (n)
8337 "Make N odd if required."
8338 (if org-odd-levels-only (1+ (/ n 2)) n))
8340 ;;; Vertical tree motion, cutting and pasting of subtrees
8342 (defun org-move-subtree-up (&optional arg)
8343 "Move the current subtree up past ARG headlines of the same level."
8344 (interactive "p")
8345 (org-move-subtree-down (- (prefix-numeric-value arg))))
8347 (defun org-move-subtree-down (&optional arg)
8348 "Move the current subtree down past ARG headlines of the same level."
8349 (interactive "p")
8350 (setq arg (prefix-numeric-value arg))
8351 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8352 'org-get-last-sibling))
8353 (ins-point (make-marker))
8354 (cnt (abs arg))
8355 (col (current-column))
8356 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8357 ;; Select the tree
8358 (org-back-to-heading)
8359 (setq beg0 (point))
8360 (save-excursion
8361 (setq ne-beg (org-back-over-empty-lines))
8362 (setq beg (point)))
8363 (save-match-data
8364 (save-excursion (outline-end-of-heading)
8365 (setq folded (outline-invisible-p)))
8366 (progn (org-end-of-subtree nil t)
8367 (unless (eobp) (backward-char))))
8368 (outline-next-heading)
8369 (setq ne-end (org-back-over-empty-lines))
8370 (setq end (point))
8371 (goto-char beg0)
8372 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8373 ;; include less whitespace
8374 (save-excursion
8375 (goto-char beg)
8376 (forward-line (- ne-beg ne-end))
8377 (setq beg (point))))
8378 ;; Find insertion point, with error handling
8379 (while (> cnt 0)
8380 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8381 (progn (goto-char beg0)
8382 (user-error "Cannot move past superior level or buffer limit")))
8383 (setq cnt (1- cnt)))
8384 (when (> arg 0)
8385 ;; Moving forward - still need to move over subtree
8386 (org-end-of-subtree t t)
8387 (save-excursion
8388 (org-back-over-empty-lines)
8389 (or (bolp) (newline))))
8390 (setq ne-ins (org-back-over-empty-lines))
8391 (move-marker ins-point (point))
8392 (setq txt (buffer-substring beg end))
8393 (org-save-markers-in-region beg end)
8394 (delete-region beg end)
8395 (org-remove-empty-overlays-at beg)
8396 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8397 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8398 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8399 (let ((bbb (point)))
8400 (insert-before-markers txt)
8401 (org-reinstall-markers-in-region bbb)
8402 (move-marker ins-point bbb))
8403 (or (bolp) (insert "\n"))
8404 (setq ins-end (point))
8405 (goto-char ins-point)
8406 (org-skip-whitespace)
8407 (when (and (< arg 0)
8408 (org-first-sibling-p)
8409 (> ne-ins ne-beg))
8410 ;; Move whitespace back to beginning
8411 (save-excursion
8412 (goto-char ins-end)
8413 (let ((kill-whole-line t))
8414 (kill-line (- ne-ins ne-beg)) (point)))
8415 (insert (make-string (- ne-ins ne-beg) ?\n)))
8416 (move-marker ins-point nil)
8417 (if folded
8418 (outline-hide-subtree)
8419 (org-show-entry)
8420 (org-show-children)
8421 (org-cycle-hide-drawers 'children))
8422 (org-clean-visibility-after-subtree-move)
8423 ;; move back to the initial column we were at
8424 (move-to-column col)))
8426 (defvar org-subtree-clip ""
8427 "Clipboard for cut and paste of subtrees.
8428 This is actually only a copy of the kill, because we use the normal kill
8429 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8431 (defvar org-subtree-clip-folded nil
8432 "Was the last copied subtree folded?
8433 This is used to fold the tree back after pasting.")
8435 (defun org-cut-subtree (&optional n)
8436 "Cut the current subtree into the clipboard.
8437 With prefix arg N, cut this many sequential subtrees.
8438 This is a short-hand for marking the subtree and then cutting it."
8439 (interactive "p")
8440 (org-copy-subtree n 'cut))
8442 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8443 "Copy the current subtree it in the clipboard.
8444 With prefix arg N, copy this many sequential subtrees.
8445 This is a short-hand for marking the subtree and then copying it.
8446 If CUT is non-nil, actually cut the subtree.
8447 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8448 of some markers in the region, even if CUT is non-nil. This is
8449 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8450 (interactive "p")
8451 (let (beg end folded (beg0 (point)))
8452 (if (org-called-interactively-p 'any)
8453 (org-back-to-heading nil) ; take what looks like a subtree
8454 (org-back-to-heading t)) ; take what is really there
8455 (setq beg (point))
8456 (skip-chars-forward " \t\r\n")
8457 (save-match-data
8458 (if nosubtrees
8459 (outline-next-heading)
8460 (save-excursion (outline-end-of-heading)
8461 (setq folded (outline-invisible-p)))
8462 (ignore-errors (org-forward-heading-same-level (1- n) t))
8463 (org-end-of-subtree t t)))
8464 ;; Include the end of an inlinetask
8465 (when (and (featurep 'org-inlinetask)
8466 (looking-at-p (concat (org-inlinetask-outline-regexp)
8467 "END[ \t]*$")))
8468 (end-of-line))
8469 (setq end (point))
8470 (goto-char beg0)
8471 (when (> end beg)
8472 (setq org-subtree-clip-folded folded)
8473 (when (or cut force-store-markers)
8474 (org-save-markers-in-region beg end))
8475 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8476 (setq org-subtree-clip (current-kill 0))
8477 (message "%s: Subtree(s) with %d characters"
8478 (if cut "Cut" "Copied")
8479 (length org-subtree-clip)))))
8481 (defun org-paste-subtree (&optional level tree for-yank remove)
8482 "Paste the clipboard as a subtree, with modification of headline level.
8483 The entire subtree is promoted or demoted in order to match a new headline
8484 level.
8486 If the cursor is at the beginning of a headline, the same level as
8487 that headline is used to paste the tree.
8489 If not, the new level is derived from the *visible* headings
8490 before and after the insertion point, and taken to be the inferior headline
8491 level of the two. So if the previous visible heading is level 3 and the
8492 next is level 4 (or vice versa), level 4 will be used for insertion.
8493 This makes sure that the subtree remains an independent subtree and does
8494 not swallow low level entries.
8496 You can also force a different level, either by using a numeric prefix
8497 argument, or by inserting the heading marker by hand. For example, if the
8498 cursor is after \"*****\", then the tree will be shifted to level 5.
8500 If optional TREE is given, use this text instead of the kill ring.
8502 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8503 move back over whitespace before inserting, and move point to the end of
8504 the inserted text when done.
8506 When REMOVE is non-nil, remove the subtree from the clipboard."
8507 (interactive "P")
8508 (setq tree (or tree (and kill-ring (current-kill 0))))
8509 (unless (org-kill-is-subtree-p tree)
8510 (user-error "%s"
8511 (substitute-command-keys
8512 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8513 (org-with-limited-levels
8514 (let* ((visp (not (outline-invisible-p)))
8515 (txt tree)
8516 (^re_ "\\(\\*+\\)[ \t]*")
8517 (old-level (if (string-match org-outline-regexp-bol txt)
8518 (- (match-end 0) (match-beginning 0) 1)
8519 -1))
8520 (force-level (cond (level (prefix-numeric-value level))
8521 ((and (looking-at "[ \t]*$")
8522 (string-match
8523 "^\\*+$" (buffer-substring
8524 (point-at-bol) (point))))
8525 (- (match-end 0) (match-beginning 0)))
8526 ((and (bolp)
8527 (looking-at org-outline-regexp))
8528 (- (match-end 0) (point) 1))))
8529 (previous-level (save-excursion
8530 (condition-case nil
8531 (progn
8532 (outline-previous-visible-heading 1)
8533 (if (looking-at ^re_)
8534 (- (match-end 0) (match-beginning 0) 1)
8536 (error 1))))
8537 (next-level (save-excursion
8538 (condition-case nil
8539 (progn
8540 (or (looking-at org-outline-regexp)
8541 (outline-next-visible-heading 1))
8542 (if (looking-at ^re_)
8543 (- (match-end 0) (match-beginning 0) 1)
8545 (error 1))))
8546 (new-level (or force-level (max previous-level next-level)))
8547 (shift (if (or (= old-level -1)
8548 (= new-level -1)
8549 (= old-level new-level))
8551 (- new-level old-level)))
8552 (delta (if (> shift 0) -1 1))
8553 (func (if (> shift 0) 'org-demote 'org-promote))
8554 (org-odd-levels-only nil)
8555 beg end newend)
8556 ;; Remove the forced level indicator
8557 (when force-level
8558 (delete-region (point-at-bol) (point)))
8559 ;; Paste
8560 (beginning-of-line (if (bolp) 1 2))
8561 (setq beg (point))
8562 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8563 (insert-before-markers txt)
8564 (unless (string-match "\n\\'" txt) (insert "\n"))
8565 (setq newend (point))
8566 (org-reinstall-markers-in-region beg)
8567 (setq end (point))
8568 (goto-char beg)
8569 (skip-chars-forward " \t\n\r")
8570 (setq beg (point))
8571 (when (and (outline-invisible-p) visp)
8572 (save-excursion (outline-show-heading)))
8573 ;; Shift if necessary
8574 (unless (= shift 0)
8575 (save-restriction
8576 (narrow-to-region beg end)
8577 (while (not (= shift 0))
8578 (org-map-region func (point-min) (point-max))
8579 (setq shift (+ delta shift)))
8580 (goto-char (point-min))
8581 (setq newend (point-max))))
8582 (when (or (org-called-interactively-p 'interactive) for-yank)
8583 (message "Clipboard pasted as level %d subtree" new-level))
8584 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8585 kill-ring
8586 (eq org-subtree-clip (current-kill 0))
8587 org-subtree-clip-folded)
8588 ;; The tree was folded before it was killed/copied
8589 (outline-hide-subtree))
8590 (and for-yank (goto-char newend))
8591 (and remove (setq kill-ring (cdr kill-ring))))))
8593 (defun org-kill-is-subtree-p (&optional txt)
8594 "Check if the current kill is an outline subtree, or a set of trees.
8595 Returns nil if kill does not start with a headline, or if the first
8596 headline level is not the largest headline level in the tree.
8597 So this will actually accept several entries of equal levels as well,
8598 which is OK for `org-paste-subtree'.
8599 If optional TXT is given, check this string instead of the current kill."
8600 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8601 (re (org-get-limited-outline-regexp))
8602 (^re (concat "^" re))
8603 (start-level (and kill
8604 (string-match
8605 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8606 kill)
8607 (- (match-end 2) (match-beginning 2) 1)))
8608 (start (1+ (or (match-beginning 2) -1))))
8609 (if (not start-level)
8610 (progn
8611 nil) ;; does not even start with a heading
8612 (catch 'exit
8613 (while (setq start (string-match ^re kill (1+ start)))
8614 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8615 (throw 'exit nil)))
8616 t))))
8618 (defvar org-markers-to-move nil
8619 "Markers that should be moved with a cut-and-paste operation.
8620 Those markers are stored together with their positions relative to
8621 the start of the region.")
8623 (defun org-save-markers-in-region (beg end)
8624 "Check markers in region.
8625 If these markers are between BEG and END, record their position relative
8626 to BEG, so that after moving the block of text, we can put the markers back
8627 into place.
8628 This function gets called just before an entry or tree gets cut from the
8629 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8630 called immediately, to move the markers with the entries."
8631 (setq org-markers-to-move nil)
8632 (when (featurep 'org-clock)
8633 (org-clock-save-markers-for-cut-and-paste beg end))
8634 (when (featurep 'org-agenda)
8635 (org-agenda-save-markers-for-cut-and-paste beg end)))
8637 (defun org-check-and-save-marker (marker beg end)
8638 "Check if MARKER is between BEG and END.
8639 If yes, remember the marker and the distance to BEG."
8640 (when (and (marker-buffer marker)
8641 (equal (marker-buffer marker) (current-buffer))
8642 (>= marker beg) (< marker end))
8643 (push (cons marker (- marker beg)) org-markers-to-move)))
8645 (defun org-reinstall-markers-in-region (beg)
8646 "Move all remembered markers to their position relative to BEG."
8647 (dolist (x org-markers-to-move)
8648 (move-marker (car x) (+ beg (cdr x))))
8649 (setq org-markers-to-move nil))
8651 (defun org-narrow-to-subtree ()
8652 "Narrow buffer to the current subtree."
8653 (interactive)
8654 (save-excursion
8655 (save-match-data
8656 (org-with-limited-levels
8657 (narrow-to-region
8658 (progn (org-back-to-heading t) (point))
8659 (progn (org-end-of-subtree t t)
8660 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8661 (point)))))))
8663 (defun org-narrow-to-block ()
8664 "Narrow buffer to the current block."
8665 (interactive)
8666 (let* ((case-fold-search t)
8667 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8668 "^[ \t]*#\\+end_.*")))
8669 (if blockp
8670 (narrow-to-region (car blockp) (cdr blockp))
8671 (user-error "Not in a block"))))
8673 (defun org-clone-subtree-with-time-shift (n &optional shift)
8674 "Clone the task (subtree) at point N times.
8675 The clones will be inserted as siblings.
8677 In interactive use, the user will be prompted for the number of
8678 clones to be produced. If the entry has a timestamp, the user
8679 will also be prompted for a time shift, which may be a repeater
8680 as used in time stamps, for example `+3d'. To disable this,
8681 you can call the function with a universal prefix argument.
8683 When a valid repeater is given and the entry contains any time
8684 stamps, the clones will become a sequence in time, with time
8685 stamps in the subtree shifted for each clone produced. If SHIFT
8686 is nil or the empty string, time stamps will be left alone. The
8687 ID property of the original subtree is removed.
8689 If the original subtree did contain time stamps with a repeater,
8690 the following will happen:
8691 - the repeater will be removed in each clone
8692 - an additional clone will be produced, with the current, unshifted
8693 date(s) in the entry.
8694 - the original entry will be placed *after* all the clones, with
8695 repeater intact.
8696 - the start days in the repeater in the original entry will be shifted
8697 to past the last clone.
8698 In this way you can spell out a number of instances of a repeating task,
8699 and still retain the repeater to cover future instances of the task.
8701 As described above, N+1 clones are produced when the original
8702 subtree has a repeater. Setting N to 0, then, can be used to
8703 remove the repeater from a subtree and create a shifted clone
8704 with the original repeater."
8705 (interactive "nNumber of clones to produce: ")
8706 (let ((shift
8707 (or shift
8708 (if (and (not (equal current-prefix-arg '(4)))
8709 (save-excursion
8710 (re-search-forward org-ts-regexp-both
8711 (save-excursion
8712 (org-end-of-subtree t)
8713 (point)) t)))
8714 (read-from-minibuffer
8715 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8716 ""))) ;; No time shift
8717 (n-no-remove -1)
8718 (drawer-re org-drawer-regexp)
8719 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8720 beg end template task idprop
8721 shift-n shift-what doshift nmin nmax)
8722 (unless (wholenump n)
8723 (user-error "Invalid number of replications %s" n))
8724 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8725 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8726 shift)))
8727 (user-error "Invalid shift specification %s" shift))
8728 (when doshift
8729 (setq shift-n (string-to-number (match-string 1 shift))
8730 shift-what (cdr (assoc (match-string 2 shift)
8731 '(("d" . day) ("w" . week)
8732 ("m" . month) ("y" . year))))))
8733 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8734 (setq nmin 1 nmax n)
8735 (org-back-to-heading t)
8736 (setq beg (point))
8737 (setq idprop (org-entry-get nil "ID"))
8738 (org-end-of-subtree t t)
8739 (or (bolp) (insert "\n"))
8740 (setq end (point))
8741 (setq template (buffer-substring beg end))
8742 (when (and doshift
8743 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8744 (delete-region beg end)
8745 (setq end beg)
8746 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8747 (goto-char end)
8748 (cl-loop for n from nmin to nmax do
8749 ;; prepare clone
8750 (with-temp-buffer
8751 (insert template)
8752 (org-mode)
8753 (goto-char (point-min))
8754 (org-show-subtree)
8755 (and idprop (if org-clone-delete-id
8756 (org-entry-delete nil "ID")
8757 (org-id-get-create t)))
8758 (unless (= n 0)
8759 (while (re-search-forward org-clock-re nil t)
8760 (kill-whole-line))
8761 (goto-char (point-min))
8762 (while (re-search-forward drawer-re nil t)
8763 (org-remove-empty-drawer-at (point))))
8764 (goto-char (point-min))
8765 (when doshift
8766 (while (re-search-forward org-ts-regexp-both nil t)
8767 (org-timestamp-change (* n shift-n) shift-what))
8768 (unless (= n n-no-remove)
8769 (goto-char (point-min))
8770 (while (re-search-forward org-ts-regexp nil t)
8771 (save-excursion
8772 (goto-char (match-beginning 0))
8773 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8774 (delete-region (match-beginning 1) (match-end 1)))))))
8775 (setq task (buffer-string)))
8776 (insert task))
8777 (goto-char beg)))
8779 ;;; Outline Sorting
8781 (defun org-sort (with-case)
8782 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8783 Optional argument WITH-CASE means sort case-sensitively."
8784 (interactive "P")
8785 (cond
8786 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8787 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8789 (org-call-with-arg 'org-sort-entries with-case))))
8791 (defun org-sort-remove-invisible (s)
8792 "Remove invisible links from string S."
8793 (remove-text-properties 0 (length s) org-rm-props s)
8794 (while (string-match org-bracket-link-regexp s)
8795 (setq s (replace-match (if (match-end 2)
8796 (match-string 3 s)
8797 (match-string 1 s))
8798 t t s)))
8799 (let ((st (format " %s " s)))
8800 (while (string-match org-emph-re st)
8801 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8802 (setq s (substring st 1 -1)))
8805 (defvar org-priority-regexp) ; defined later in the file
8807 (defvar org-after-sorting-entries-or-items-hook nil
8808 "Hook that is run after a bunch of entries or items have been sorted.
8809 When children are sorted, the cursor is in the parent line when this
8810 hook gets called. When a region or a plain list is sorted, the cursor
8811 will be in the first entry of the sorted region/list.")
8813 (defun org-sort-entries
8814 (&optional with-case sorting-type getkey-func compare-func property)
8815 "Sort entries on a certain level of an outline tree.
8816 If there is an active region, the entries in the region are sorted.
8817 Else, if the cursor is before the first entry, sort the top-level items.
8818 Else, the children of the entry at point are sorted.
8820 Sorting can be alphabetically, numerically, by date/time as given by
8821 a time stamp, by a property, by priority order, or by a custom function.
8823 The command prompts for the sorting type unless it has been given to the
8824 function through the SORTING-TYPE argument, which needs to be a character,
8825 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8826 the precise meaning of each character:
8828 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8829 c By creation time, which is assumed to be the first inactive time stamp
8830 at the beginning of a line.
8831 d By deadline date/time.
8832 k By clocking time.
8833 n Numerically, by converting the beginning of the entry/item to a number.
8834 o By order of TODO keywords.
8835 p By priority according to the cookie.
8836 r By the value of a property.
8837 s By scheduled date/time.
8838 t By date/time, either the first active time stamp in the entry, or, if
8839 none exist, by the first inactive one.
8841 Capital letters will reverse the sort order.
8843 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8844 called with point at the beginning of the record. It must return either
8845 a string or a number that should serve as the sorting key for that record.
8847 Comparing entries ignores case by default. However, with an optional argument
8848 WITH-CASE, the sorting considers case as well.
8850 Sorting is done against the visible part of the headlines, it ignores hidden
8851 links.
8853 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8854 (interactive "P")
8855 (let ((case-func (if with-case 'identity 'downcase))
8856 (cmstr
8857 ;; The clock marker is lost when using `sort-subr', let's
8858 ;; store the clocking string.
8859 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8860 (save-excursion
8861 (goto-char org-clock-marker)
8862 (buffer-substring-no-properties (line-beginning-position)
8863 (point)))))
8864 start beg end stars re re2
8865 txt what tmp)
8866 ;; Find beginning and end of region to sort
8867 (cond
8868 ((org-region-active-p)
8869 ;; we will sort the region
8870 (setq end (region-end)
8871 what "region")
8872 (goto-char (region-beginning))
8873 (unless (org-at-heading-p) (outline-next-heading))
8874 (setq start (point)))
8875 ((or (org-at-heading-p)
8876 (ignore-errors (progn (org-back-to-heading) t)))
8877 ;; we will sort the children of the current headline
8878 (org-back-to-heading)
8879 (setq start (point)
8880 end (progn (org-end-of-subtree t t)
8881 (or (bolp) (insert "\n"))
8882 (when (>= (org-back-over-empty-lines) 1)
8883 (forward-line 1))
8884 (point))
8885 what "children")
8886 (goto-char start)
8887 (outline-show-subtree)
8888 (outline-next-heading))
8890 ;; we will sort the top-level entries in this file
8891 (goto-char (point-min))
8892 (or (org-at-heading-p) (outline-next-heading))
8893 (setq start (point))
8894 (goto-char (point-max))
8895 (beginning-of-line 1)
8896 (when (looking-at ".*?\\S-")
8897 ;; File ends in a non-white line
8898 (end-of-line 1)
8899 (insert "\n"))
8900 (setq end (point-max))
8901 (setq what "top-level")
8902 (goto-char start)
8903 (outline-show-all)))
8905 (setq beg (point))
8906 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8908 (looking-at "\\(\\*+\\)")
8909 (setq stars (match-string 1)
8910 re (concat "^" (regexp-quote stars) " +")
8911 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8912 txt (buffer-substring beg end))
8913 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8914 (when (and (not (equal stars "*")) (string-match re2 txt))
8915 (user-error "Region to sort contains a level above the first entry"))
8917 (unless sorting-type
8918 (message
8919 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8920 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8921 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8922 what)
8923 (setq sorting-type (read-char-exclusive))
8925 (unless getkey-func
8926 (and (= (downcase sorting-type) ?f)
8927 (setq getkey-func
8928 (completing-read "Sort using function: "
8929 obarray 'fboundp t nil nil))
8930 (setq getkey-func (intern getkey-func))))
8932 (and (= (downcase sorting-type) ?r)
8933 (not property)
8934 (setq property
8935 (completing-read "Property: "
8936 (mapcar #'list (org-buffer-property-keys t))
8937 nil t))))
8939 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8940 (message "Sorting entries...")
8942 (save-restriction
8943 (narrow-to-region start end)
8944 (let ((dcst (downcase sorting-type))
8945 (case-fold-search nil)
8946 (now (current-time)))
8947 (sort-subr
8948 (/= dcst sorting-type)
8949 ;; This function moves to the beginning character of the "record" to
8950 ;; be sorted.
8951 (lambda nil
8952 (if (re-search-forward re nil t)
8953 (goto-char (match-beginning 0))
8954 (goto-char (point-max))))
8955 ;; This function moves to the last character of the "record" being
8956 ;; sorted.
8957 (lambda nil
8958 (save-match-data
8959 (condition-case nil
8960 (outline-forward-same-level 1)
8961 (error
8962 (goto-char (point-max))))))
8963 ;; This function returns the value that gets sorted against.
8964 (lambda nil
8965 (cond
8966 ((= dcst ?n)
8967 (if (looking-at org-complex-heading-regexp)
8968 (string-to-number (org-sort-remove-invisible (match-string 4)))
8969 nil))
8970 ((= dcst ?a)
8971 (if (looking-at org-complex-heading-regexp)
8972 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8973 nil))
8974 ((= dcst ?k)
8975 (or (get-text-property (point) :org-clock-minutes) 0))
8976 ((= dcst ?t)
8977 (let ((end (save-excursion (outline-next-heading) (point))))
8978 (if (or (re-search-forward org-ts-regexp end t)
8979 (re-search-forward org-ts-regexp-both end t))
8980 (org-time-string-to-seconds (match-string 0))
8981 (org-float-time now))))
8982 ((= dcst ?c)
8983 (let ((end (save-excursion (outline-next-heading) (point))))
8984 (if (re-search-forward
8985 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8986 end t)
8987 (org-time-string-to-seconds (match-string 0))
8988 (org-float-time now))))
8989 ((= dcst ?s)
8990 (let ((end (save-excursion (outline-next-heading) (point))))
8991 (if (re-search-forward org-scheduled-time-regexp end t)
8992 (org-time-string-to-seconds (match-string 1))
8993 (org-float-time now))))
8994 ((= dcst ?d)
8995 (let ((end (save-excursion (outline-next-heading) (point))))
8996 (if (re-search-forward org-deadline-time-regexp end t)
8997 (org-time-string-to-seconds (match-string 1))
8998 (org-float-time now))))
8999 ((= dcst ?p)
9000 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9001 (string-to-char (match-string 2))
9002 org-default-priority))
9003 ((= dcst ?r)
9004 (or (org-entry-get nil property) ""))
9005 ((= dcst ?o)
9006 (when (looking-at org-complex-heading-regexp)
9007 (let* ((m (match-string 2))
9008 (s (if (member m org-done-keywords) '- '+)))
9009 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9010 ((= dcst ?f)
9011 (if getkey-func
9012 (progn
9013 (setq tmp (funcall getkey-func))
9014 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9015 tmp)
9016 (error "Invalid key function `%s'" getkey-func)))
9017 (t (error "Invalid sorting type `%c'" sorting-type))))
9019 (cond
9020 ((= dcst ?a) 'string<)
9021 ((= dcst ?f) compare-func)
9022 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9023 (run-hooks 'org-after-sorting-entries-or-items-hook)
9024 ;; Reset the clock marker if needed
9025 (when cmstr
9026 (save-excursion
9027 (goto-char start)
9028 (search-forward cmstr nil t)
9029 (move-marker org-clock-marker (point))))
9030 (message "Sorting entries...done")))
9032 ;;; The orgstruct minor mode
9034 ;; Define a minor mode which can be used in other modes in order to
9035 ;; integrate the org-mode structure editing commands.
9037 ;; This is really a hack, because the org-mode structure commands use
9038 ;; keys which normally belong to the major mode. Here is how it
9039 ;; works: The minor mode defines all the keys necessary to operate the
9040 ;; structure commands, but wraps the commands into a function which
9041 ;; tests if the cursor is currently at a headline or a plain list
9042 ;; item. If that is the case, the structure command is used,
9043 ;; temporarily setting many Org-mode variables like regular
9044 ;; expressions for filling etc. However, when any of those keys is
9045 ;; used at a different location, function uses `key-binding' to look
9046 ;; up if the key has an associated command in another currently active
9047 ;; keymap (minor modes, major mode, global), and executes that
9048 ;; command. There might be problems if any of the keys is otherwise
9049 ;; used as a prefix key.
9051 (defcustom orgstruct-heading-prefix-regexp ""
9052 "Regexp that matches the custom prefix of Org headlines in
9053 orgstruct(++)-mode."
9054 :group 'org
9055 :version "24.4"
9056 :package-version '(Org . "8.3")
9057 :type 'regexp)
9058 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9060 (defcustom orgstruct-setup-hook nil
9061 "Hook run after orgstruct-mode-map is filled."
9062 :group 'org
9063 :version "24.4"
9064 :package-version '(Org . "8.0")
9065 :type 'hook)
9067 (defvar orgstruct-initialized nil)
9069 (defvar org-local-vars nil
9070 "List of local variables, for use by `orgstruct-mode'.")
9072 ;;;###autoload
9073 (define-minor-mode orgstruct-mode
9074 "Toggle the minor mode `orgstruct-mode'.
9075 This mode is for using Org-mode structure commands in other
9076 modes. The following keys behave as if Org-mode were active, if
9077 the cursor is on a headline, or on a plain list item (both as
9078 defined by Org-mode)."
9079 nil " OrgStruct" (make-sparse-keymap)
9080 (funcall (if orgstruct-mode
9081 'add-to-invisibility-spec
9082 'remove-from-invisibility-spec)
9083 '(outline . t))
9084 (when orgstruct-mode
9085 (org-load-modules-maybe)
9086 (unless orgstruct-initialized
9087 (orgstruct-setup)
9088 (setq orgstruct-initialized t))))
9090 ;;;###autoload
9091 (defun turn-on-orgstruct ()
9092 "Unconditionally turn on `orgstruct-mode'."
9093 (orgstruct-mode 1))
9095 (defvar-local orgstruct-is-++ nil
9096 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9097 (defvar-local org-fb-vars nil)
9098 (defun orgstruct++-mode (&optional arg)
9099 "Toggle `orgstruct-mode', the enhanced version of it.
9100 In addition to setting orgstruct-mode, this also exports all
9101 indentation and autofilling variables from org-mode into the
9102 buffer. It will also recognize item context in multiline items."
9103 (interactive "P")
9104 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9105 (if (< arg 1)
9106 (progn (orgstruct-mode -1)
9107 (dolist (v org-fb-vars)
9108 (set (make-local-variable (car v))
9109 (if (eq (car-safe (cadr v)) 'quote)
9110 (cl-cadadr v)
9111 (nth 1 v)))))
9112 (orgstruct-mode 1)
9113 (setq org-fb-vars nil)
9114 (unless org-local-vars
9115 (setq org-local-vars (org-get-local-variables)))
9116 (let (var val)
9117 (dolist (x org-local-vars)
9118 (when (string-match
9119 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9120 \\|fill-prefix\\|indent-\\)"
9121 (symbol-name (car x)))
9122 (setq var (car x) val (nth 1 x))
9123 (push (list var `(quote ,(eval var))) org-fb-vars)
9124 (set (make-local-variable var)
9125 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9126 (setq-local orgstruct-is-++ t))))
9128 ;;;###autoload
9129 (defun turn-on-orgstruct++ ()
9130 "Unconditionally turn on `orgstruct++-mode'."
9131 (orgstruct++-mode 1))
9133 (defun orgstruct-error ()
9134 "Error when there is no default binding for a structure key."
9135 (interactive)
9136 (funcall (if (fboundp 'user-error)
9137 'user-error
9138 'error)
9139 "This key has no function outside structure elements"))
9141 (defun orgstruct-setup ()
9142 "Setup orgstruct keymap."
9143 (dolist (cell '((org-demote . t)
9144 (org-metaleft . t)
9145 (org-metaright . t)
9146 (org-promote . t)
9147 (org-shiftmetaleft . t)
9148 (org-shiftmetaright . t)
9149 org-backward-element
9150 org-backward-heading-same-level
9151 org-ctrl-c-ret
9152 org-ctrl-c-minus
9153 org-ctrl-c-star
9154 org-cycle
9155 org-forward-heading-same-level
9156 org-insert-heading
9157 org-insert-heading-respect-content
9158 org-kill-note-or-show-branches
9159 org-mark-subtree
9160 org-meta-return
9161 org-metadown
9162 org-metaup
9163 org-narrow-to-subtree
9164 org-promote-subtree
9165 org-reveal
9166 org-shiftdown
9167 org-shiftleft
9168 org-shiftmetadown
9169 org-shiftmetaup
9170 org-shiftright
9171 org-shifttab
9172 org-shifttab
9173 org-shiftup
9174 org-show-children
9175 org-show-subtree
9176 org-sort
9177 org-up-element
9178 outline-demote
9179 outline-next-visible-heading
9180 outline-previous-visible-heading
9181 outline-promote
9182 outline-up-heading))
9183 (let ((f (or (car-safe cell) cell))
9184 (disable-when-heading-prefix (cdr-safe cell)))
9185 (when (fboundp f)
9186 (let ((new-bindings))
9187 (dolist (binding (nconc (where-is-internal f org-mode-map)
9188 (where-is-internal f outline-mode-map)))
9189 (push binding new-bindings)
9190 ;; TODO use local-function-key-map
9191 (dolist (rep '(("<tab>" . "TAB")
9192 ("<return>" . "RET")
9193 ("<escape>" . "ESC")
9194 ("<delete>" . "DEL")))
9195 (setq binding (read-kbd-macro
9196 (let ((case-fold-search))
9197 (replace-regexp-in-string
9198 (regexp-quote (cdr rep))
9199 (car rep)
9200 (key-description binding)))))
9201 (cl-pushnew binding new-bindings :test 'equal)))
9202 (dolist (binding new-bindings)
9203 (let ((key (lookup-key orgstruct-mode-map binding)))
9204 (when (or (not key) (numberp key))
9205 (ignore-errors
9206 (org-defkey orgstruct-mode-map
9207 binding
9208 (orgstruct-make-binding
9209 f binding disable-when-heading-prefix))))))))))
9210 (run-hooks 'orgstruct-setup-hook))
9212 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9213 "Create a function for binding in the structure minor mode.
9214 FUN is the command to call inside a table. KEY is the key that
9215 should be checked in for a command to execute outside of tables.
9216 Non-nil `disable-when-heading-prefix' means to disable the command
9217 if `orgstruct-heading-prefix-regexp' is not empty."
9218 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9219 (let ((nname name)
9220 (i 0))
9221 (while (fboundp (intern nname))
9222 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9223 (setq name (intern nname)))
9224 (eval
9225 (let ((bindings '((org-heading-regexp
9226 (concat "^"
9227 orgstruct-heading-prefix-regexp
9228 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9229 (org-outline-regexp
9230 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9231 (org-outline-regexp-bol
9232 (concat "^" org-outline-regexp))
9233 (outline-regexp org-outline-regexp)
9234 (outline-heading-end-regexp "\n")
9235 (outline-level 'org-outline-level)
9236 (outline-heading-alist))))
9237 `(defun ,name (arg)
9238 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9239 "Outside of structure, run the binding of `"
9240 (key-description key) "'."
9241 (when disable-when-heading-prefix
9242 (concat
9243 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9244 "back to the default binding due to limitations of Org's implementation of\n"
9245 "`" (symbol-name fun) "'.")))
9246 (interactive "p")
9247 (let* ((disable
9248 ,(and disable-when-heading-prefix
9249 '(not (string= orgstruct-heading-prefix-regexp ""))))
9250 (fallback
9251 (or disable
9252 (not
9253 (let* ,bindings
9254 (org-context-p 'headline 'item
9255 ,(when (memq fun
9256 '(org-insert-heading
9257 org-insert-heading-respect-content
9258 org-meta-return))
9259 '(when orgstruct-is-++
9260 'item-body))))))))
9261 (if fallback
9262 (let* ((orgstruct-mode)
9263 (binding
9264 (let ((key ,key))
9265 (catch 'exit
9266 (dolist
9267 (rep
9268 '(nil
9269 ("<\\([^>]*\\)tab>" . "\\1TAB")
9270 ("<\\([^>]*\\)return>" . "\\1RET")
9271 ("<\\([^>]*\\)escape>" . "\\1ESC")
9272 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9273 nil)
9274 (when rep
9275 (setq key (read-kbd-macro
9276 (let ((case-fold-search))
9277 (replace-regexp-in-string
9278 (car rep)
9279 (cdr rep)
9280 (key-description key))))))
9281 (when (key-binding key)
9282 (throw 'exit (key-binding key))))))))
9283 (if (keymapp binding)
9284 (org-set-transient-map binding)
9285 (let ((func (or binding
9286 (unless disable
9287 'orgstruct-error))))
9288 (when func
9289 (call-interactively func)))))
9290 (org-run-like-in-org-mode
9291 (lambda ()
9292 (interactive)
9293 (let* ,bindings
9294 (call-interactively ',fun)))))))))
9295 name))
9297 (defun org-contextualize-keys (alist contexts)
9298 "Return valid elements in ALIST depending on CONTEXTS.
9300 `org-agenda-custom-commands' or `org-capture-templates' are the
9301 values used for ALIST, and `org-agenda-custom-commands-contexts'
9302 or `org-capture-templates-contexts' are the associated contexts
9303 definitions."
9304 (let ((contexts
9305 ;; normalize contexts
9306 (mapcar
9307 (lambda(c) (cond ((listp (cadr c))
9308 (list (car c) (car c) (nth 1 c)))
9309 ((string= "" (cadr c))
9310 (list (car c) (car c) (nth 2 c)))
9311 (t c)))
9312 contexts))
9313 (a alist) r s)
9314 ;; loop over all commands or templates
9315 (dolist (c a)
9316 (let (vrules repl)
9317 (cond
9318 ((not (assoc (car c) contexts))
9319 (push c r))
9320 ((and (assoc (car c) contexts)
9321 (setq vrules (org-contextualize-validate-key
9322 (car c) contexts)))
9323 (mapc (lambda (vr)
9324 (unless (equal (car vr) (cadr vr))
9325 (setq repl vr)))
9326 vrules)
9327 (if (not repl) (push c r)
9328 (push (cadr repl) s)
9329 (push
9330 (cons (car c)
9331 (cdr (or (assoc (cadr repl) alist)
9332 (error "Undefined key `%s' as contextual replacement for `%s'"
9333 (cadr repl) (car c)))))
9334 r))))))
9335 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9336 (delq
9338 (delete-dups
9339 (mapcar (lambda (x)
9340 (let ((tpl (car x)))
9341 (unless (delq
9343 (mapcar (lambda (y)
9344 (equal y tpl))
9346 x)))
9347 (reverse r))))))
9349 (defun org-contextualize-validate-key (key contexts)
9350 "Check CONTEXTS for agenda or capture KEY."
9351 (let (res)
9352 (dolist (r contexts)
9353 (dolist (rr (car (last r)))
9354 (when
9355 (and (equal key (car r))
9356 (if (functionp rr) (funcall rr)
9357 (or (and (eq (car rr) 'in-file)
9358 (buffer-file-name)
9359 (string-match (cdr rr) (buffer-file-name)))
9360 (and (eq (car rr) 'in-mode)
9361 (string-match (cdr rr) (symbol-name major-mode)))
9362 (and (eq (car rr) 'in-buffer)
9363 (string-match (cdr rr) (buffer-name)))
9364 (when (and (eq (car rr) 'not-in-file)
9365 (buffer-file-name))
9366 (not (string-match (cdr rr) (buffer-file-name))))
9367 (when (eq (car rr) 'not-in-mode)
9368 (not (string-match (cdr rr) (symbol-name major-mode))))
9369 (when (eq (car rr) 'not-in-buffer)
9370 (not (string-match (cdr rr) (buffer-name)))))))
9371 (push r res))))
9372 (delete-dups (delq nil res))))
9374 (defun org-context-p (&rest contexts)
9375 "Check if local context is any of CONTEXTS.
9376 Possible values in the list of contexts are `table', `headline', and `item'."
9377 (let ((pos (point)))
9378 (goto-char (point-at-bol))
9379 (prog1 (or (and (memq 'table contexts)
9380 (looking-at "[ \t]*|"))
9381 (and (memq 'headline contexts)
9382 (looking-at org-outline-regexp))
9383 (and (memq 'item contexts)
9384 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9385 (and (memq 'item-body contexts)
9386 (org-in-item-p)))
9387 (goto-char pos))))
9389 (defconst org-unique-local-variables
9390 '(org-element--cache
9391 org-element--cache-objects
9392 org-element--cache-sync-keys
9393 org-element--cache-sync-requests
9394 org-element--cache-sync-timer)
9395 "List of local variables that cannot be transferred to another buffer.")
9397 (defun org-get-local-variables ()
9398 "Return a list of all local variables in an Org mode buffer."
9399 (delq nil
9400 (mapcar
9401 (lambda (x)
9402 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9403 (name (car binding)))
9404 (and (not (get name 'org-state))
9405 (not (memq name org-unique-local-variables))
9406 (string-match-p
9407 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9408 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9409 (symbol-name name))
9410 binding)))
9411 (with-temp-buffer
9412 (org-mode)
9413 (buffer-local-variables)))))
9415 (defun org-clone-local-variables (from-buffer &optional regexp)
9416 "Clone local variables from FROM-BUFFER.
9417 Optional argument REGEXP selects variables to clone."
9418 (dolist (pair (buffer-local-variables from-buffer))
9419 (let ((name (car pair)))
9420 (when (and (symbolp name)
9421 (not (memq name org-unique-local-variables))
9422 (or (null regexp) (string-match regexp (symbol-name name))))
9423 (set (make-local-variable name) (cdr pair))))))
9425 ;;;###autoload
9426 (defun org-run-like-in-org-mode (cmd)
9427 "Run a command, pretending that the current buffer is in Org-mode.
9428 This will temporarily bind local variables that are typically bound in
9429 Org-mode to the values they have in Org-mode, and then interactively
9430 call CMD."
9431 (org-load-modules-maybe)
9432 (unless org-local-vars
9433 (setq org-local-vars (org-get-local-variables)))
9434 (let (binds)
9435 (dolist (var org-local-vars)
9436 (when (or (not (boundp (car var)))
9437 (eq (symbol-value (car var))
9438 (default-value (car var))))
9439 (push (list (car var) `(quote ,(cadr var))) binds)))
9440 (eval `(let ,binds
9441 (call-interactively (quote ,cmd))))))
9443 (defun org-get-category (&optional pos force-refresh)
9444 "Get the category applying to position POS."
9445 (save-match-data
9446 (when force-refresh (org-refresh-category-properties))
9447 (let ((pos (or pos (point))))
9448 (or (get-text-property pos 'org-category)
9449 (progn (org-refresh-category-properties)
9450 (get-text-property pos 'org-category))))))
9452 ;;; Refresh properties
9454 (defun org-refresh-properties (dprop tprop)
9455 "Refresh buffer text properties.
9456 DPROP is the drawer property and TPROP is either the
9457 corresponding text property to set, or an alist with each element
9458 being a text property (as a symbol) and a function to apply to
9459 the value of the drawer property."
9460 (let ((case-fold-search t)
9461 (inhibit-read-only t))
9462 (org-with-silent-modifications
9463 (save-excursion
9464 (save-restriction
9465 (widen)
9466 (goto-char (point-min))
9467 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9468 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9470 (defun org-refresh-property (tprop p)
9471 "Refresh the buffer text property TPROP from the drawer property P.
9472 The refresh happens only for the current tree (not subtree)."
9473 (unless (org-before-first-heading-p)
9474 (save-excursion
9475 (org-back-to-heading t)
9476 (if (symbolp tprop)
9477 ;; TPROP is a text property symbol
9478 (put-text-property
9479 (point) (or (outline-next-heading) (point-max)) tprop p)
9480 ;; TPROP is an alist with (properties . function) elements
9481 (dolist (al tprop)
9482 (save-excursion
9483 (put-text-property
9484 (line-beginning-position) (or (outline-next-heading) (point-max))
9485 (car al)
9486 (funcall (cdr al) p))))))))
9488 (defun org-refresh-category-properties ()
9489 "Refresh category text properties in the buffer."
9490 (let ((case-fold-search t)
9491 (inhibit-read-only t)
9492 (default-category
9493 (cond ((null org-category)
9494 (if buffer-file-name
9495 (file-name-sans-extension
9496 (file-name-nondirectory buffer-file-name))
9497 "???"))
9498 ((symbolp org-category) (symbol-name org-category))
9499 (t org-category))))
9500 (org-with-silent-modifications
9501 (org-with-wide-buffer
9502 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9503 ;; This is the default category for the buffer. If none is
9504 ;; found, fall-back to `org-category' or buffer file name.
9505 (put-text-property
9506 (point-min) (point-max)
9507 'org-category
9508 (catch 'buffer-category
9509 (goto-char (point-max))
9510 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9511 (let ((element (org-element-at-point)))
9512 (when (eq (org-element-type element) 'keyword)
9513 (throw 'buffer-category
9514 (org-element-property :value element)))))
9515 default-category))
9516 ;; Set sub-tree specific categories.
9517 (goto-char (point-min))
9518 (let ((regexp (org-re-property "CATEGORY")))
9519 (while (re-search-forward regexp nil t)
9520 (let ((value (org-match-string-no-properties 3)))
9521 (when (org-at-property-p)
9522 (put-text-property
9523 (save-excursion (org-back-to-heading t) (point))
9524 (save-excursion (org-end-of-subtree t t) (point))
9525 'org-category
9526 value)))))))))
9528 (defun org-refresh-stats-properties ()
9529 "Refresh stats text properties in the buffer."
9530 (let (stats)
9531 (org-with-silent-modifications
9532 (save-excursion
9533 (save-restriction
9534 (widen)
9535 (goto-char (point-min))
9536 (while (re-search-forward
9537 (concat org-outline-regexp-bol ".*"
9538 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9539 nil t)
9540 (setq stats (cond ((equal (match-string 3) "0") 0)
9541 ((match-string 2)
9542 (/ (* (string-to-number (match-string 2)) 100)
9543 (string-to-number (match-string 3))))
9544 (t (string-to-number (match-string 1)))))
9545 (org-back-to-heading t)
9546 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9547 'org-stats stats)))))))
9549 (defun org-refresh-effort-properties ()
9550 "Refresh effort properties"
9551 (org-refresh-properties
9552 org-effort-property
9553 '((effort . identity)
9554 (effort-minutes . org-duration-string-to-minutes))))
9556 ;;;; Link Stuff
9558 ;;; Link abbreviations
9560 (defun org-link-expand-abbrev (link)
9561 "Apply replacements as defined in `org-link-abbrev-alist'."
9562 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9563 (let* ((key (match-string 1 link))
9564 (as (or (assoc key org-link-abbrev-alist-local)
9565 (assoc key org-link-abbrev-alist)))
9566 (tag (and (match-end 2) (match-string 3 link)))
9567 rpl)
9568 (if (not as)
9569 link
9570 (setq rpl (cdr as))
9571 (cond
9572 ((symbolp rpl) (funcall rpl tag))
9573 ((string-match "%(\\([^)]+\\))" rpl)
9574 (replace-match
9575 (save-match-data
9576 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9577 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9578 ((string-match "%h" rpl)
9579 (replace-match (url-hexify-string (or tag "")) t t rpl))
9580 (t (concat rpl tag)))))
9581 link))
9583 ;;; Storing and inserting links
9585 (defvar org-insert-link-history nil
9586 "Minibuffer history for links inserted with `org-insert-link'.")
9588 (defvar org-stored-links nil
9589 "Contains the links stored with `org-store-link'.")
9591 (defvar org-store-link-plist nil
9592 "Plist with info about the most recently link created with `org-store-link'.")
9594 (defvar org-link-protocols nil
9595 "Link protocols added to Org-mode using `org-add-link-type'.")
9597 (defvar org-store-link-functions nil
9598 "List of functions that are called to create and store a link.
9599 Each function will be called in turn until one returns a non-nil
9600 value. Each function should check if it is responsible for creating
9601 this link (for example by looking at the major mode).
9602 If not, it must exit and return nil.
9603 If yes, it should return a non-nil value after a calling
9604 `org-store-link-props' with a list of properties and values.
9605 Special properties are:
9607 :type The link prefix, like \"http\". This must be given.
9608 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9609 This is obligatory as well.
9610 :description Optional default description for the second pair
9611 of brackets in an Org-mode link. The user can still change
9612 this when inserting this link into an Org-mode buffer.
9614 In addition to these, any additional properties can be specified
9615 and then used in capture templates.")
9617 (defun org-add-link-type (type &optional follow export)
9618 "Add TYPE to the list of `org-link-types'.
9619 Re-compute all regular expressions depending on `org-link-types'
9621 FOLLOW and EXPORT are two functions.
9623 FOLLOW should take the link path as the single argument and do whatever
9624 is necessary to follow the link, for example find a file or display
9625 a mail message.
9627 EXPORT should format the link path for export to one of the export formats.
9628 It should be a function accepting three arguments:
9630 path the path of the link, the text after the prefix (like \"http:\")
9631 desc the description of the link, if any
9632 format the export format, a symbol like `html' or `latex' or `ascii'.
9634 The function may use the FORMAT information to return different values
9635 depending on the format. The return value will be put literally into
9636 the exported file. If the return value is nil, this means Org should
9637 do what it normally does with links which do not have EXPORT defined.
9639 Org mode has a built-in default for exporting links. If you are happy with
9640 this default, there is no need to define an export function for the link
9641 type. For a simple example of an export function, see `org-bbdb.el'."
9642 (add-to-list 'org-link-types type t)
9643 (org-make-link-regexps)
9644 (org-element-update-syntax)
9645 (if (assoc type org-link-protocols)
9646 (setcdr (assoc type org-link-protocols) (list follow export))
9647 (push (list type follow export) org-link-protocols)))
9649 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9650 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9652 ;;;###autoload
9653 (defun org-store-link (arg)
9654 "\\<org-mode-map>Store an org-link to the current location.
9655 This link is added to `org-stored-links' and can later be inserted
9656 into an Org buffer with \\[org-insert-link].
9658 For some link types, a prefix ARG is interpreted.
9659 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9660 For file links, ARG negates `org-context-in-file-links'.
9662 A double prefix ARG force skipping storing functions that are not
9663 part of Org's core.
9665 A triple prefix ARG force storing a link for each line in the
9666 active region."
9667 (interactive "P")
9668 (org-load-modules-maybe)
9669 (if (and (equal arg '(64)) (org-region-active-p))
9670 (save-excursion
9671 (let ((end (region-end)))
9672 (goto-char (region-beginning))
9673 (set-mark (point))
9674 (while (< (point-at-eol) end)
9675 (move-end-of-line 1) (activate-mark)
9676 (let (current-prefix-arg)
9677 (call-interactively 'org-store-link))
9678 (move-beginning-of-line 2)
9679 (set-mark (point)))))
9680 (org-with-limited-levels
9681 (setq org-store-link-plist nil)
9682 (let (link cpltxt desc description search
9683 txt custom-id agenda-link sfuns sfunsn)
9684 (cond
9686 ;; Store a link using an external link type
9687 ((and (not (equal arg '(16)))
9688 (setq sfuns
9689 (delq
9690 nil (mapcar (lambda (f)
9691 (let (fs) (if (funcall f) (push f fs))))
9692 org-store-link-functions))
9693 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9694 (or (and (cdr sfuns)
9695 (funcall (intern
9696 (completing-read
9697 "Which function for creating the link? "
9698 sfunsn nil t (car sfunsn)))))
9699 (funcall (caar sfuns)))
9700 (setq link (plist-get org-store-link-plist :link)
9701 desc (or (plist-get org-store-link-plist
9702 :description)
9703 link))))
9705 ;; Store a link from a source code buffer.
9706 ((org-src-edit-buffer-p)
9707 (cond
9708 ((save-excursion
9709 (beginning-of-line)
9710 (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
9711 "[ \t]*$")))
9712 (setq link (format "(%s)" (org-match-string-no-properties 1))))
9713 ((org-called-interactively-p 'any)
9714 (let (label)
9715 (while (or (not label)
9716 (org-with-wide-buffer
9717 (goto-char (point-min))
9718 (re-search-forward
9719 (regexp-quote (format org-coderef-label-format label))
9720 nil t)))
9721 (when label (message "Label exists already") (sit-for 2))
9722 (setq label (read-string "Code line label: " label)))
9723 (end-of-line)
9724 (setq link (format org-coderef-label-format label))
9725 (let ((gc (- 79 (length link))))
9726 (if (< (current-column) gc) (org-move-to-column gc t)
9727 (insert " ")))
9728 (insert link)
9729 (setq link (concat "(" label ")") desc nil)))
9730 (t (setq link nil))))
9732 ;; We are in the agenda, link to referenced location
9733 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9734 (let ((m (or (get-text-property (point) 'org-hd-marker)
9735 (get-text-property (point) 'org-marker))))
9736 (when m
9737 (org-with-point-at m
9738 (setq agenda-link
9739 (if (org-called-interactively-p 'any)
9740 (call-interactively 'org-store-link)
9741 (org-store-link nil)))))))
9743 ((eq major-mode 'calendar-mode)
9744 (let ((cd (calendar-cursor-to-date)))
9745 (setq link
9746 (format-time-string
9747 (car org-time-stamp-formats)
9748 (apply 'encode-time
9749 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9750 nil nil nil))))
9751 (org-store-link-props :type "calendar" :date cd)))
9753 ((eq major-mode 'help-mode)
9754 (setq link (concat "help:" (save-excursion
9755 (goto-char (point-min))
9756 (looking-at "^[^ ]+")
9757 (match-string 0))))
9758 (org-store-link-props :type "help"))
9760 ((eq major-mode 'w3-mode)
9761 (setq cpltxt (if (and (buffer-name)
9762 (not (string-match "Untitled" (buffer-name))))
9763 (buffer-name)
9764 (url-view-url t))
9765 link (url-view-url t))
9766 (org-store-link-props :type "w3" :url (url-view-url t)))
9768 ((eq major-mode 'image-mode)
9769 (setq cpltxt (concat "file:"
9770 (abbreviate-file-name buffer-file-name))
9771 link cpltxt)
9772 (org-store-link-props :type "image" :file buffer-file-name))
9774 ;; In dired, store a link to the file of the current line
9775 ((derived-mode-p 'dired-mode)
9776 (let ((file (dired-get-filename nil t)))
9777 (setq file (if file
9778 (abbreviate-file-name
9779 (expand-file-name (dired-get-filename nil t)))
9780 ;; otherwise, no file so use current directory.
9781 default-directory))
9782 (setq cpltxt (concat "file:" file)
9783 link cpltxt)))
9785 ((setq search (run-hook-with-args-until-success
9786 'org-create-file-search-functions))
9787 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9788 "::" search))
9789 (setq cpltxt (or description link)))
9791 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9792 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9793 (cond
9794 ;; Store a link using the target at point
9795 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9796 (setq cpltxt
9797 (concat "file:"
9798 (abbreviate-file-name
9799 (buffer-file-name (buffer-base-buffer)))
9800 "::" (match-string 1))
9801 link cpltxt))
9802 ((and (featurep 'org-id)
9803 (or (eq org-id-link-to-org-use-id t)
9804 (and (org-called-interactively-p 'any)
9805 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9806 (and (eq org-id-link-to-org-use-id
9807 'create-if-interactive-and-no-custom-id)
9808 (not custom-id))))
9809 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9810 ;; Store a link using the ID at point
9811 (setq link (condition-case nil
9812 (prog1 (org-id-store-link)
9813 (setq desc (or (plist-get org-store-link-plist
9814 :description)
9815 "")))
9816 (error
9817 ;; Probably before first headline, link only to file
9818 (concat "file:"
9819 (abbreviate-file-name
9820 (buffer-file-name (buffer-base-buffer))))))))
9822 ;; Just link to current headline
9823 (setq cpltxt (concat "file:"
9824 (abbreviate-file-name
9825 (buffer-file-name (buffer-base-buffer)))))
9826 ;; Add a context search string
9827 (when (org-xor org-context-in-file-links arg)
9828 (let* ((ee (org-element-at-point))
9829 (et (org-element-type ee))
9830 (ev (plist-get (cadr ee) :value))
9831 (ek (plist-get (cadr ee) :key))
9832 (eok (and (stringp ek) (string-match "name" ek))))
9833 (setq txt (cond
9834 ((org-at-heading-p) nil)
9835 ((and (eq et 'keyword) eok) ev)
9836 ((org-region-active-p)
9837 (buffer-substring (region-beginning) (region-end)))))
9838 (when (or (null txt) (string-match "\\S-" txt))
9839 (setq cpltxt
9840 (concat cpltxt "::"
9841 (condition-case nil
9842 (org-make-org-heading-search-string txt)
9843 (error "")))
9844 desc (or (and (eq et 'keyword) eok ev)
9845 (nth 4 (ignore-errors (org-heading-components)))
9846 "NONE")))))
9847 (when (string-match "::\\'" cpltxt)
9848 (setq cpltxt (substring cpltxt 0 -2)))
9849 (setq link cpltxt))))
9851 ((buffer-file-name (buffer-base-buffer))
9852 ;; Just link to this file here.
9853 (setq cpltxt (concat "file:"
9854 (abbreviate-file-name
9855 (buffer-file-name (buffer-base-buffer)))))
9856 ;; Add a context string.
9857 (when (org-xor org-context-in-file-links arg)
9858 (setq txt (if (org-region-active-p)
9859 (buffer-substring (region-beginning) (region-end))
9860 (buffer-substring (point-at-bol) (point-at-eol))))
9861 ;; Only use search option if there is some text.
9862 (when (string-match "\\S-" txt)
9863 (setq cpltxt
9864 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9865 desc "NONE")))
9866 (setq link cpltxt))
9868 ((org-called-interactively-p 'interactive)
9869 (user-error "No method for storing a link from this buffer"))
9871 (t (setq link nil)))
9873 ;; We're done setting link and desc, clean up
9874 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9875 (setq link (or link cpltxt)
9876 desc (or desc cpltxt))
9877 (cond ((equal desc "NONE") (setq desc nil))
9878 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9879 (let ((d0 (match-string 3 desc))
9880 (p0 (match-string 5 desc)))
9881 (setq desc
9882 (replace-regexp-in-string
9883 org-bracket-link-regexp
9884 (concat (or p0 d0)
9885 (if (equal (length (match-string 0 desc))
9886 (length desc)) "*" "")) desc)))))
9888 ;; Return the link
9889 (if (not (and (or (org-called-interactively-p 'any)
9890 executing-kbd-macro)
9891 link))
9892 (or agenda-link (and link (org-make-link-string link desc)))
9893 (push (list link desc) org-stored-links)
9894 (message "Stored: %s" (or desc link))
9895 (when custom-id
9896 (setq link (concat "file:" (abbreviate-file-name
9897 (buffer-file-name)) "::#" custom-id))
9898 (push (list link desc) org-stored-links))
9899 (car org-stored-links))))))
9901 (defun org-store-link-props (&rest plist)
9902 "Store link properties, extract names, addresses and dates."
9903 (let ((x (plist-get plist :from)))
9904 (when x
9905 (let ((adr (mail-extract-address-components x)))
9906 (setq plist (plist-put plist :fromname (car adr)))
9907 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9908 (let ((x (plist-get plist :to)))
9909 (when x
9910 (let ((adr (mail-extract-address-components x)))
9911 (setq plist (plist-put plist :toname (car adr)))
9912 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9913 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9914 (when x
9915 (setq plist (plist-put plist :date-timestamp
9916 (format-time-string
9917 (org-time-stamp-format t) x)))
9918 (setq plist (plist-put plist :date-timestamp-inactive
9919 (format-time-string
9920 (org-time-stamp-format t t) x)))))
9921 (let ((from (plist-get plist :from))
9922 (to (plist-get plist :to)))
9923 (when (and from to org-from-is-user-regexp)
9924 (setq plist
9925 (plist-put plist :fromto
9926 (if (string-match org-from-is-user-regexp from)
9927 (concat "to %t")
9928 (concat "from %f"))))))
9929 (setq org-store-link-plist plist))
9931 (defun org-add-link-props (&rest plist)
9932 "Add these properties to the link property list."
9933 (let (key value)
9934 (while plist
9935 (setq key (pop plist) value (pop plist))
9936 (setq org-store-link-plist
9937 (plist-put org-store-link-plist key value)))))
9939 (defun org-email-link-description (&optional fmt)
9940 "Return the description part of an email link.
9941 This takes information from `org-store-link-plist' and formats it
9942 according to FMT (default from `org-email-link-description-format')."
9943 (setq fmt (or fmt org-email-link-description-format))
9944 (let* ((p org-store-link-plist)
9945 (to (plist-get p :toaddress))
9946 (from (plist-get p :fromaddress))
9947 (table
9948 (list
9949 (cons "%c" (plist-get p :fromto))
9950 (cons "%F" (plist-get p :from))
9951 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9952 (cons "%T" (plist-get p :to))
9953 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9954 (cons "%s" (plist-get p :subject))
9955 (cons "%d" (plist-get p :date))
9956 (cons "%m" (plist-get p :message-id)))))
9957 (when (string-match "%c" fmt)
9958 ;; Check if the user wrote this message
9959 (if (and org-from-is-user-regexp from to
9960 (save-match-data (string-match org-from-is-user-regexp from)))
9961 (setq fmt (replace-match "to %t" t t fmt))
9962 (setq fmt (replace-match "from %f" t t fmt))))
9963 (org-replace-escapes fmt table)))
9965 (defun org-make-org-heading-search-string (&optional string)
9966 "Make search string for the current headline or STRING."
9967 (let ((s (or string
9968 (and (derived-mode-p 'org-mode)
9969 (save-excursion
9970 (org-back-to-heading t)
9971 (org-element-property :raw-value (org-element-at-point))))))
9972 (lines org-context-in-file-links))
9973 (or string (setq s (concat "*" s))) ; Add * for headlines
9974 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9975 (when (and string (integerp lines) (> lines 0))
9976 (let ((slines (org-split-string s "\n")))
9977 (when (< lines (length slines))
9978 (setq s (mapconcat
9979 'identity
9980 (reverse (nthcdr (- (length slines) lines)
9981 (reverse slines))) "\n")))))
9982 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9984 (defun org-make-link-string (link &optional description)
9985 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9986 (unless (org-string-nw-p link) (error "Empty link"))
9987 (let ((uri (cond ((string-match org-link-types-re link)
9988 (concat (match-string 1 link)
9989 (org-link-escape (substring link (match-end 1)))))
9990 ;; For readability, url-encode internal links only
9991 ;; when absolutely needed (i.e, when they contain
9992 ;; square brackets). File links however, are
9993 ;; encoded since, e.g., spaces are significant.
9994 ((or (file-name-absolute-p link)
9995 (org-string-match-p "\\`\\.\\.?/\\|[][]" link))
9996 (org-link-escape link))
9997 (t link)))
9998 (description
9999 (and (org-string-nw-p description)
10000 ;; Remove brackets from description, as they are fatal.
10001 (replace-regexp-in-string
10002 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10003 (org-trim description)))))
10004 (format "[[%s]%s]"
10006 (if description (format "[%s]" description) ""))))
10008 (defconst org-link-escape-chars
10009 ;;%20 %5B %5D %25
10010 '(?\s ?\[ ?\] ?%)
10011 "List of characters that should be escaped in a link when stored to Org.
10012 This is the list that is used for internal purposes.")
10014 (defconst org-link-escape-chars-browser
10015 ;;%20 %22
10016 '(?\s ?\")
10017 "List of characters to be escaped before handing over to the browser.
10018 If you consider using this constant then you probably want to use
10019 the function `org-link-escape-browser' instead. See there why
10020 this constant is a candidate to be removed once Org drops support
10021 for Emacs 24.1 and 24.2.")
10023 (defun org-link-escape (text &optional table merge)
10024 "Return percent escaped representation of TEXT.
10025 TEXT is a string with the text to escape.
10026 Optional argument TABLE is a list with characters that should be
10027 escaped. When nil, `org-link-escape-chars' is used.
10028 If optional argument MERGE is set, merge TABLE into
10029 `org-link-escape-chars'."
10030 (let ((characters-to-encode
10031 (cond ((null table) org-link-escape-chars)
10032 (merge (append org-link-escape-chars table))
10033 (t table))))
10034 (mapconcat
10035 (lambda (c)
10036 (if (or (memq c characters-to-encode)
10037 (and org-url-hexify-p (or (< c 32) (> c 126))))
10038 (mapconcat (lambda (e) (format "%%%.2X" e))
10039 (or (encode-coding-char c 'utf-8)
10040 (error "Unable to percent escape character: %c" c))
10042 (char-to-string c)))
10043 text "")))
10045 (defun org-link-escape-browser (text)
10046 "Escape some characters before handing over to the browser.
10047 This function is a candidate to be removed together with the
10048 constant `org-link-escape-chars-browser' once Org drops support
10049 for Emacs 24.1 and 24.2. All calls to this function will have to
10050 be replaced with `url-encode-url' which is available since Emacs
10051 24.3.1."
10052 ;; Example with the Org link
10053 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10054 ;; to open the browser with +subject:"Release 8.2" filled into the
10055 ;; query field: In this case the variable TEXT contains the
10056 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10057 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10058 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10059 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10060 (if (fboundp 'url-encode-url)
10061 (url-encode-url text)
10062 (if (org-string-match-p
10063 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10064 text)
10065 (org-link-escape text org-link-escape-chars-browser)
10066 text)))
10068 (defun org-link-unescape (str)
10069 "Unhex hexified Unicode parts in string STR.
10070 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10071 reciprocal of `org-link-escape', which see."
10072 (if (org-string-nw-p str)
10073 (replace-regexp-in-string
10074 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10075 str))
10077 (defun org-link-unescape-compound (hex)
10078 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10079 Note: this function also decodes single byte encodings like
10080 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10081 (save-match-data
10082 (let* ((bytes (cdr (split-string hex "%")))
10083 (ret "")
10084 (eat 0)
10085 (sum 0))
10086 (while bytes
10087 (let* ((val (string-to-number (pop bytes) 16))
10088 (shift-xor
10089 (if (= 0 eat)
10090 (cond
10091 ((>= val 252) (cons 6 252))
10092 ((>= val 248) (cons 5 248))
10093 ((>= val 240) (cons 4 240))
10094 ((>= val 224) (cons 3 224))
10095 ((>= val 192) (cons 2 192))
10096 (t (cons 0 0)))
10097 (cons 6 128))))
10098 (when (>= val 192) (setq eat (car shift-xor)))
10099 (setq val (logxor val (cdr shift-xor)))
10100 (setq sum (+ (lsh sum (car shift-xor)) val))
10101 (when (> eat 0) (setq eat (- eat 1)))
10102 (cond
10103 ((= 0 eat) ;multi byte
10104 (setq ret (concat ret (org-char-to-string sum)))
10105 (setq sum 0))
10106 ((not bytes) ; single byte(s)
10107 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10108 ret)))
10110 (defun org-link-unescape-single-byte-sequence (hex)
10111 "Unhexify hex-encoded single byte character sequences."
10112 (mapconcat (lambda (byte)
10113 (char-to-string (string-to-number byte 16)))
10114 (cdr (split-string hex "%")) ""))
10116 (defun org-xor (a b)
10117 "Exclusive or."
10118 (if a (not b) b))
10120 (defun org-fixup-message-id-for-http (s)
10121 "Replace special characters in a message id, so it can be used in an http query."
10122 (when (string-match "%" s)
10123 (setq s (mapconcat (lambda (c)
10124 (if (eq c ?%)
10125 "%25"
10126 (char-to-string c)))
10127 s "")))
10128 (while (string-match "<" s)
10129 (setq s (replace-match "%3C" t t s)))
10130 (while (string-match ">" s)
10131 (setq s (replace-match "%3E" t t s)))
10132 (while (string-match "@" s)
10133 (setq s (replace-match "%40" t t s)))
10136 (defun org-link-prettify (link)
10137 "Return a human-readable representation of LINK.
10138 The car of LINK must be a raw link.
10139 The cdr of LINK must be either a link description or nil."
10140 (let ((desc (or (cadr link) "<no description>")))
10141 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10142 "<" (car link) ">")))
10144 ;;;###autoload
10145 (defun org-insert-link-global ()
10146 "Insert a link like Org-mode does.
10147 This command can be called in any mode to insert a link in Org-mode syntax."
10148 (interactive)
10149 (org-load-modules-maybe)
10150 (org-run-like-in-org-mode 'org-insert-link))
10152 (defun org-insert-all-links (arg &optional pre post)
10153 "Insert all links in `org-stored-links'.
10154 When a universal prefix, do not delete the links from `org-stored-links'.
10155 When `ARG' is a number, insert the last N link(s).
10156 `PRE' and `POST' are optional arguments to define a string to
10157 prepend or to append."
10158 (interactive "P")
10159 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10160 (links (copy-sequence org-stored-links))
10161 (pr (or pre "- "))
10162 (po (or post "\n"))
10163 (cnt 1) l)
10164 (if (null org-stored-links)
10165 (message "No link to insert")
10166 (while (and (or (listp arg) (>= arg cnt))
10167 (setq l (if (listp arg)
10168 (pop links)
10169 (pop org-stored-links))))
10170 (setq cnt (1+ cnt))
10171 (insert pr)
10172 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10173 (insert po)))))
10175 (defun org-insert-last-stored-link (arg)
10176 "Insert the last link stored in `org-stored-links'."
10177 (interactive "p")
10178 (org-insert-all-links arg "" "\n"))
10180 (defun org-link-fontify-links-to-this-file ()
10181 "Fontify links to the current file in `org-stored-links'."
10182 (let ((f (buffer-file-name)) a b)
10183 (setq a (mapcar (lambda(l)
10184 (let ((ll (car l)))
10185 (when (and (string-match "^file:\\(.+\\)::" ll)
10186 (equal f (expand-file-name (match-string 1 ll))))
10187 ll)))
10188 org-stored-links))
10189 (when (featurep 'org-id)
10190 (setq b (mapcar (lambda(l)
10191 (let ((ll (car l)))
10192 (when (and (string-match "^id:\\(.+\\)$" ll)
10193 (equal f (expand-file-name
10194 (or (org-id-find-id-file
10195 (match-string 1 ll)) ""))))
10196 ll)))
10197 org-stored-links)))
10198 (mapcar (lambda(l)
10199 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10200 (delq nil (append a b)))))
10202 (defvar org--links-history nil)
10203 (defun org-insert-link (&optional complete-file link-location default-description)
10204 "Insert a link. At the prompt, enter the link.
10206 Completion can be used to insert any of the link protocol prefixes like
10207 http or ftp in use.
10209 The history can be used to select a link previously stored with
10210 `org-store-link'. When the empty string is entered (i.e. if you just
10211 press RET at the prompt), the link defaults to the most recently
10212 stored link. As SPC triggers completion in the minibuffer, you need to
10213 use M-SPC or C-q SPC to force the insertion of a space character.
10215 You will also be prompted for a description, and if one is given, it will
10216 be displayed in the buffer instead of the link.
10218 If there is already a link at point, this command will allow you to edit link
10219 and description parts.
10221 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10222 be selected using completion. The path to the file will be relative to the
10223 current directory if the file is in the current directory or a subdirectory.
10224 Otherwise, the link will be the absolute path as completed in the minibuffer
10225 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10226 option `org-link-file-path-type'.
10228 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10229 the current directory or below.
10231 With three \\[universal-argument] prefixes, negate the meaning of
10232 `org-keep-stored-link-after-insertion'.
10234 If `org-make-link-description-function' is non-nil, this function will be
10235 called with the link target, and the result will be the default
10236 link description.
10238 If the LINK-LOCATION parameter is non-nil, this value will be
10239 used as the link location instead of reading one interactively.
10241 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10242 be used as the default description."
10243 (interactive "P")
10244 (let* ((wcf (current-window-configuration))
10245 (origbuf (current-buffer))
10246 (region (when (org-region-active-p)
10247 (buffer-substring (region-beginning) (region-end))))
10248 (remove (and region (list (region-beginning) (region-end))))
10249 (desc region)
10250 (link link-location)
10251 (abbrevs org-link-abbrev-alist-local)
10252 entry all-prefixes auto-desc)
10253 (cond
10254 (link-location) ; specified by arg, just use it.
10255 ((org-in-regexp org-bracket-link-regexp 1)
10256 ;; We do have a link at point, and we are going to edit it.
10257 (setq remove (list (match-beginning 0) (match-end 0)))
10258 (setq desc (when (match-end 3) (org-match-string-no-properties 3)))
10259 (setq link (read-string "Link: "
10260 (org-link-unescape
10261 (org-match-string-no-properties 1)))))
10262 ((or (org-in-regexp org-angle-link-re)
10263 (org-in-regexp org-plain-link-re))
10264 ;; Convert to bracket link
10265 (setq remove (list (match-beginning 0) (match-end 0))
10266 link (read-string "Link: "
10267 (org-remove-angle-brackets (match-string 0)))))
10268 ((member complete-file '((4) (16)))
10269 ;; Completing read for file names.
10270 (setq link (org-file-complete-link complete-file)))
10272 ;; Read link, with completion for stored links.
10273 (org-link-fontify-links-to-this-file)
10274 (org-switch-to-buffer-other-window "*Org Links*")
10275 (with-current-buffer "*Org Links*"
10276 (erase-buffer)
10277 (insert "Insert a link.
10278 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10279 (when org-stored-links
10280 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10281 (insert (mapconcat 'org-link-prettify
10282 (reverse org-stored-links) "\n")))
10283 (goto-char (point-min)))
10284 (let ((cw (selected-window)))
10285 (select-window (get-buffer-window "*Org Links*" 'visible))
10286 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10287 (unless (pos-visible-in-window-p (point-max))
10288 (org-fit-window-to-buffer))
10289 (and (window-live-p cw) (select-window cw)))
10290 (setq all-prefixes (append (mapcar 'car abbrevs)
10291 (mapcar 'car org-link-abbrev-alist)
10292 org-link-types))
10293 (unwind-protect
10294 ;; Fake a link history, containing the stored links.
10295 (let ((org--links-history
10296 (append (mapcar #'car org-stored-links)
10297 org-insert-link-history)))
10298 (setq link
10299 (org-completing-read
10300 "Link: "
10301 (append
10302 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10303 (mapcar #'car org-stored-links))
10304 nil nil nil
10305 'org--links-history
10306 (caar org-stored-links)))
10307 (unless (org-string-nw-p link) (user-error "No link selected"))
10308 (dolist (l org-stored-links)
10309 (when (equal link (cadr l))
10310 (setq link (car l))
10311 (setq auto-desc t)))
10312 (when (or (member link all-prefixes)
10313 (and (equal ":" (substring link -1))
10314 (member (substring link 0 -1) all-prefixes)
10315 (setq link (substring link 0 -1))))
10316 (setq link (with-current-buffer origbuf
10317 (org-link-try-special-completion link)))))
10318 (set-window-configuration wcf)
10319 (kill-buffer "*Org Links*"))
10320 (setq entry (assoc link org-stored-links))
10321 (or entry (push link org-insert-link-history))
10322 (setq desc (or desc (nth 1 entry)))))
10324 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10325 (not org-keep-stored-link-after-insertion))
10326 (setq org-stored-links (delq (assoc link org-stored-links)
10327 org-stored-links)))
10329 (when (and (string-match org-plain-link-re link)
10330 (not (string-match org-ts-regexp link)))
10331 ;; URL-like link, normalize the use of angular brackets.
10332 (setq link (org-remove-angle-brackets link)))
10334 ;; Check if we are linking to the current file with a search
10335 ;; option If yes, simplify the link by using only the search
10336 ;; option.
10337 (when (and buffer-file-name
10338 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10339 (let* ((path (match-string 1 link))
10340 (case-fold-search nil)
10341 (search (match-string 2 link)))
10342 (save-match-data
10343 (when (equal (file-truename buffer-file-name) (file-truename path))
10344 ;; We are linking to this same file, with a search option
10345 (setq link search)))))
10347 ;; Check if we can/should use a relative path. If yes, simplify the link
10348 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10349 (let* ((type (match-string 1 link))
10350 (path (match-string 2 link))
10351 (origpath path)
10352 (case-fold-search nil))
10353 (cond
10354 ((or (eq org-link-file-path-type 'absolute)
10355 (equal complete-file '(16)))
10356 (setq path (abbreviate-file-name (expand-file-name path))))
10357 ((eq org-link-file-path-type 'noabbrev)
10358 (setq path (expand-file-name path)))
10359 ((eq org-link-file-path-type 'relative)
10360 (setq path (file-relative-name path)))
10362 (save-match-data
10363 (if (string-match (concat "^" (regexp-quote
10364 (expand-file-name
10365 (file-name-as-directory
10366 default-directory))))
10367 (expand-file-name path))
10368 ;; We are linking a file with relative path name.
10369 (setq path (substring (expand-file-name path)
10370 (match-end 0)))
10371 (setq path (abbreviate-file-name (expand-file-name path)))))))
10372 (setq link (concat type path))
10373 (when (equal desc origpath)
10374 (setq desc path))))
10376 (if org-make-link-description-function
10377 (setq desc
10378 (or (condition-case nil
10379 (funcall org-make-link-description-function link desc)
10380 (error (progn (message "Can't get link description from `%s'"
10381 (symbol-name org-make-link-description-function))
10382 (sit-for 2) nil)))
10383 (read-string "Description: " default-description)))
10384 (if default-description (setq desc default-description)
10385 (setq desc (or (and auto-desc desc)
10386 (read-string "Description: " desc)))))
10388 (unless (string-match "\\S-" desc) (setq desc nil))
10389 (when remove (apply 'delete-region remove))
10390 (insert (org-make-link-string link desc))
10391 ;; Redisplay so as the new link has proper invisible characters.
10392 (sit-for 0)))
10394 (defun org-link-try-special-completion (type)
10395 "If there is completion support for link type TYPE, offer it."
10396 (let ((fun (intern (concat "org-" type "-complete-link"))))
10397 (if (functionp fun)
10398 (funcall fun)
10399 (read-string "Link (no completion support): " (concat type ":")))))
10401 (defun org-file-complete-link (&optional arg)
10402 "Create a file link using completion."
10403 (let ((file (org-iread-file-name "File: "))
10404 (pwd (file-name-as-directory (expand-file-name ".")))
10405 (pwd1 (file-name-as-directory (abbreviate-file-name
10406 (expand-file-name ".")))))
10407 (cond ((equal arg '(16))
10408 (concat "file:"
10409 (abbreviate-file-name (expand-file-name file))))
10410 ((string-match
10411 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10412 (concat "file:" (match-string 1 file)))
10413 ((string-match
10414 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10415 (expand-file-name file))
10416 (concat "file:"
10417 (match-string 1 (expand-file-name file))))
10418 (t (concat "file:" file)))))
10420 (defvar ido-enter-matching-directory)
10421 (defun org-iread-file-name (&rest args)
10422 "Read-file-name using `ido-mode' speedup if available.
10423 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10424 See `read-file-name' for a description of parameters."
10425 (org-without-partial-completion
10426 (if (and org-completion-use-ido
10427 (fboundp 'ido-read-file-name)
10428 (org-bound-and-true-p ido-mode)
10429 (listp (nth 1 args)))
10430 (let ((ido-enter-matching-directory nil))
10431 (apply #'ido-read-file-name args))
10432 (apply #'read-file-name args))))
10434 (defun org-completing-read (&rest args)
10435 "Completing-read with SPACE being a normal character."
10436 (let ((enable-recursive-minibuffers t)
10437 (minibuffer-local-completion-map
10438 (copy-keymap minibuffer-local-completion-map)))
10439 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10440 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10441 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10442 'org-time-stamp-inactive)
10443 (apply #'completing-read args)))
10445 (define-obsolete-function-alias
10446 'org-completing-read-no-i 'completing-read "Org 9.0")
10447 (define-obsolete-function-alias
10448 'org-icompleting-read 'completing-read "Org 9.0")
10450 ;;; Opening/following a link
10452 (defvar org-link-search-failed nil)
10454 (defvar org-open-link-functions nil
10455 "Hook for functions finding a plain text link.
10456 These functions must take a single argument, the link content.
10457 They will be called for links that look like [[link text][description]]
10458 when LINK TEXT does not have a protocol like \"http:\" and does not look
10459 like a filename (e.g. \"./blue.png\").
10461 These functions will be called *before* Org attempts to resolve the
10462 link by doing text searches in the current buffer - so if you want a
10463 link \"[[target]]\" to still find \"<<target>>\", your function should
10464 handle this as a special case.
10466 When the function does handle the link, it must return a non-nil value.
10467 If it decides that it is not responsible for this link, it must return
10468 nil to indicate that that Org-mode can continue with other options
10469 like exact and fuzzy text search.")
10471 (defun org-next-link (&optional search-backward)
10472 "Move forward to the next link.
10473 If the link is in hidden text, expose it."
10474 (interactive "P")
10475 (when (and org-link-search-failed (eq this-command last-command))
10476 (goto-char (point-min))
10477 (message "Link search wrapped back to beginning of buffer"))
10478 (setq org-link-search-failed nil)
10479 (let* ((pos (point))
10480 (ct (org-context))
10481 (a (assoc :link ct))
10482 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10483 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10484 ((looking-at org-any-link-re)
10485 ;; Don't stay stuck at link without an org-link face
10486 (forward-char (if search-backward -1 1))))
10487 (if (funcall srch-fun org-any-link-re nil t)
10488 (progn
10489 (goto-char (match-beginning 0))
10490 (when (outline-invisible-p) (org-show-context)))
10491 (goto-char pos)
10492 (setq org-link-search-failed t)
10493 (message "No further link found"))))
10495 (defun org-previous-link ()
10496 "Move backward to the previous link.
10497 If the link is in hidden text, expose it."
10498 (interactive)
10499 (funcall 'org-next-link t))
10501 (defun org-translate-link (s)
10502 "Translate a link string if a translation function has been defined."
10503 (with-temp-buffer
10504 (insert (org-trim s))
10505 (org-trim (org-element-interpret-data (org-element-context)))))
10507 (defun org-translate-link-from-planner (type path)
10508 "Translate a link from Emacs Planner syntax so that Org can follow it.
10509 This is still an experimental function, your mileage may vary."
10510 (cond
10511 ((member type '("http" "https" "news" "ftp"))
10512 ;; standard Internet links are the same.
10513 nil)
10514 ((and (equal type "irc") (string-match "^//" path))
10515 ;; Planner has two / at the beginning of an irc link, we have 1.
10516 ;; We should have zero, actually....
10517 (setq path (substring path 1)))
10518 ((and (equal type "lisp") (string-match "^/" path))
10519 ;; Planner has a slash, we do not.
10520 (setq type "elisp" path (substring path 1)))
10521 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10522 ;; A typical message link. Planner has the id after the final slash,
10523 ;; we separate it with a hash mark
10524 (setq path (concat (match-string 1 path) "#"
10525 (org-remove-angle-brackets (match-string 2 path))))))
10526 (cons type path))
10528 (defun org-find-file-at-mouse (ev)
10529 "Open file link or URL at mouse."
10530 (interactive "e")
10531 (mouse-set-point ev)
10532 (org-open-at-point 'in-emacs))
10534 (defun org-open-at-mouse (ev)
10535 "Open file link or URL at mouse.
10536 See the docstring of `org-open-file' for details."
10537 (interactive "e")
10538 (mouse-set-point ev)
10539 (when (eq major-mode 'org-agenda-mode)
10540 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10541 (org-open-at-point))
10543 (defvar org-window-config-before-follow-link nil
10544 "The window configuration before following a link.
10545 This is saved in case the need arises to restore it.")
10547 ;;;###autoload
10548 (defun org-open-at-point-global ()
10549 "Follow a link like Org-mode does.
10550 This command can be called in any mode to follow a link that has
10551 Org-mode syntax."
10552 (interactive)
10553 (org-run-like-in-org-mode 'org-open-at-point))
10555 ;;;###autoload
10556 (defun org-open-link-from-string (s &optional arg reference-buffer)
10557 "Open a link in the string S, as if it was in Org-mode."
10558 (interactive "sLink: \nP")
10559 (let ((reference-buffer (or reference-buffer (current-buffer))))
10560 (with-temp-buffer
10561 (let ((org-inhibit-startup (not reference-buffer)))
10562 (org-mode)
10563 (insert s)
10564 (goto-char (point-min))
10565 (when reference-buffer
10566 (setq org-link-abbrev-alist-local
10567 (with-current-buffer reference-buffer
10568 org-link-abbrev-alist-local)))
10569 (org-open-at-point arg reference-buffer)))))
10571 (defvar org-open-at-point-functions nil
10572 "Hook that is run when following a link at point.
10574 Functions in this hook must return t if they identify and follow
10575 a link at point. If they don't find anything interesting at point,
10576 they must return nil.")
10578 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10579 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10580 (defun org-open-at-point (&optional arg reference-buffer)
10581 "Open link, timestamp, footnote or tags at point.
10583 When point is on a link, follow it. Normally, files will be
10584 opened by an appropriate application. If the optional prefix
10585 argument ARG is non-nil, Emacs will visit the file. With
10586 a double prefix argument, try to open outside of Emacs, in the
10587 application the system uses for this file type.
10589 When point is on a timestamp, open the agenda at the day
10590 specified.
10592 When point is a footnote definition, move to the first reference
10593 found. If it is on a reference, move to the associated
10594 definition.
10596 When point is on a headline, display a list of every link in the
10597 entry, so it is possible to pick one, or all, of them. If point
10598 is on a tag, call `org-tags-view' instead.
10600 When optional argument REFERENCE-BUFFER is non-nil, it should
10601 specify a buffer from where the link search should happen. This
10602 is used internally by `org-open-link-from-string'.
10604 On top of syntactically correct links, this function will open
10605 the link at point in comments or comment blocks and the first
10606 link in a property drawer line."
10607 (interactive "P")
10608 ;; On a code block, open block's results.
10609 (unless (call-interactively 'org-babel-open-src-block-result)
10610 (org-load-modules-maybe)
10611 (setq org-window-config-before-follow-link (current-window-configuration))
10612 (org-remove-occur-highlights nil nil t)
10613 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10614 (let* ((context
10615 ;; Only consider supported types, even if they are not
10616 ;; the closest one.
10617 (org-element-lineage
10618 (org-element-context)
10619 '(clock comment comment-block footnote-definition
10620 footnote-reference headline inlinetask keyword link
10621 node-property timestamp)
10623 (type (org-element-type context))
10624 (value (org-element-property :value context)))
10625 (cond
10626 ((not context) (user-error "No link found"))
10627 ;; Exception: open timestamps and links in properties
10628 ;; drawers, keywords and comments.
10629 ((memq type '(comment comment-block keyword node-property))
10630 (cond ((org-in-regexp org-any-link-re)
10631 (org-open-link-from-string (match-string-no-properties 0)))
10632 ((or (org-in-regexp org-ts-regexp-both nil t)
10633 (org-in-regexp org-tsr-regexp-both nil t))
10634 (org-follow-timestamp-link))
10635 (t (user-error "No link found"))))
10636 ;; On a headline or an inlinetask, but not on a timestamp,
10637 ;; a link, a footnote reference or on tags.
10638 ((and (memq type '(headline inlinetask))
10639 ;; Not on tags.
10640 (progn (save-excursion (beginning-of-line)
10641 (looking-at org-complex-heading-regexp))
10642 (or (not (match-beginning 5))
10643 (< (point) (match-beginning 5)))))
10644 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10645 (links (car data))
10646 (links-end (cdr data)))
10647 (if links
10648 (dolist (link (if (stringp links) (list links) links))
10649 (search-forward link nil links-end)
10650 (goto-char (match-beginning 0))
10651 (org-open-at-point))
10652 (require 'org-attach)
10653 (org-attach-reveal 'if-exists))))
10654 ;; On a clock line, make sure point is on the timestamp
10655 ;; before opening it.
10656 ((and (eq type 'clock)
10657 value
10658 (>= (point) (org-element-property :begin value))
10659 (<= (point) (org-element-property :end value)))
10660 (org-follow-timestamp-link))
10661 ;; Do nothing on white spaces after an object.
10662 ((>= (point)
10663 (save-excursion
10664 (goto-char (org-element-property :end context))
10665 (skip-chars-backward " \t")
10666 (point)))
10667 (user-error "No link found"))
10668 ((eq type 'timestamp) (org-follow-timestamp-link))
10669 ;; On tags within a headline or an inlinetask.
10670 ((and (memq type '(headline inlinetask))
10671 (progn (save-excursion (beginning-of-line)
10672 (looking-at org-complex-heading-regexp))
10673 (and (match-beginning 5)
10674 (>= (point) (match-beginning 5)))))
10675 (org-tags-view arg (substring (match-string 5) 0 -1)))
10676 ((eq type 'link)
10677 ;; When link is located within the description of another
10678 ;; link (e.g., an inline image), always open the parent
10679 ;; link.
10680 (let*((link (let ((up (org-element-property :parent context)))
10681 (if (eq (org-element-type up) 'link) up context)))
10682 (type (org-element-property :type link))
10683 (path (org-link-unescape (org-element-property :path link))))
10684 ;; Switch back to REFERENCE-BUFFER needed when called in
10685 ;; a temporary buffer through `org-open-link-from-string'.
10686 (with-current-buffer (or reference-buffer (current-buffer))
10687 (cond
10688 ((equal type "file")
10689 (if (string-match "[*?{]" (file-name-nondirectory path))
10690 (dired path)
10691 ;; Look into `org-link-protocols' in order to find
10692 ;; a DEDICATED-FUNCTION to open file. The function
10693 ;; will be applied on raw link instead of parsed
10694 ;; link due to the limitation in `org-add-link-type'
10695 ;; ("open" function called with a single argument).
10696 ;; If no such function is found, fallback to
10697 ;; `org-open-file'.
10699 ;; Note : "file+emacs" and "file+sys" types are
10700 ;; hard-coded in order to escape the previous
10701 ;; limitation.
10702 (let* ((option (org-element-property :search-option link))
10703 (app (org-element-property :application link))
10704 (dedicated-function
10705 (nth 1 (assoc app org-link-protocols))))
10706 (if dedicated-function
10707 (funcall dedicated-function
10708 (concat path
10709 (and option (concat "::" option))))
10710 (apply #'org-open-file
10711 path
10712 (cond (arg)
10713 ((equal app "emacs") 'emacs)
10714 ((equal app "sys") 'system))
10715 (cond ((not option) nil)
10716 ((org-string-match-p "\\`[0-9]+\\'" option)
10717 (list (string-to-number option)))
10718 (t (list nil
10719 (org-link-unescape option)))))))))
10720 ((assoc type org-link-protocols)
10721 (funcall (nth 1 (assoc type org-link-protocols)) path))
10722 ((equal type "help")
10723 (let ((f-or-v (intern path)))
10724 (cond ((fboundp f-or-v) (describe-function f-or-v))
10725 ((boundp f-or-v) (describe-variable f-or-v))
10726 (t (error "Not a known function or variable")))))
10727 ((member type '("http" "https" "ftp" "mailto" "news"))
10728 (browse-url (org-link-escape-browser (concat type ":" path))))
10729 ((equal type "doi")
10730 (browse-url
10731 (org-link-escape-browser (concat org-doi-server-url path))))
10732 ((equal type "message") (browse-url (concat type ":" path)))
10733 ((equal type "shell")
10734 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10735 (cmd path))
10736 (if (or (and (org-string-nw-p
10737 org-confirm-shell-link-not-regexp)
10738 (string-match
10739 org-confirm-shell-link-not-regexp cmd))
10740 (not org-confirm-shell-link-function)
10741 (funcall org-confirm-shell-link-function
10742 (format "Execute \"%s\" in shell? "
10743 (org-add-props cmd nil
10744 'face 'org-warning))))
10745 (progn
10746 (message "Executing %s" cmd)
10747 (shell-command cmd buf)
10748 (when (featurep 'midnight)
10749 (setq clean-buffer-list-kill-buffer-names
10750 (cons (buffer-name buf)
10751 clean-buffer-list-kill-buffer-names))))
10752 (user-error "Abort"))))
10753 ((equal type "elisp")
10754 (let ((cmd path))
10755 (if (or (and (org-string-nw-p
10756 org-confirm-elisp-link-not-regexp)
10757 (org-string-match-p
10758 org-confirm-elisp-link-not-regexp cmd))
10759 (not org-confirm-elisp-link-function)
10760 (funcall org-confirm-elisp-link-function
10761 (format "Execute \"%s\" as elisp? "
10762 (org-add-props cmd nil
10763 'face 'org-warning))))
10764 (message "%s => %s" cmd
10765 (if (eq (string-to-char cmd) ?\()
10766 (eval (read cmd))
10767 (call-interactively (read cmd))))
10768 (user-error "Abort"))))
10769 ((equal type "id")
10770 (require 'org-id)
10771 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10772 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10773 (unless (run-hook-with-args-until-success
10774 'org-open-link-functions path)
10775 (if (not arg) (org-mark-ring-push)
10776 (switch-to-buffer-other-window
10777 (org-get-buffer-for-internal-link (current-buffer))))
10778 (let ((destination
10779 (org-with-wide-buffer
10780 (if (equal type "radio")
10781 (org-search-radio-target
10782 (org-element-property :path link))
10783 (org-link-search
10784 (if (member type '("custom-id" "coderef"))
10785 (org-element-property :raw-link link)
10786 path)
10787 ;; Prevent fuzzy links from matching
10788 ;; themselves.
10789 (and (equal type "fuzzy")
10790 (+ 2 (org-element-property :begin link)))))
10791 (point))))
10792 (unless (and (<= (point-min) destination)
10793 (>= (point-max) destination))
10794 (widen))
10795 (goto-char destination))))
10796 (t (browse-url-at-point))))))
10797 ;; On a footnote reference or at a footnote definition's label.
10798 ((or (eq type 'footnote-reference)
10799 (and (eq type 'footnote-definition)
10800 (save-excursion
10801 ;; Do not validate action when point is on the
10802 ;; spaces right after the footnote label, in
10803 ;; order to be on par with behaviour on links.
10804 (skip-chars-forward " \t")
10805 (let ((begin
10806 (org-element-property :contents-begin context)))
10807 (if begin (< (point) begin)
10808 (= (org-element-property :post-affiliated context)
10809 (line-beginning-position)))))))
10810 (org-footnote-action))
10811 (t (user-error "No link found")))))
10812 (run-hook-with-args 'org-follow-link-hook)))
10814 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10815 "Offer links in the current entry and return the selected link.
10816 If there is only one link, return it.
10817 If NTH is an integer, return the NTH link found.
10818 If ZERO is a string, check also this string for a link, and if
10819 there is one, return it."
10820 (with-current-buffer buffer
10821 (save-excursion
10822 (save-restriction
10823 (widen)
10824 (goto-char marker)
10825 (let ((cnt ?0)
10826 have-zero end links link c)
10827 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10828 (push (match-string 0 zero) links)
10829 (setq cnt (1- cnt) have-zero t))
10830 (save-excursion
10831 (org-back-to-heading t)
10832 (setq end (save-excursion (outline-next-heading) (point)))
10833 (while (re-search-forward org-any-link-re end t)
10834 (push (match-string 0) links))
10835 (setq links (org-uniquify (reverse links))))
10836 (cond
10837 ((null links)
10838 (message "No links"))
10839 ((equal (length links) 1)
10840 (setq link (car links)))
10841 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10842 (setq link (nth (if have-zero nth (1- nth)) links)))
10843 (t ; we have to select a link
10844 (save-excursion
10845 (save-window-excursion
10846 (delete-other-windows)
10847 (with-output-to-temp-buffer "*Select Link*"
10848 (dolist (l links)
10849 (cond
10850 ((not (string-match org-bracket-link-regexp l))
10851 (princ (format "[%c] %s\n" (cl-incf cnt)
10852 (org-remove-angle-brackets l))))
10853 ((match-end 3)
10854 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10855 (match-string 3 l) (match-string 1 l))))
10856 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10857 (match-string 1 l)))))))
10858 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10859 (message "Select link to open, RET to open all:")
10860 (setq c (read-char-exclusive))
10861 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10862 (when (equal c ?q) (user-error "Abort"))
10863 (if (equal c ?\C-m)
10864 (setq link links)
10865 (setq nth (- c ?0))
10866 (when have-zero (setq nth (1+ nth)))
10867 (unless (and (integerp nth) (>= (length links) nth))
10868 (user-error "Invalid link selection"))
10869 (setq link (nth (1- nth) links)))))
10870 (cons link end))))))
10872 ;; TODO: These functions are deprecated since `org-open-at-point'
10873 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10874 (defun org-open-file-with-system (path)
10875 "Open file at PATH using the system way of opening it."
10876 (org-open-file path 'system))
10877 (defun org-open-file-with-emacs (path)
10878 "Open file at PATH in Emacs."
10879 (org-open-file path 'emacs))
10882 ;;; File search
10884 (defvar org-create-file-search-functions nil
10885 "List of functions to construct the right search string for a file link.
10886 These functions are called in turn with point at the location to
10887 which the link should point.
10889 A function in the hook should first test if it would like to
10890 handle this file type, for example by checking the `major-mode'
10891 or the file extension. If it decides not to handle this file, it
10892 should just return nil to give other functions a chance. If it
10893 does handle the file, it must return the search string to be used
10894 when following the link. The search string will be part of the
10895 file link, given after a double colon, and `org-open-at-point'
10896 will automatically search for it. If special measures must be
10897 taken to make the search successful, another function should be
10898 added to the companion hook `org-execute-file-search-functions',
10899 which see.
10901 A function in this hook may also use `setq' to set the variable
10902 `description' to provide a suggestion for the descriptive text to
10903 be used for this link when it gets inserted into an Org-mode
10904 buffer with \\[org-insert-link].")
10906 (defvar org-execute-file-search-functions nil
10907 "List of functions to execute a file search triggered by a link.
10909 Functions added to this hook must accept a single argument, the
10910 search string that was part of the file link, the part after the
10911 double colon. The function must first check if it would like to
10912 handle this search, for example by checking the `major-mode' or
10913 the file extension. If it decides not to handle this search, it
10914 should just return nil to give other functions a chance. If it
10915 does handle the search, it must return a non-nil value to keep
10916 other functions from trying.
10918 Each function can access the current prefix argument through the
10919 variable `current-prefix-arg'. Note that a single prefix is used
10920 to force opening a link in Emacs, so it may be good to only use a
10921 numeric or double prefix to guide the search function.
10923 In case this is needed, a function in this hook can also restore
10924 the window configuration before `org-open-at-point' was called using:
10926 \(set-window-configuration org-window-config-before-follow-link)")
10928 (defun org-search-radio-target (target)
10929 "Search a radio target matching TARGET in current buffer.
10930 White spaces are not significant."
10931 (let ((re (format "<<<%s>>>"
10932 (mapconcat #'regexp-quote
10933 (org-split-string target "[ \t\n]+")
10934 "[ \t]+\\(?:\n[ \t]*\\)?")))
10935 (origin (point)))
10936 (goto-char (point-min))
10937 (catch :radio-match
10938 (while (re-search-forward re nil t)
10939 (backward-char)
10940 (let ((object (org-element-context)))
10941 (when (eq (org-element-type object) 'radio-target)
10942 (goto-char (org-element-property :begin object))
10943 (org-show-context 'link-search)
10944 (throw :radio-match nil))))
10945 (goto-char origin)
10946 (user-error "No match for radio target: %s" target))))
10948 (defun org-link-search (s &optional avoid-pos stealth)
10949 "Search for a search string S.
10951 If S starts with \"#\", it triggers a custom ID search.
10953 If S is enclosed within parenthesis, it initiates a coderef
10954 search.
10956 If S is surrounded by forward slashes, it is interpreted as
10957 a regular expression. In Org mode files, this will create an
10958 `org-occur' sparse tree. In ordinary files, `occur' will be used
10959 to list matches. If the current buffer is in `dired-mode', grep
10960 will be used to search in all files.
10962 When AVOID-POS is given, ignore matches near that position.
10964 When optional argument STEALTH is non-nil, do not modify
10965 visibility around point, thus ignoring `org-show-context-detail'
10966 variable.
10968 Search is case-insensitive and ignores white spaces. Return type
10969 of matched result, with is either `dedicated' or `fuzzy'."
10970 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10971 (let* ((case-fold-search t)
10972 (origin (point))
10973 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10974 (words (org-split-string s "[ \t\n]+"))
10975 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
10976 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10977 type)
10978 (cond
10979 ;; Check if there are any special search functions.
10980 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10981 ((eq (string-to-char s) ?#)
10982 ;; Look for a custom ID S if S starts with "#".
10983 (let* ((id (substring normalized 1))
10984 (match (org-find-property "CUSTOM_ID" id)))
10985 (if match (progn (goto-char match) (setf type 'dedicated))
10986 (error "No match for custom ID: %s" id))))
10987 ((string-match "\\`(\\(.*\\))\\'" normalized)
10988 ;; Look for coderef targets if S is enclosed within parenthesis.
10989 (let ((coderef (match-string-no-properties 1 normalized))
10990 (re (substring s-single-re 1 -1)))
10991 (goto-char (point-min))
10992 (catch :coderef-match
10993 (while (re-search-forward re nil t)
10994 (let ((element (org-element-at-point)))
10995 (when (and (memq (org-element-type element)
10996 '(example-block src-block))
10997 ;; Build proper regexp according to current
10998 ;; block's label format.
10999 (let ((label-fmt
11000 (regexp-quote
11001 (or (org-element-property :label-fmt element)
11002 org-coderef-label-format))))
11003 (save-excursion
11004 (beginning-of-line)
11005 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11006 (format label-fmt coderef))))))
11007 (setq type 'dedicated)
11008 (goto-char (match-beginning 1))
11009 (throw :coderef-match nil))))
11010 (goto-char origin)
11011 (error "No match for coderef: %s" coderef))))
11012 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11013 ;; Look for a regular expression.
11014 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11015 (match-string 1 s)))
11016 ;; Fuzzy links.
11018 (let ((starred (eq (string-to-char normalized) ?*)))
11019 (cond
11020 ;; Look for targets, only if not in a headline search.
11021 ((and (not starred)
11022 (let ((target (format "<<%s>>" s-multi-re)))
11023 (catch :target-match
11024 (goto-char (point-min))
11025 (while (re-search-forward target nil t)
11026 (backward-char)
11027 (let ((context (org-element-context)))
11028 (when (eq (org-element-type context) 'target)
11029 (setq type 'dedicated)
11030 (goto-char (org-element-property :begin context))
11031 (throw :target-match t))))
11032 nil))))
11033 ;; Look for elements named after S, only if not in a headline
11034 ;; search.
11035 ((and (not starred)
11036 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11037 (catch :name-match
11038 (goto-char (point-min))
11039 (while (re-search-forward name nil t)
11040 (let ((element (org-element-at-point)))
11041 (when (equal (org-split-string
11042 (org-element-property :name element)
11043 "[ \t]+")
11044 words)
11045 (setq type 'dedicated)
11046 (beginning-of-line)
11047 (throw :name-match t))))
11048 nil))))
11049 ;; Regular text search. Prefer headlines in Org mode
11050 ;; buffers.
11051 ((and (derived-mode-p 'org-mode)
11052 (let* ((wspace "[ \t]")
11053 (wspaceopt (concat wspace "*"))
11054 (cookie (concat "\\(?:"
11055 wspaceopt
11056 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11057 wspaceopt
11058 "\\)"))
11059 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11060 (re (concat
11061 org-outline-regexp-bol
11062 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11063 "\\(?:\\[#.\\][ \t]+\\)?"
11064 "\\(?:" org-comment-string "[ \t]+\\)?"
11065 sep "?"
11066 (let ((title (mapconcat #'regexp-quote
11067 words
11068 sep)))
11069 (if starred (substring title 1) title))
11070 sep "?"
11071 (org-re "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?")
11072 "[ \t]*$")))
11073 (goto-char (point-min))
11074 (re-search-forward re nil t)))
11075 (goto-char (match-beginning 0))
11076 (setq type 'dedicated))
11077 ;; Offer to create non-existent headline depending on
11078 ;; `org-link-search-must-match-exact-headline'.
11079 ((and (derived-mode-p 'org-mode)
11080 (not org-link-search-inhibit-query)
11081 (eq org-link-search-must-match-exact-headline 'query-to-create)
11082 (yes-or-no-p "No match - create this as a new heading? "))
11083 (goto-char (point-max))
11084 (unless (bolp) (newline))
11085 (org-insert-heading nil t t)
11086 (insert s "\n")
11087 (beginning-of-line 0))
11088 ;; Only headlines are looked after. No need to process
11089 ;; further: throw an error.
11090 ((and (derived-mode-p 'org-mode)
11091 (or starred org-link-search-must-match-exact-headline))
11092 (goto-char origin)
11093 (error "No match for fuzzy expression: %s" normalized))
11094 ;; Regular text search.
11095 ((catch :fuzzy-match
11096 (goto-char (point-min))
11097 (while (re-search-forward s-multi-re nil t)
11098 ;; Skip match if it contains AVOID-POS or it is included
11099 ;; in a link with a description but outside the
11100 ;; description.
11101 (unless (or (and avoid-pos
11102 (<= (match-beginning 0) avoid-pos)
11103 (> (match-end 0) avoid-pos))
11104 (and (save-match-data
11105 (org-in-regexp org-bracket-link-regexp))
11106 (match-beginning 3)
11107 (or (> (match-beginning 3) (point))
11108 (<= (match-end 3) (point)))
11109 (org-element-lineage
11110 (save-match-data (org-element-context))
11111 '(link) t)))
11112 (goto-char (match-beginning 0))
11113 (setq type 'fuzzy)
11114 (throw :fuzzy-match t)))
11115 nil))
11116 ;; All failed. Throw an error.
11117 (t (goto-char origin)
11118 (error "No match for fuzzy expression: %s" normalized))))))
11119 ;; Disclose surroundings of match, if appropriate.
11120 (when (and (derived-mode-p 'org-mode) (not stealth))
11121 (org-show-context 'link-search))
11122 type))
11124 (defun org-get-buffer-for-internal-link (buffer)
11125 "Return a buffer to be used for displaying the link target of internal links."
11126 (cond
11127 ((not org-display-internal-link-with-indirect-buffer)
11128 buffer)
11129 ((string-match "(Clone)$" (buffer-name buffer))
11130 (message "Buffer is already a clone, not making another one")
11131 ;; we also do not modify visibility in this case
11132 buffer)
11133 (t ; make a new indirect buffer for displaying the link
11134 (let* ((bn (buffer-name buffer))
11135 (ibn (concat bn "(Clone)"))
11136 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11137 (with-current-buffer ib (org-overview))
11138 ib))))
11140 (defun org-do-occur (regexp &optional cleanup)
11141 "Call the Emacs command `occur'.
11142 If CLEANUP is non-nil, remove the printout of the regular expression
11143 in the *Occur* buffer. This is useful if the regex is long and not useful
11144 to read."
11145 (occur regexp)
11146 (when cleanup
11147 (let ((cwin (selected-window)) win beg end)
11148 (when (setq win (get-buffer-window "*Occur*"))
11149 (select-window win))
11150 (goto-char (point-min))
11151 (when (re-search-forward "match[a-z]+" nil t)
11152 (setq beg (match-end 0))
11153 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11154 (setq end (1- (match-beginning 0)))))
11155 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11156 (goto-char (point-min))
11157 (select-window cwin))))
11159 ;;; The mark ring for links jumps
11161 (defvar org-mark-ring nil
11162 "Mark ring for positions before jumps in Org-mode.")
11163 (defvar org-mark-ring-last-goto nil
11164 "Last position in the mark ring used to go back.")
11165 ;; Fill and close the ring
11166 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11167 (dotimes (_ org-mark-ring-length)
11168 (push (make-marker) org-mark-ring))
11169 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11170 org-mark-ring)
11172 (defun org-mark-ring-push (&optional pos buffer)
11173 "Put the current position or POS into the mark ring and rotate it."
11174 (interactive)
11175 (setq pos (or pos (point)))
11176 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11177 (move-marker (car org-mark-ring)
11178 (or pos (point))
11179 (or buffer (current-buffer)))
11180 (message "%s"
11181 (substitute-command-keys
11182 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11184 (defun org-mark-ring-goto (&optional n)
11185 "Jump to the previous position in the mark ring.
11186 With prefix arg N, jump back that many stored positions. When
11187 called several times in succession, walk through the entire ring.
11188 Org-mode commands jumping to a different position in the current file,
11189 or to another Org-mode file, automatically push the old position
11190 onto the ring."
11191 (interactive "p")
11192 (let (p m)
11193 (if (eq last-command this-command)
11194 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11195 (setq p org-mark-ring))
11196 (setq org-mark-ring-last-goto p)
11197 (setq m (car p))
11198 (org-pop-to-buffer-same-window (marker-buffer m))
11199 (goto-char m)
11200 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11202 ;;; TODO: Use string-remove-prefix and -suffix once we only support
11203 ;;; Emacs 24.4+
11204 (defun org-remove-angle-brackets (s)
11205 (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
11206 (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11208 (defun org-add-angle-brackets (s)
11209 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11210 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11212 (defun org-remove-double-quotes (s)
11213 (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11214 (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11217 ;;; Following specific links
11219 (defvar org-agenda-buffer-tmp-name)
11220 (defvar org-agenda-start-on-weekday)
11221 (defun org-follow-timestamp-link ()
11222 "Open an agenda view for the time-stamp date/range at point."
11223 (cond
11224 ((org-at-date-range-p t)
11225 (let ((org-agenda-start-on-weekday)
11226 (t1 (match-string 1))
11227 (t2 (match-string 2)) tt1 tt2)
11228 (setq tt1 (time-to-days (org-time-string-to-time t1))
11229 tt2 (time-to-days (org-time-string-to-time t2)))
11230 (let ((org-agenda-buffer-tmp-name
11231 (format "*Org Agenda(a:%s)"
11232 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11233 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11234 ((org-at-timestamp-p t)
11235 (let ((org-agenda-buffer-tmp-name
11236 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11237 (org-agenda-list nil (time-to-days (org-time-string-to-time
11238 (substring (match-string 1) 0 10)))
11239 1)))
11240 (t (error "This should not happen"))))
11243 ;;; Following file links
11244 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11245 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11246 (declare-function mailcap-mime-info
11247 "mailcap" (string &optional request no-decode))
11248 (defvar org-wait nil)
11249 (defun org-open-file (path &optional in-emacs line search)
11250 "Open the file at PATH.
11251 First, this expands any special file name abbreviations. Then the
11252 configuration variable `org-file-apps' is checked if it contains an
11253 entry for this file type, and if yes, the corresponding command is launched.
11255 If no application is found, Emacs simply visits the file.
11257 With optional prefix argument IN-EMACS, Emacs will visit the file.
11258 With a double \\[universal-argument] \\[universal-argument] \
11259 prefix arg, Org tries to avoid opening in Emacs
11260 and to use an external application to visit the file.
11262 Optional LINE specifies a line to go to, optional SEARCH a string
11263 to search for. If LINE or SEARCH is given, the file will be
11264 opened in Emacs, unless an entry from org-file-apps that makes
11265 use of groups in a regexp matches.
11267 If you want to change the way frames are used when following a
11268 link, please customize `org-link-frame-setup'.
11270 If the file does not exist, an error is thrown."
11271 (let* ((file (if (equal path "")
11272 buffer-file-name
11273 (substitute-in-file-name (expand-file-name path))))
11274 (file-apps (append org-file-apps (org-default-apps)))
11275 (apps (cl-remove-if
11276 'org-file-apps-entry-match-against-dlink-p file-apps))
11277 (apps-dlink (cl-remove-if-not
11278 'org-file-apps-entry-match-against-dlink-p file-apps))
11279 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11280 (dirp (unless remp (file-directory-p file)))
11281 (file (if (and dirp org-open-directory-means-index-dot-org)
11282 (concat (file-name-as-directory file) "index.org")
11283 file))
11284 (a-m-a-p (assq 'auto-mode apps))
11285 (dfile (downcase file))
11286 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11287 (link (cond ((and (eq line nil)
11288 (eq search nil))
11289 file)
11290 (line
11291 (concat file "::" (number-to-string line)))
11292 (search
11293 (concat file "::" search))))
11294 (dlink (downcase link))
11295 (old-buffer (current-buffer))
11296 (old-pos (point))
11297 (old-mode major-mode)
11298 ext cmd link-match-data)
11299 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11300 (setq ext (match-string 1 dfile))
11301 (when (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11302 (setq ext (match-string 1 dfile))))
11303 (cond
11304 ((member in-emacs '((16) system))
11305 (setq cmd (cdr (assoc 'system apps))))
11306 (in-emacs (setq cmd 'emacs))
11308 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11309 (and dirp (cdr (assoc 'directory apps)))
11310 ; first, try matching against apps-dlink
11311 ; if we get a match here, store the match data for later
11312 (let ((match (assoc-default dlink apps-dlink
11313 'string-match)))
11314 (if match
11315 (progn (setq link-match-data (match-data))
11316 match)
11317 (progn (setq in-emacs (or in-emacs line search))
11318 nil))) ; if we have no match in apps-dlink,
11319 ; always open the file in emacs if line or search
11320 ; is given (for backwards compatibility)
11321 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11322 'string-match)
11323 (cdr (assoc ext apps))
11324 (cdr (assoc t apps))))))
11325 (when (eq cmd 'system)
11326 (setq cmd (cdr (assoc 'system apps))))
11327 (when (eq cmd 'default)
11328 (setq cmd (cdr (assoc t apps))))
11329 (when (eq cmd 'mailcap)
11330 (require 'mailcap)
11331 (mailcap-parse-mailcaps)
11332 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11333 (command (mailcap-mime-info mime-type)))
11334 (if (stringp command)
11335 (setq cmd command)
11336 (setq cmd 'emacs))))
11337 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11338 (not (file-exists-p file))
11339 (not org-open-non-existing-files))
11340 (user-error "No such file: %s" file))
11341 (cond
11342 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11343 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11344 (while (string-match "['\"]%s['\"]" cmd)
11345 (setq cmd (replace-match "%s" t t cmd)))
11346 (while (string-match "%s" cmd)
11347 (setq cmd (replace-match
11348 (save-match-data
11349 (shell-quote-argument
11350 (convert-standard-filename file)))
11351 t t cmd)))
11353 ;; Replace "%1", "%2" etc. in command with group matches from regex
11354 (save-match-data
11355 (let ((match-index 1)
11356 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11357 (set-match-data link-match-data)
11358 (while (<= match-index number-of-groups)
11359 (let ((regex (concat "%" (number-to-string match-index)))
11360 (replace-with (match-string match-index dlink)))
11361 (while (string-match regex cmd)
11362 (setq cmd (replace-match replace-with t t cmd))))
11363 (setq match-index (+ match-index 1)))))
11365 (save-window-excursion
11366 (message "Running %s...done" cmd)
11367 (start-process-shell-command cmd nil cmd)
11368 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11369 ((or (stringp cmd)
11370 (eq cmd 'emacs))
11371 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11372 (widen)
11373 (if line (progn (org-goto-line line)
11374 (when (derived-mode-p 'org-mode)
11375 (org-reveal)))
11376 (when search (org-link-search search))))
11377 ((consp cmd)
11378 (save-match-data
11379 (set-match-data link-match-data)
11380 (eval cmd `((file . ,(convert-standard-filename file))))))
11381 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11382 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11383 (or (not (equal old-buffer (current-buffer)))
11384 (not (equal old-pos (point))))
11385 (org-mark-ring-push old-pos old-buffer))))
11387 (defun org-file-apps-entry-match-against-dlink-p (entry)
11388 "This function returns non-nil if `entry' uses a regular
11389 expression which should be matched against the whole link by
11390 org-open-file.
11392 It assumes that is the case when the entry uses a regular
11393 expression which has at least one grouping construct and the
11394 action is either a lisp form or a command string containing
11395 `%1', i.e. using at least one subexpression match as a
11396 parameter."
11397 (let ((selector (car entry))
11398 (action (cdr entry)))
11399 (if (stringp selector)
11400 (and (> (regexp-opt-depth selector) 0)
11401 (or (and (stringp action)
11402 (string-match "%[0-9]" action))
11403 (consp action)))
11404 nil)))
11406 (defun org-default-apps ()
11407 "Return the default applications for this operating system."
11408 (cond
11409 ((eq system-type 'darwin)
11410 org-file-apps-defaults-macosx)
11411 ((eq system-type 'windows-nt)
11412 org-file-apps-defaults-windowsnt)
11413 (t org-file-apps-defaults-gnu)))
11415 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11416 "Convert extensions to regular expressions in the cars of LIST.
11417 Also, weed out any non-string entries, because the return value is used
11418 only for regexp matching.
11419 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11420 point to the symbol `emacs', indicating that the file should
11421 be opened in Emacs."
11422 (append
11423 (delq nil
11424 (mapcar (lambda (x)
11425 (unless (not (stringp (car x)))
11426 (if (string-match "\\W" (car x))
11428 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11429 list))
11430 (when add-auto-mode
11431 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11433 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11434 (defun org-file-remote-p (file)
11435 "Test whether FILE specifies a location on a remote system.
11436 Return non-nil if the location is indeed remote.
11438 For example, the filename \"/user@host:/foo\" specifies a location
11439 on the system \"/user@host:\"."
11440 (cond ((fboundp 'file-remote-p)
11441 (file-remote-p file))
11442 ((fboundp 'tramp-handle-file-remote-p)
11443 (tramp-handle-file-remote-p file))
11444 ((and (boundp 'ange-ftp-name-format)
11445 (string-match (car ange-ftp-name-format) file))
11446 t)))
11449 ;;;; Refiling
11451 (defun org-get-org-file ()
11452 "Read a filename, with default directory `org-directory'."
11453 (let ((default (or org-default-notes-file remember-data-file)))
11454 (read-file-name (format "File name [%s]: " default)
11455 (file-name-as-directory org-directory)
11456 default)))
11458 (defun org-notes-order-reversed-p ()
11459 "Check if the current file should receive notes in reversed order."
11460 (cond
11461 ((not org-reverse-note-order) nil)
11462 ((eq t org-reverse-note-order) t)
11463 ((not (listp org-reverse-note-order)) nil)
11464 (t (catch 'exit
11465 (dolist (entry org-reverse-note-order)
11466 (when (string-match (car entry) buffer-file-name)
11467 (throw 'exit (cdr entry))))))))
11469 (defvar org-refile-target-table nil
11470 "The list of refile targets, created by `org-refile'.")
11472 (defvar org-agenda-new-buffers nil
11473 "Buffers created to visit agenda files.")
11475 (defvar org-refile-cache nil
11476 "Cache for refile targets.")
11478 (defvar org-refile-markers nil
11479 "All the markers used for caching refile locations.")
11481 (defun org-refile-marker (pos)
11482 "Get a new refile marker, but only if caching is in use."
11483 (if (not org-refile-use-cache)
11485 (let ((m (make-marker)))
11486 (move-marker m pos)
11487 (push m org-refile-markers)
11488 m)))
11490 (defun org-refile-cache-clear ()
11491 "Clear the refile cache and disable all the markers."
11492 (dolist (m org-refile-markers) (move-marker m nil))
11493 (setq org-refile-markers nil)
11494 (setq org-refile-cache nil)
11495 (message "Refile cache has been cleared"))
11497 (defun org-refile-cache-check-set (set)
11498 "Check if all the markers in the cache still have live buffers."
11499 (let (marker)
11500 (catch 'exit
11501 (while (and set (setq marker (nth 3 (pop set))))
11502 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11503 (when (and marker (null (marker-buffer marker)))
11504 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11505 (sit-for 3)
11506 (throw 'exit nil)))
11507 t)))
11509 (defun org-refile-cache-put (set &rest identifiers)
11510 "Push the refile targets SET into the cache, under IDENTIFIERS."
11511 (let* ((key (sha1 (prin1-to-string identifiers)))
11512 (entry (assoc key org-refile-cache)))
11513 (if entry
11514 (setcdr entry set)
11515 (push (cons key set) org-refile-cache))))
11517 (defun org-refile-cache-get (&rest identifiers)
11518 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11519 (cond
11520 ((not org-refile-cache) nil)
11521 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11523 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11524 org-refile-cache))))
11525 (and set (org-refile-cache-check-set set) set)))))
11527 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11528 "Produce a table with refile targets."
11529 (let ((case-fold-search nil)
11530 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11531 (entries (or org-refile-targets '((nil . (:level . 1)))))
11532 targets tgs txt re files desc descre fast-path-p level pos0)
11533 (message "Getting targets...")
11534 (with-current-buffer (or default-buffer (current-buffer))
11535 (dolist (entry entries)
11536 (setq files (car entry) desc (cdr entry))
11537 (setq fast-path-p nil)
11538 (cond
11539 ((null files) (setq files (list (current-buffer))))
11540 ((eq files 'org-agenda-files)
11541 (setq files (org-agenda-files 'unrestricted)))
11542 ((and (symbolp files) (fboundp files))
11543 (setq files (funcall files)))
11544 ((and (symbolp files) (boundp files))
11545 (setq files (symbol-value files))))
11546 (when (stringp files) (setq files (list files)))
11547 (cond
11548 ((eq (car desc) :tag)
11549 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11550 ((eq (car desc) :todo)
11551 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11552 ((eq (car desc) :regexp)
11553 (setq descre (cdr desc)))
11554 ((eq (car desc) :level)
11555 (setq descre (concat "^\\*\\{" (number-to-string
11556 (if org-odd-levels-only
11557 (1- (* 2 (cdr desc)))
11558 (cdr desc)))
11559 "\\}[ \t]")))
11560 ((eq (car desc) :maxlevel)
11561 (setq fast-path-p t)
11562 (setq descre (concat "^\\*\\{1," (number-to-string
11563 (if org-odd-levels-only
11564 (1- (* 2 (cdr desc)))
11565 (cdr desc)))
11566 "\\}[ \t]")))
11567 (t (error "Bad refiling target description %s" desc)))
11568 (dolist (f files)
11569 (with-current-buffer
11570 (if (bufferp f) f (org-get-agenda-file-buffer f))
11572 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11573 (progn
11574 (when (bufferp f) (setq f (buffer-file-name
11575 (buffer-base-buffer f))))
11576 (setq f (and f (expand-file-name f)))
11577 (when (eq org-refile-use-outline-path 'file)
11578 (push (list (file-name-nondirectory f) f nil nil) tgs))
11579 (save-excursion
11580 (save-restriction
11581 (widen)
11582 (goto-char (point-min))
11583 (while (re-search-forward descre nil t)
11584 (goto-char (setq pos0 (point-at-bol)))
11585 (catch 'next
11586 (when org-refile-target-verify-function
11587 (save-match-data
11588 (or (funcall org-refile-target-verify-function)
11589 (throw 'next t))))
11590 (when (and (looking-at org-complex-heading-regexp)
11591 (not (member (match-string 4) excluded-entries))
11592 (match-string 4))
11593 (setq level (org-reduced-level
11594 (- (match-end 1) (match-beginning 1)))
11595 txt (org-link-display-format (match-string 4))
11596 txt (replace-regexp-in-string "\\( *[[0-9]+/?[0-9]*%?]\\)+$" "" txt)
11597 re (format org-complex-heading-regexp-format
11598 (regexp-quote (match-string 4))))
11599 (when org-refile-use-outline-path
11600 (setq txt (mapconcat
11601 'org-protect-slash
11602 (append
11603 (if (eq org-refile-use-outline-path
11604 'file)
11605 (list (file-name-nondirectory
11606 (buffer-file-name
11607 (buffer-base-buffer))))
11608 (when (eq org-refile-use-outline-path
11609 'full-file-path)
11610 (list (buffer-file-name
11611 (buffer-base-buffer)))))
11612 (org-get-outline-path fast-path-p
11613 level txt)
11614 (list txt))
11615 "/")))
11616 (push (list txt f re (org-refile-marker (point)))
11617 tgs)))
11618 (when (= (point) pos0)
11619 ;; verification function has not moved point
11620 (goto-char (point-at-eol))))))))
11621 (when org-refile-use-cache
11622 (org-refile-cache-put tgs (buffer-file-name) descre))
11623 (setq targets (append tgs targets))))))
11624 (message "Getting targets...done")
11625 (nreverse targets)))
11627 (defun org-protect-slash (s)
11628 (while (string-match "/" s)
11629 (setq s (replace-match "\\" t t s)))
11632 (defvar org-olpa (make-vector 20 nil))
11634 (defun org-get-outline-path (&optional fastp level heading)
11635 "Return the outline path to the current entry, as a list.
11637 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11638 routine which makes outline path derivations for an entire file,
11639 avoiding backtracing. Refile target collection makes use of that."
11640 (if fastp
11641 (progn
11642 (when (> level 19)
11643 (error "Outline path failure, more than 19 levels"))
11644 (cl-loop for i from level upto 19 do
11645 (aset org-olpa i nil))
11646 (prog1
11647 (delq nil (append org-olpa nil))
11648 (aset org-olpa level heading)))
11649 (let (rtn case-fold-search)
11650 (save-excursion
11651 (save-restriction
11652 (widen)
11653 (while (org-up-heading-safe)
11654 (when (looking-at org-complex-heading-regexp)
11655 (push (org-trim
11656 (replace-regexp-in-string
11657 ;; Remove statistical/checkboxes cookies
11658 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11659 (org-match-string-no-properties 4)))
11660 rtn)))
11661 rtn)))))
11663 (defun org-format-outline-path (path &optional width prefix separator)
11664 "Format the outline path PATH for display.
11665 WIDTH is the maximum number of characters that is available.
11666 PREFIX is a prefix to be included in the returned string,
11667 such as the file name.
11668 SEPARATOR is inserted between the different parts of the path,
11669 the default is \"/\"."
11670 (setq width (or width 79))
11671 (setq path (delq nil path))
11672 (unless (> width 0)
11673 (user-error "Argument `width' must be positive"))
11674 (setq separator (or separator "/"))
11675 (let* ((org-odd-levels-only nil)
11676 (fpath (concat
11677 prefix (and prefix path separator)
11678 (mapconcat
11679 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11680 (cl-loop for head in path
11681 for n from 0
11682 collect (org-add-props
11683 head nil 'face
11684 (nth (% n org-n-level-faces) org-level-faces)))
11685 separator))))
11686 (when (> (length fpath) width)
11687 (if (< width 7)
11688 ;; It's unlikely that `width' will be this small, but don't
11689 ;; waste characters by adding ".." if it is.
11690 (setq fpath (substring fpath 0 width))
11691 (setf (substring fpath (- width 2)) "..")))
11692 fpath))
11694 (defun org-display-outline-path (&optional file current separator just-return-string)
11695 "Display the current outline path in the echo area.
11697 If FILE is non-nil, prepend the output with the file name.
11698 If CURRENT is non-nil, append the current heading to the output.
11699 SEPARATOR is passed through to `org-format-outline-path'. It separates
11700 the different parts of the path and defaults to \"/\".
11701 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11702 (interactive "P")
11703 (let* (case-fold-search
11704 (bfn (buffer-file-name (buffer-base-buffer)))
11705 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11706 res)
11707 (when current (setq path (append path
11708 (save-excursion
11709 (org-back-to-heading t)
11710 (when (looking-at org-complex-heading-regexp)
11711 (list (match-string 4)))))))
11712 (setq res
11713 (org-format-outline-path
11714 path
11715 (1- (frame-width))
11716 (and file bfn (concat (file-name-nondirectory bfn) separator))
11717 separator))
11718 (if just-return-string
11719 (org-no-properties res)
11720 (org-unlogged-message "%s" res))))
11722 (defvar org-refile-history nil
11723 "History for refiling operations.")
11725 (defvar org-after-refile-insert-hook nil
11726 "Hook run after `org-refile' has inserted its stuff at the new location.
11727 Note that this is still *before* the stuff will be removed from
11728 the *old* location.")
11730 (defvar org-capture-last-stored-marker)
11731 (defvar org-refile-keep nil
11732 "Non-nil means `org-refile' will copy instead of refile.")
11734 (defun org-copy ()
11735 "Like `org-refile', but copy."
11736 (interactive)
11737 (let ((org-refile-keep t))
11738 (funcall 'org-refile nil nil nil "Copy")))
11740 (defun org-refile (&optional arg default-buffer rfloc msg)
11741 "Move the entry or entries at point to another heading.
11742 The list of target headings is compiled using the information in
11743 `org-refile-targets', which see.
11745 At the target location, the entry is filed as a subitem of the
11746 target heading. Depending on `org-reverse-note-order', the new
11747 subitem will either be the first or the last subitem.
11749 If there is an active region, all entries in that region will be
11750 refiled. However, the region must fulfill the requirement that
11751 the first heading sets the top-level of the moved text.
11753 With prefix arg ARG, the command will only visit the target
11754 location and not actually move anything.
11756 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11757 refiling operation has put the subtree.
11759 With a numeric prefix argument of `2', refile to the running clock.
11761 With a numeric prefix argument of `3', emulate `org-refile-keep'
11762 being set to t and copy to the target location, don't move it.
11763 Beware that keeping refiled entries may result in duplicated ID
11764 properties.
11766 RFLOC can be a refile location obtained in a different way.
11768 MSG is a string to replace \"Refile\" in the default prompt with
11769 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11771 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11773 If you are using target caching (see `org-refile-use-cache'), you
11774 have to clear the target cache in order to find new targets.
11775 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11776 prefix argument (`C-u C-u C-u C-c C-w')."
11777 (interactive "P")
11778 (if (member arg '(0 (64)))
11779 (org-refile-cache-clear)
11780 (let* ((actionmsg (cond (msg msg)
11781 ((equal arg 3) "Refile (and keep)")
11782 (t "Refile")))
11783 (regionp (org-region-active-p))
11784 (region-start (and regionp (region-beginning)))
11785 (region-end (and regionp (region-end)))
11786 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11787 pos it nbuf file level reversed)
11788 (setq last-command nil)
11789 (when regionp
11790 (goto-char region-start)
11791 (or (bolp) (goto-char (point-at-bol)))
11792 (setq region-start (point))
11793 (unless (or (org-kill-is-subtree-p
11794 (buffer-substring region-start region-end))
11795 (prog1 org-refile-active-region-within-subtree
11796 (let ((s (point-at-eol)))
11797 (org-toggle-heading)
11798 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11799 (user-error "The region is not a (sequence of) subtree(s)")))
11800 (if (equal arg '(16))
11801 (org-refile-goto-last-stored)
11802 (when (or
11803 (and (equal arg 2)
11804 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11805 (prog1
11806 (setq it (list (or org-clock-heading "running clock")
11807 (buffer-file-name
11808 (marker-buffer org-clock-hd-marker))
11810 (marker-position org-clock-hd-marker)))
11811 (setq arg nil)))
11812 (setq it (or rfloc
11813 (let (heading-text)
11814 (save-excursion
11815 (unless (and arg (listp arg))
11816 (org-back-to-heading t)
11817 (setq heading-text
11818 (replace-regexp-in-string
11819 org-bracket-link-regexp
11820 "\\3"
11821 (nth 4 (org-heading-components)))))
11822 (org-refile-get-location
11823 (cond ((and arg (listp arg)) "Goto")
11824 (regionp (concat actionmsg " region to"))
11825 (t (concat actionmsg " subtree \""
11826 heading-text "\" to")))
11827 default-buffer
11828 (and (not (equal '(4) arg))
11829 org-refile-allow-creating-parent-nodes)
11830 arg))))))
11831 (setq file (nth 1 it)
11832 pos (nth 3 it))
11833 (when (and (not arg)
11835 (equal (buffer-file-name) file)
11836 (if regionp
11837 (and (>= pos region-start)
11838 (<= pos region-end))
11839 (and (>= pos (point))
11840 (< pos (save-excursion
11841 (org-end-of-subtree t t))))))
11842 (error "Cannot refile to position inside the tree or region"))
11843 (setq nbuf (or (find-buffer-visiting file)
11844 (find-file-noselect file)))
11845 (if (and arg (not (equal arg 3)))
11846 (progn
11847 (org-pop-to-buffer-same-window nbuf)
11848 (goto-char pos)
11849 (org-show-context 'org-goto))
11850 (if regionp
11851 (progn
11852 (org-kill-new (buffer-substring region-start region-end))
11853 (org-save-markers-in-region region-start region-end))
11854 (org-copy-subtree 1 nil t))
11855 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11856 (find-file-noselect file)))
11857 (setq reversed (org-notes-order-reversed-p))
11858 (save-excursion
11859 (save-restriction
11860 (widen)
11861 (if pos
11862 (progn
11863 (goto-char pos)
11864 (looking-at org-outline-regexp)
11865 (setq level (org-get-valid-level (funcall outline-level) 1))
11866 (goto-char
11867 (if reversed
11868 (or (outline-next-heading) (point-max))
11869 (or (save-excursion (org-get-next-sibling))
11870 (org-end-of-subtree t t)
11871 (point-max)))))
11872 (setq level 1)
11873 (if (not reversed)
11874 (goto-char (point-max))
11875 (goto-char (point-min))
11876 (or (outline-next-heading) (goto-char (point-max)))))
11877 (unless (bolp) (newline))
11878 (org-paste-subtree level nil nil t)
11879 (when org-log-refile
11880 (org-add-log-setup 'refile nil nil org-log-refile)
11881 (unless (eq org-log-refile 'note)
11882 (save-excursion (org-add-log-note))))
11883 (and org-auto-align-tags
11884 (let ((org-loop-over-headlines-in-active-region nil))
11885 (org-set-tags nil t)))
11886 (let ((bookmark-name (plist-get org-bookmark-names-plist
11887 :last-refile)))
11888 (when bookmark-name
11889 (with-demoted-errors
11890 (bookmark-set bookmark-name))))
11891 ;; If we are refiling for capture, make sure that the
11892 ;; last-capture pointers point here
11893 (when (org-bound-and-true-p org-capture-is-refiling)
11894 (let ((bookmark-name (plist-get org-bookmark-names-plist
11895 :last-capture-marker)))
11896 (when bookmark-name
11897 (with-demoted-errors
11898 (bookmark-set bookmark-name))))
11899 (move-marker org-capture-last-stored-marker (point)))
11900 (when (fboundp 'deactivate-mark) (deactivate-mark))
11901 (run-hooks 'org-after-refile-insert-hook))))
11902 (unless org-refile-keep
11903 (if regionp
11904 (delete-region (point) (+ (point) (- region-end region-start)))
11905 (delete-region
11906 (and (org-back-to-heading t) (point))
11907 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11908 (when (featurep 'org-inlinetask)
11909 (org-inlinetask-remove-END-maybe))
11910 (setq org-markers-to-move nil)
11911 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11913 (defun org-refile-goto-last-stored ()
11914 "Go to the location where the last refile was stored."
11915 (interactive)
11916 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11917 (message "This is the location of the last refile"))
11919 (defun org-refile--get-location (refloc tbl)
11920 "When user refile to REFLOC, find the associated target in TBL.
11921 Also check `org-refile-target-table'."
11922 (car (delq
11924 (mapcar
11925 (lambda (r) (or (assoc r tbl)
11926 (assoc r org-refile-target-table)))
11927 (list (replace-regexp-in-string "/$" "" refloc)
11928 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11930 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11931 no-exclude)
11932 "Prompt the user for a refile location, using PROMPT.
11933 PROMPT should not be suffixed with a colon and a space, because
11934 this function appends the default value from
11935 `org-refile-history' automatically, if that is not empty.
11936 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11937 this is used for the GOTO interface."
11938 (let ((org-refile-targets org-refile-targets)
11939 (org-refile-use-outline-path org-refile-use-outline-path)
11940 excluded-entries)
11941 (when (and (derived-mode-p 'org-mode)
11942 (not org-refile-use-cache)
11943 (not no-exclude))
11944 (org-map-tree
11945 (lambda()
11946 (setq excluded-entries
11947 (append excluded-entries (list (org-get-heading t t)))))))
11948 (setq org-refile-target-table
11949 (org-refile-get-targets default-buffer excluded-entries)))
11950 (unless org-refile-target-table
11951 (user-error "No refile targets"))
11952 (let* ((cbuf (current-buffer))
11953 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11954 (cfunc (if (and org-refile-use-outline-path
11955 org-outline-path-complete-in-steps)
11956 #'org-olpath-completing-read
11957 #'completing-read))
11958 (extra (if org-refile-use-outline-path "/" ""))
11959 (cbnex (concat (buffer-name) extra))
11960 (filename (and cfn (expand-file-name cfn)))
11961 (tbl (mapcar
11962 (lambda (x)
11963 (if (and (not (member org-refile-use-outline-path
11964 '(file full-file-path)))
11965 (not (equal filename (nth 1 x))))
11966 (cons (concat (car x) extra " ("
11967 (file-name-nondirectory (nth 1 x)) ")")
11968 (cdr x))
11969 (cons (concat (car x) extra) (cdr x))))
11970 org-refile-target-table))
11971 (completion-ignore-case t)
11972 cdef
11973 (prompt (concat prompt
11974 (or (and (car org-refile-history)
11975 (concat " (default " (car org-refile-history) ")"))
11976 (and (assoc cbnex tbl) (setq cdef cbnex)
11977 (concat " (default " cbnex ")"))) ": "))
11978 pa answ parent-target child parent old-hist)
11979 (setq old-hist org-refile-history)
11980 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11981 nil 'org-refile-history (or cdef (car org-refile-history))))
11982 (if (setq pa (org-refile--get-location answ tbl))
11983 (progn
11984 (org-refile-check-position pa)
11985 (when (or (not org-refile-history)
11986 (not (eq old-hist org-refile-history))
11987 (not (equal (car pa) (car org-refile-history))))
11988 (setq org-refile-history
11989 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11990 org-refile-history
11991 (cdr org-refile-history))))
11992 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11993 (pop org-refile-history)))
11995 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11996 (progn
11997 (setq parent (match-string 1 answ)
11998 child (match-string 2 answ))
11999 (setq parent-target (org-refile--get-location parent tbl))
12000 (when (and parent-target
12001 (or (eq new-nodes t)
12002 (and (eq new-nodes 'confirm)
12003 (y-or-n-p (format "Create new node \"%s\"? "
12004 child)))))
12005 (org-refile-new-child parent-target child)))
12006 (user-error "Invalid target location")))))
12008 (declare-function org-string-nw-p "org-macs" (s))
12009 (defun org-refile-check-position (refile-pointer)
12010 "Check if the refile pointer matches the headline to which it points."
12011 (let* ((file (nth 1 refile-pointer))
12012 (re (nth 2 refile-pointer))
12013 (pos (nth 3 refile-pointer))
12014 buffer)
12015 (if (and (not (markerp pos)) (not file))
12016 (user-error "Please indicate a target file in the refile path")
12017 (when (org-string-nw-p re)
12018 (setq buffer (if (markerp pos)
12019 (marker-buffer pos)
12020 (or (find-buffer-visiting file)
12021 (find-file-noselect file))))
12022 (with-current-buffer buffer
12023 (save-excursion
12024 (save-restriction
12025 (widen)
12026 (goto-char pos)
12027 (beginning-of-line 1)
12028 (unless (org-looking-at-p re)
12029 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12031 (defun org-refile-new-child (parent-target child)
12032 "Use refile target PARENT-TARGET to add new CHILD below it."
12033 (unless parent-target
12034 (error "Cannot find parent for new node"))
12035 (let ((file (nth 1 parent-target))
12036 (pos (nth 3 parent-target))
12037 level)
12038 (with-current-buffer (or (find-buffer-visiting file)
12039 (find-file-noselect file))
12040 (save-excursion
12041 (save-restriction
12042 (widen)
12043 (if pos
12044 (goto-char pos)
12045 (goto-char (point-max))
12046 (unless (bolp) (newline)))
12047 (when (looking-at org-outline-regexp)
12048 (setq level (funcall outline-level))
12049 (org-end-of-subtree t t))
12050 (org-back-over-empty-lines)
12051 (insert "\n" (make-string
12052 (if pos (org-get-valid-level level 1) 1) ?*)
12053 " " child "\n")
12054 (beginning-of-line 0)
12055 (list (concat (car parent-target) "/" child) file "" (point)))))))
12057 (defun org-olpath-completing-read (prompt collection &rest args)
12058 "Read an outline path like a file name."
12059 (let ((thetable collection))
12060 (apply #'completing-read
12061 prompt
12062 (lambda (string predicate &optional flag)
12063 (cond
12064 ((eq flag nil) (try-completion string thetable))
12065 ((eq flag t)
12066 (let ((l (length string)))
12067 (mapcar (lambda (x)
12068 (let ((r (substring x l))
12069 (f (if (string-match " ([^)]*)$" x)
12070 (match-string 0 x)
12071 "")))
12072 (if (string-match "/" r)
12073 (concat string (substring r 0 (match-end 0)) f)
12074 x)))
12075 (all-completions string thetable predicate))))
12076 ;; Exact match?
12077 ((eq flag 'lambda) (assoc string thetable))))
12078 args)))
12080 ;;;; Dynamic blocks
12082 (defun org-find-dblock (name)
12083 "Find the first dynamic block with name NAME in the buffer.
12084 If not found, stay at current position and return nil."
12085 (let ((case-fold-search t) pos)
12086 (save-excursion
12087 (goto-char (point-min))
12088 (setq pos (and (re-search-forward
12089 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12090 (match-beginning 0))))
12091 (when pos (goto-char pos))
12092 pos))
12094 (defun org-create-dblock (plist)
12095 "Create a dynamic block section, with parameters taken from PLIST.
12096 PLIST must contain a :name entry which is used as the name of the block."
12097 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12098 (end-of-line 1)
12099 (newline))
12100 (let ((col (current-column))
12101 (name (plist-get plist :name)))
12102 (insert "#+BEGIN: " name)
12103 (while plist
12104 (if (eq (car plist) :name)
12105 (setq plist (cddr plist))
12106 (insert " " (prin1-to-string (pop plist)))))
12107 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12108 (beginning-of-line -2)))
12110 (defun org-prepare-dblock ()
12111 "Prepare dynamic block for refresh.
12112 This empties the block, puts the cursor at the insert position and returns
12113 the property list including an extra property :name with the block name."
12114 (unless (looking-at org-dblock-start-re)
12115 (user-error "Not at a dynamic block"))
12116 (let* ((begdel (1+ (match-end 0)))
12117 (name (org-no-properties (match-string 1)))
12118 (params (append (list :name name)
12119 (read (concat "(" (match-string 3) ")")))))
12120 (save-excursion
12121 (beginning-of-line 1)
12122 (skip-chars-forward " \t")
12123 (setq params (plist-put params :indentation-column (current-column))))
12124 (unless (re-search-forward org-dblock-end-re nil t)
12125 (error "Dynamic block not terminated"))
12126 (setq params
12127 (append params
12128 (list :content (buffer-substring
12129 begdel (match-beginning 0)))))
12130 (delete-region begdel (match-beginning 0))
12131 (goto-char begdel)
12132 (open-line 1)
12133 params))
12135 (defun org-map-dblocks (&optional command)
12136 "Apply COMMAND to all dynamic blocks in the current buffer.
12137 If COMMAND is not given, use `org-update-dblock'."
12138 (let ((cmd (or command 'org-update-dblock)))
12139 (save-excursion
12140 (goto-char (point-min))
12141 (while (re-search-forward org-dblock-start-re nil t)
12142 (goto-char (match-beginning 0))
12143 (save-excursion
12144 (condition-case nil
12145 (funcall cmd)
12146 (error (message "Error during update of dynamic block"))))
12147 (unless (re-search-forward org-dblock-end-re nil t)
12148 (error "Dynamic block not terminated"))))))
12150 (defun org-dblock-update (&optional arg)
12151 "User command for updating dynamic blocks.
12152 Update the dynamic block at point. With prefix ARG, update all dynamic
12153 blocks in the buffer."
12154 (interactive "P")
12155 (if arg
12156 (org-update-all-dblocks)
12157 (or (looking-at org-dblock-start-re)
12158 (org-beginning-of-dblock))
12159 (org-update-dblock)))
12161 (defun org-update-dblock ()
12162 "Update the dynamic block at point.
12163 This means to empty the block, parse for parameters and then call
12164 the correct writing function."
12165 (interactive)
12166 (save-excursion
12167 (let* ((win (selected-window))
12168 (pos (point))
12169 (line (org-current-line))
12170 (params (org-prepare-dblock))
12171 (name (plist-get params :name))
12172 (indent (plist-get params :indentation-column))
12173 (cmd (intern (concat "org-dblock-write:" name))))
12174 (message "Updating dynamic block `%s' at line %d..." name line)
12175 (funcall cmd params)
12176 (message "Updating dynamic block `%s' at line %d...done" name line)
12177 (goto-char pos)
12178 (when (and indent (> indent 0))
12179 (setq indent (make-string indent ?\ ))
12180 (save-excursion
12181 (select-window win)
12182 (org-beginning-of-dblock)
12183 (forward-line 1)
12184 (while (not (looking-at org-dblock-end-re))
12185 (insert indent)
12186 (beginning-of-line 2))
12187 (when (looking-at org-dblock-end-re)
12188 (and (looking-at "[ \t]+")
12189 (replace-match ""))
12190 (insert indent)))))))
12192 (defun org-beginning-of-dblock ()
12193 "Find the beginning of the dynamic block at point.
12194 Error if there is no such block at point."
12195 (let ((pos (point))
12196 beg)
12197 (end-of-line 1)
12198 (if (and (re-search-backward org-dblock-start-re nil t)
12199 (setq beg (match-beginning 0))
12200 (re-search-forward org-dblock-end-re nil t)
12201 (> (match-end 0) pos))
12202 (goto-char beg)
12203 (goto-char pos)
12204 (error "Not in a dynamic block"))))
12206 (defun org-update-all-dblocks ()
12207 "Update all dynamic blocks in the buffer.
12208 This function can be used in a hook."
12209 (interactive)
12210 (when (derived-mode-p 'org-mode)
12211 (org-map-dblocks 'org-update-dblock)))
12214 ;;;; Completion
12216 (declare-function org-export-backend-name "org-export" (cl-x))
12217 (declare-function org-export-backend-options "org-export" (cl-x))
12218 (defun org-get-export-keywords ()
12219 "Return a list of all currently understood export keywords.
12220 Export keywords include options, block names, attributes and
12221 keywords relative to each registered export back-end."
12222 (let (keywords)
12223 (dolist (backend
12224 (org-bound-and-true-p org-export-registered-backends)
12225 (delq nil keywords))
12226 ;; Back-end name (for keywords, like #+LATEX:)
12227 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12228 (dolist (option-entry (org-export-backend-options backend))
12229 ;; Back-end options.
12230 (push (nth 1 option-entry) keywords)))))
12232 (defconst org-options-keywords
12233 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12234 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12235 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12236 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12237 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12239 (defcustom org-structure-template-alist
12240 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12241 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12242 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12243 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12244 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12245 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12246 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12247 ("L" "#+LaTeX: ")
12248 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12249 ("H" "#+HTML: ")
12250 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12251 ("A" "#+ASCII: ")
12252 ("i" "#+INDEX: ?")
12253 ("I" "#+INCLUDE: %file ?"))
12254 "Structure completion elements.
12255 This is a list of abbreviation keys and values. The value gets inserted
12256 if you type `<' followed by the key and then press the completion key,
12257 usually `TAB'. %file will be replaced by a file name after prompting
12258 for the file using completion. The cursor will be placed at the position
12259 of the `?' in the template.
12260 There are two templates for each key, the first uses the original Org syntax,
12261 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12262 the default when the /org-mtags.el/ module has been loaded. See also the
12263 variable `org-mtags-prefer-muse-templates'."
12264 :group 'org-completion
12265 :type '(repeat
12266 (list
12267 (string :tag "Key")
12268 (string :tag "Template")))
12269 :version "25.1"
12270 :package-version '(Org . "8.3"))
12272 (defun org-try-structure-completion ()
12273 "Try to complete a structure template before point.
12274 This looks for strings like \"<e\" on an otherwise empty line and
12275 expands them."
12276 (let ((l (buffer-substring (point-at-bol) (point)))
12278 (when (and (looking-at "[ \t]*$")
12279 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12280 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12281 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12282 (match-beginning 1)) a)
12283 t)))
12285 (defun org-complete-expand-structure-template (start cell)
12286 "Expand a structure template."
12287 (let ((rpl (nth 1 cell))
12288 (ind ""))
12289 (delete-region start (point))
12290 (when (string-match "\\`[ \t]*#\\+" rpl)
12291 (cond
12292 ((bolp))
12293 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12294 (setq ind (buffer-substring (point-at-bol) (point))))
12295 (t (newline))))
12296 (setq start (point))
12297 (when (string-match "%file" rpl)
12298 (setq rpl (replace-match
12299 (concat
12300 "\""
12301 (save-match-data
12302 (abbreviate-file-name (read-file-name "Include file: ")))
12303 "\"")
12304 t t rpl)))
12305 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12306 (concat "\n" ind)))
12307 (insert rpl)
12308 (when (re-search-backward "\\?" start t) (delete-char 1))))
12310 ;;;; TODO, DEADLINE, Comments
12312 (defun org-toggle-comment ()
12313 "Change the COMMENT state of an entry."
12314 (interactive)
12315 (save-excursion
12316 (org-back-to-heading)
12317 (looking-at org-complex-heading-regexp)
12318 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12319 (skip-chars-forward " \t")
12320 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12321 (if (org-in-commented-heading-p t)
12322 (delete-region (point)
12323 (progn (search-forward " " (line-end-position) 'move)
12324 (skip-chars-forward " \t")
12325 (point)))
12326 (insert org-comment-string)
12327 (unless (eolp) (insert " ")))))
12329 (defvar org-last-todo-state-is-todo nil
12330 "This is non-nil when the last TODO state change led to a TODO state.
12331 If the last change removed the TODO tag or switched to DONE, then
12332 this is nil.")
12334 (defvar org-setting-tags nil) ; dynamically skipped
12336 (defvar org-todo-setup-filter-hook nil
12337 "Hook for functions that pre-filter todo specs.
12338 Each function takes a todo spec and returns either nil or the spec
12339 transformed into canonical form." )
12341 (defvar org-todo-get-default-hook nil
12342 "Hook for functions that get a default item for todo.
12343 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12344 nil or a string to be used for the todo mark." )
12346 (defvar org-agenda-headline-snapshot-before-repeat)
12348 (defun org-current-effective-time ()
12349 "Return current time adjusted for `org-extend-today-until' variable."
12350 (let* ((ct (org-current-time))
12351 (dct (decode-time ct))
12352 (ct1
12353 (cond
12354 (org-use-last-clock-out-time-as-effective-time
12355 (or (org-clock-get-last-clock-out-time) ct))
12356 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12357 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12358 (t ct))))
12359 ct1))
12361 (defun org-todo-yesterday (&optional arg)
12362 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12363 (interactive "P")
12364 (if (eq major-mode 'org-agenda-mode)
12365 (apply 'org-agenda-todo-yesterday arg)
12366 (let* ((org-use-effective-time t)
12367 (hour (nth 2 (decode-time (org-current-time))))
12368 (org-extend-today-until (1+ hour)))
12369 (org-todo arg))))
12371 (defvar org-block-entry-blocking ""
12372 "First entry preventing the TODO state change.")
12374 (defun org-cancel-repeater ()
12375 "Cancel a repeater by setting its numeric value to zero."
12376 (interactive)
12377 (save-excursion
12378 (org-back-to-heading t)
12379 (let ((bound1 (point))
12380 (bound0 (save-excursion (outline-next-heading) (point))))
12381 (when (and (re-search-forward
12382 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12383 org-deadline-time-regexp "\\)\\|\\("
12384 org-ts-regexp "\\)")
12385 bound0 t)
12386 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12387 bound1 t))
12388 (replace-match "0" t nil nil 1)))))
12390 (defvar org-state) ;; dynamically scoped into this function
12391 (defun org-todo (&optional arg)
12392 "Change the TODO state of an item.
12393 The state of an item is given by a keyword at the start of the heading,
12394 like
12395 *** TODO Write paper
12396 *** DONE Call mom
12398 The different keywords are specified in the variable `org-todo-keywords'.
12399 By default the available states are \"TODO\" and \"DONE\".
12400 So for this example: when the item starts with TODO, it is changed to DONE.
12401 When it starts with DONE, the DONE is removed. And when neither TODO nor
12402 DONE are present, add TODO at the beginning of the heading.
12404 With \\[universal-argument] prefix arg, use completion to determine the new \
12405 state.
12406 With numeric prefix arg, switch to that state.
12407 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12408 keywords (nextset).
12409 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12410 With a numeric prefix arg of 0, inhibit note taking for the change.
12411 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12413 When called through ELisp, arg is also interpreted in the following way:
12414 `none' -> empty state
12415 \"\"(empty string) -> switch to empty state
12416 `done' -> switch to DONE
12417 `nextset' -> switch to the next set of keywords
12418 `previousset' -> switch to the previous set of keywords
12419 \"WAITING\" -> switch to the specified keyword, but only if it
12420 really is a member of `org-todo-keywords'."
12421 (interactive "P")
12422 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12423 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12424 'region-start-level 'region))
12425 org-loop-over-headlines-in-active-region)
12426 (org-map-entries
12427 `(org-todo ,arg)
12428 org-loop-over-headlines-in-active-region
12429 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12430 (when (equal arg '(16)) (setq arg 'nextset))
12431 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12432 (let ((org-blocker-hook org-blocker-hook)
12433 commentp
12434 case-fold-search)
12435 (when (equal arg '(64))
12436 (setq arg nil org-blocker-hook nil))
12437 (when (and org-blocker-hook
12438 (or org-inhibit-blocking
12439 (org-entry-get nil "NOBLOCKING")))
12440 (setq org-blocker-hook nil))
12441 (save-excursion
12442 (catch 'exit
12443 (org-back-to-heading t)
12444 (when (org-in-commented-heading-p t)
12445 (org-toggle-comment)
12446 (setq commentp t))
12447 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12448 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12449 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12450 (let* ((match-data (match-data))
12451 (startpos (point-at-bol))
12452 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12453 (org-log-done org-log-done)
12454 (org-log-repeat org-log-repeat)
12455 (org-todo-log-states org-todo-log-states)
12456 (org-inhibit-logging
12457 (if (equal arg 0)
12458 (progn (setq arg nil) 'note) org-inhibit-logging))
12459 (this (match-string 1))
12460 (hl-pos (match-beginning 0))
12461 (head (org-get-todo-sequence-head this))
12462 (ass (assoc head org-todo-kwd-alist))
12463 (interpret (nth 1 ass))
12464 (done-word (nth 3 ass))
12465 (final-done-word (nth 4 ass))
12466 (org-last-state (or this ""))
12467 (completion-ignore-case t)
12468 (member (member this org-todo-keywords-1))
12469 (tail (cdr member))
12470 (org-state (cond
12471 ((and org-todo-key-trigger
12472 (or (and (equal arg '(4))
12473 (eq org-use-fast-todo-selection 'prefix))
12474 (and (not arg) org-use-fast-todo-selection
12475 (not (eq org-use-fast-todo-selection
12476 'prefix)))))
12477 ;; Use fast selection
12478 (org-fast-todo-selection))
12479 ((and (equal arg '(4))
12480 (or (not org-use-fast-todo-selection)
12481 (not org-todo-key-trigger)))
12482 ;; Read a state with completion
12483 (completing-read
12484 "State: " (mapcar #'list org-todo-keywords-1)
12485 nil t))
12486 ((eq arg 'right)
12487 (if this
12488 (if tail (car tail) nil)
12489 (car org-todo-keywords-1)))
12490 ((eq arg 'left)
12491 (unless (equal member org-todo-keywords-1)
12492 (if this
12493 (nth (- (length org-todo-keywords-1)
12494 (length tail) 2)
12495 org-todo-keywords-1)
12496 (org-last org-todo-keywords-1))))
12497 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12498 (setq arg nil))) ; hack to fall back to cycling
12499 (arg
12500 ;; user or caller requests a specific state
12501 (cond
12502 ((equal arg "") nil)
12503 ((eq arg 'none) nil)
12504 ((eq arg 'done) (or done-word (car org-done-keywords)))
12505 ((eq arg 'nextset)
12506 (or (car (cdr (member head org-todo-heads)))
12507 (car org-todo-heads)))
12508 ((eq arg 'previousset)
12509 (let ((org-todo-heads (reverse org-todo-heads)))
12510 (or (car (cdr (member head org-todo-heads)))
12511 (car org-todo-heads))))
12512 ((car (member arg org-todo-keywords-1)))
12513 ((stringp arg)
12514 (user-error "State `%s' not valid in this file" arg))
12515 ((nth (1- (prefix-numeric-value arg))
12516 org-todo-keywords-1))))
12517 ((null member) (or head (car org-todo-keywords-1)))
12518 ((equal this final-done-word) nil) ;; -> make empty
12519 ((null tail) nil) ;; -> first entry
12520 ((memq interpret '(type priority))
12521 (if (eq this-command last-command)
12522 (car tail)
12523 (if (> (length tail) 0)
12524 (or done-word (car org-done-keywords))
12525 nil)))
12527 (car tail))))
12528 (org-state (or
12529 (run-hook-with-args-until-success
12530 'org-todo-get-default-hook org-state org-last-state)
12531 org-state))
12532 (next (if org-state (concat " " org-state " ") " "))
12533 (change-plist (list :type 'todo-state-change :from this :to org-state
12534 :position startpos))
12535 dolog now-done-p)
12536 (when org-blocker-hook
12537 (setq org-last-todo-state-is-todo
12538 (not (member this org-done-keywords)))
12539 (unless (save-excursion
12540 (save-match-data
12541 (org-with-wide-buffer
12542 (run-hook-with-args-until-failure
12543 'org-blocker-hook change-plist))))
12544 (if (org-called-interactively-p 'interactive)
12545 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12546 this org-state org-block-entry-blocking)
12547 ;; fail silently
12548 (message "TODO state change from %s to %s blocked (by \"%s\")"
12549 this org-state org-block-entry-blocking)
12550 (throw 'exit nil))))
12551 (store-match-data match-data)
12552 (replace-match next t t)
12553 (cond ((equal this org-state)
12554 (message "TODO state was already %s" (org-trim next)))
12555 ((pos-visible-in-window-p hl-pos)
12556 (message "TODO state changed to %s" (org-trim next))))
12557 (unless head
12558 (setq head (org-get-todo-sequence-head org-state)
12559 ass (assoc head org-todo-kwd-alist)
12560 interpret (nth 1 ass)
12561 done-word (nth 3 ass)
12562 final-done-word (nth 4 ass)))
12563 (when (memq arg '(nextset previousset))
12564 (message "Keyword-Set %d/%d: %s"
12565 (- (length org-todo-sets) -1
12566 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12567 (length org-todo-sets)
12568 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12569 (setq org-last-todo-state-is-todo
12570 (not (member org-state org-done-keywords)))
12571 (setq now-done-p (and (member org-state org-done-keywords)
12572 (not (member this org-done-keywords))))
12573 (and logging (org-local-logging logging))
12574 (when (and (or org-todo-log-states org-log-done)
12575 (not (eq org-inhibit-logging t))
12576 (not (memq arg '(nextset previousset))))
12577 ;; we need to look at recording a time and note
12578 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12579 (nth 2 (assoc this org-todo-log-states))))
12580 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12581 (setq dolog 'time))
12582 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12583 (and org-state
12584 (member org-state org-not-done-keywords)
12585 (not (member this org-not-done-keywords))))
12586 ;; This is now a todo state and was not one before
12587 ;; If there was a CLOSED time stamp, get rid of it.
12588 (org-add-planning-info nil nil 'closed))
12589 (when (and now-done-p org-log-done)
12590 ;; It is now done, and it was not done before
12591 (org-add-planning-info 'closed (org-current-effective-time))
12592 (when (and (not dolog) (eq 'note org-log-done))
12593 (org-add-log-setup 'done org-state this 'note)))
12594 (when (and org-state dolog)
12595 ;; This is a non-nil state, and we need to log it
12596 (org-add-log-setup 'state org-state this dolog)))
12597 ;; Fixup tag positioning
12598 (org-todo-trigger-tag-changes org-state)
12599 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12600 (when org-provide-todo-statistics
12601 (org-update-parent-todo-statistics))
12602 (run-hooks 'org-after-todo-state-change-hook)
12603 (when (and arg (not (member org-state org-done-keywords)))
12604 (setq head (org-get-todo-sequence-head org-state)))
12605 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12606 ;; Do we need to trigger a repeat?
12607 (when now-done-p
12608 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12609 ;; This is for the agenda, take a snapshot of the headline.
12610 (save-match-data
12611 (setq org-agenda-headline-snapshot-before-repeat
12612 (org-get-heading))))
12613 (org-auto-repeat-maybe org-state))
12614 ;; Fixup cursor location if close to the keyword
12615 (when (and (outline-on-heading-p)
12616 (not (bolp))
12617 (save-excursion (beginning-of-line 1)
12618 (looking-at org-todo-line-regexp))
12619 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12620 (goto-char (or (match-end 2) (match-end 1)))
12621 (and (looking-at " ") (just-one-space)))
12622 (when org-trigger-hook
12623 (save-excursion
12624 (run-hook-with-args 'org-trigger-hook change-plist)))
12625 (when commentp (org-toggle-comment))))))))
12627 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12628 "Block turning an entry into a TODO, using the hierarchy.
12629 This checks whether the current task should be blocked from state
12630 changes. Such blocking occurs when:
12632 1. The task has children which are not all in a completed state.
12634 2. A task has a parent with the property :ORDERED:, and there
12635 are siblings prior to the current task with incomplete
12636 status.
12638 3. The parent of the task is blocked because it has siblings that should
12639 be done first, or is child of a block grandparent TODO entry."
12641 (if (not org-enforce-todo-dependencies)
12642 t ; if locally turned off don't block
12643 (catch 'dont-block
12644 ;; If this is not a todo state change, or if this entry is already DONE,
12645 ;; do not block
12646 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12647 (member (plist-get change-plist :from)
12648 (cons 'done org-done-keywords))
12649 (member (plist-get change-plist :to)
12650 (cons 'todo org-not-done-keywords))
12651 (not (plist-get change-plist :to)))
12652 (throw 'dont-block t))
12653 ;; If this task has children, and any are undone, it's blocked
12654 (save-excursion
12655 (org-back-to-heading t)
12656 (let ((this-level (funcall outline-level)))
12657 (outline-next-heading)
12658 (let ((child-level (funcall outline-level)))
12659 (while (and (not (eobp))
12660 (> child-level this-level))
12661 ;; this todo has children, check whether they are all
12662 ;; completed
12663 (when (and (not (org-entry-is-done-p))
12664 (org-entry-is-todo-p))
12665 (setq org-block-entry-blocking (org-get-heading))
12666 (throw 'dont-block nil))
12667 (outline-next-heading)
12668 (setq child-level (funcall outline-level))))))
12669 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12670 ;; any previous siblings are undone, it's blocked
12671 (save-excursion
12672 (org-back-to-heading t)
12673 (let* ((pos (point))
12674 (parent-pos (and (org-up-heading-safe) (point))))
12675 (unless parent-pos (throw 'dont-block t)) ; no parent
12676 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12677 (forward-line 1)
12678 (re-search-forward org-not-done-heading-regexp pos t))
12679 (setq org-block-entry-blocking (match-string 0))
12680 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12681 ;; Search further up the hierarchy, to see if an ancestor is blocked
12682 (while t
12683 (goto-char parent-pos)
12684 (unless (looking-at org-not-done-heading-regexp)
12685 (throw 'dont-block t)) ; do not block, parent is not a TODO
12686 (setq pos (point))
12687 (setq parent-pos (and (org-up-heading-safe) (point)))
12688 (unless parent-pos (throw 'dont-block t)) ; no parent
12689 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12690 (forward-line 1)
12691 (re-search-forward org-not-done-heading-regexp pos t)
12692 (setq org-block-entry-blocking (org-get-heading)))
12693 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12695 (defcustom org-track-ordered-property-with-tag nil
12696 "Should the ORDERED property also be shown as a tag?
12697 The ORDERED property decides if an entry should require subtasks to be
12698 completed in sequence. Since a property is not very visible, setting
12699 this option means that toggling the ORDERED property with the command
12700 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12701 not relevant for the behavior, but it makes things more visible.
12703 Note that toggling the tag with tags commands will not change the property
12704 and therefore not influence behavior!
12706 This can be t, meaning the tag ORDERED should be used, It can also be a
12707 string to select a different tag for this task."
12708 :group 'org-todo
12709 :type '(choice
12710 (const :tag "No tracking" nil)
12711 (const :tag "Track with ORDERED tag" t)
12712 (string :tag "Use other tag")))
12714 (defun org-toggle-ordered-property ()
12715 "Toggle the ORDERED property of the current entry.
12716 For better visibility, you can track the value of this property with a tag.
12717 See variable `org-track-ordered-property-with-tag'."
12718 (interactive)
12719 (let* ((t1 org-track-ordered-property-with-tag)
12720 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12721 (save-excursion
12722 (org-back-to-heading)
12723 (if (org-entry-get nil "ORDERED")
12724 (progn
12725 (org-delete-property "ORDERED")
12726 (and tag (org-toggle-tag tag 'off))
12727 (message "Subtasks can be completed in arbitrary order"))
12728 (org-entry-put nil "ORDERED" "t")
12729 (and tag (org-toggle-tag tag 'on))
12730 (message "Subtasks must be completed in sequence")))))
12732 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12733 (defun org-block-todo-from-checkboxes (change-plist)
12734 "Block turning an entry into a TODO, using checkboxes.
12735 This checks whether the current task should be blocked from state
12736 changes because there are unchecked boxes in this entry."
12737 (if (not org-enforce-todo-checkbox-dependencies)
12738 t ; if locally turned off don't block
12739 (catch 'dont-block
12740 ;; If this is not a todo state change, or if this entry is already DONE,
12741 ;; do not block
12742 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12743 (member (plist-get change-plist :from)
12744 (cons 'done org-done-keywords))
12745 (member (plist-get change-plist :to)
12746 (cons 'todo org-not-done-keywords))
12747 (not (plist-get change-plist :to)))
12748 (throw 'dont-block t))
12749 ;; If this task has checkboxes that are not checked, it's blocked
12750 (save-excursion
12751 (org-back-to-heading t)
12752 (let ((beg (point)) end)
12753 (outline-next-heading)
12754 (setq end (point))
12755 (goto-char beg)
12756 (when (org-list-search-forward
12757 (concat (org-item-beginning-re)
12758 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12759 "\\[[- ]\\]")
12760 end t)
12761 (when (boundp 'org-blocked-by-checkboxes)
12762 (setq org-blocked-by-checkboxes t))
12763 (throw 'dont-block nil))))
12764 t))) ; do not block
12766 (defun org-entry-blocked-p ()
12767 "Non-nil if entry at point is blocked."
12768 (and (not (org-entry-get nil "NOBLOCKING"))
12769 (member (org-entry-get nil "TODO") org-not-done-keywords)
12770 (not (run-hook-with-args-until-failure
12771 'org-blocker-hook
12772 (list :type 'todo-state-change
12773 :position (point)
12774 :from 'todo
12775 :to 'done)))))
12777 (defun org-update-statistics-cookies (all)
12778 "Update the statistics cookie, either from TODO or from checkboxes.
12779 This should be called with the cursor in a line with a statistics cookie."
12780 (interactive "P")
12781 (if all
12782 (progn
12783 (org-update-checkbox-count 'all)
12784 (org-map-entries 'org-update-parent-todo-statistics))
12785 (if (not (org-at-heading-p))
12786 (org-update-checkbox-count)
12787 (let ((pos (point-marker))
12788 end l1 l2)
12789 (ignore-errors (org-back-to-heading t))
12790 (if (not (org-at-heading-p))
12791 (org-update-checkbox-count)
12792 (setq l1 (org-outline-level))
12793 (setq end (save-excursion
12794 (outline-next-heading)
12795 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12796 (point)))
12797 (if (and (save-excursion
12798 (re-search-forward
12799 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12800 (not (save-excursion (re-search-forward
12801 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12802 (org-update-checkbox-count)
12803 (if (and l2 (> l2 l1))
12804 (progn
12805 (goto-char end)
12806 (org-update-parent-todo-statistics))
12807 (goto-char pos)
12808 (beginning-of-line 1)
12809 (while (re-search-forward
12810 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12811 (point-at-eol) t)
12812 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12813 (goto-char pos)
12814 (move-marker pos nil)))))
12816 (defvar org-entry-property-inherited-from) ;; defined below
12817 (defun org-update-parent-todo-statistics ()
12818 "Update any statistics cookie in the parent of the current headline.
12819 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12820 the entire subtree and this will travel up the hierarchy and update
12821 statistics everywhere."
12822 (let* ((prop (save-excursion (org-up-heading-safe)
12823 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12824 (recursive (or (not org-hierarchical-todo-statistics)
12825 (and prop (string-match "\\<recursive\\>" prop))))
12826 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12828 (first t)
12829 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12830 level ltoggle l1 new ndel
12831 (cnt-all 0) (cnt-done 0) is-percent kwd
12832 checkbox-beg ov ovs ove cookie-present)
12833 (catch 'exit
12834 (save-excursion
12835 (beginning-of-line 1)
12836 (setq ltoggle (funcall outline-level))
12837 ;; Three situations are to consider:
12839 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12840 ;; to the top-level ancestor on the headline;
12842 ;; 2. If parent has "recursive" property, repeat up to the
12843 ;; headline setting that property, taking inheritance into
12844 ;; account;
12846 ;; 3. Else, move up to direct parent and proceed only once.
12847 (while (and (setq level (org-up-heading-safe))
12848 (or recursive first)
12849 (>= (point) lim))
12850 (setq first nil cookie-present nil)
12851 (unless (and level
12852 (not (string-match
12853 "\\<checkbox\\>"
12854 (downcase (or (org-entry-get nil "COOKIE_DATA")
12855 "")))))
12856 (throw 'exit nil))
12857 (while (re-search-forward box-re (point-at-eol) t)
12858 (setq cnt-all 0 cnt-done 0 cookie-present t)
12859 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12860 (save-match-data
12861 (unless (outline-next-heading) (throw 'exit nil))
12862 (while (and (looking-at org-complex-heading-regexp)
12863 (> (setq l1 (length (match-string 1))) level))
12864 (setq kwd (and (or recursive (= l1 ltoggle))
12865 (match-string 2)))
12866 (if (or (eq org-provide-todo-statistics 'all-headlines)
12867 (and (eq org-provide-todo-statistics t)
12868 (or (member kwd org-done-keywords)))
12869 (and (listp org-provide-todo-statistics)
12870 (stringp (car org-provide-todo-statistics))
12871 (or (member kwd org-provide-todo-statistics)
12872 (member kwd org-done-keywords)))
12873 (and (listp org-provide-todo-statistics)
12874 (listp (car org-provide-todo-statistics))
12875 (or (member kwd (car org-provide-todo-statistics))
12876 (and (member kwd org-done-keywords)
12877 (member kwd (cadr org-provide-todo-statistics))))))
12878 (setq cnt-all (1+ cnt-all))
12879 (and (eq org-provide-todo-statistics t)
12881 (setq cnt-all (1+ cnt-all))))
12882 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12883 (member kwd org-done-keywords))
12884 (and (listp org-provide-todo-statistics)
12885 (listp (car org-provide-todo-statistics))
12886 (member kwd org-done-keywords)
12887 (member kwd (cadr org-provide-todo-statistics)))
12888 (and (listp org-provide-todo-statistics)
12889 (stringp (car org-provide-todo-statistics))
12890 (member kwd org-done-keywords)))
12891 (setq cnt-done (1+ cnt-done)))
12892 (outline-next-heading)))
12893 (setq new
12894 (if is-percent
12895 (format "[%d%%]" (floor (* 100.0 cnt-done)
12896 (max 1 cnt-all)))
12897 (format "[%d/%d]" cnt-done cnt-all))
12898 ndel (- (match-end 0) checkbox-beg))
12899 ;; handle overlays when updating cookie from column view
12900 (when (setq ov (car (overlays-at checkbox-beg)))
12901 (setq ovs (overlay-start ov) ove (overlay-end ov))
12902 (delete-overlay ov))
12903 (goto-char checkbox-beg)
12904 (insert new)
12905 (delete-region (point) (+ (point) ndel))
12906 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12907 (when ov (move-overlay ov ovs ove)))
12908 (when cookie-present
12909 (run-hook-with-args 'org-after-todo-statistics-hook
12910 cnt-done (- cnt-all cnt-done))))))
12911 (run-hooks 'org-todo-statistics-hook)))
12913 (defvar org-after-todo-statistics-hook nil
12914 "Hook that is called after a TODO statistics cookie has been updated.
12915 Each function is called with two arguments: the number of not-done entries
12916 and the number of done entries.
12918 For example, the following function, when added to this hook, will switch
12919 an entry to DONE when all children are done, and back to TODO when new
12920 entries are set to a TODO status. Note that this hook is only called
12921 when there is a statistics cookie in the headline!
12923 \(defun org-summary-todo (n-done n-not-done)
12924 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12925 \(let (org-log-done org-log-states) ; turn off logging
12926 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12929 (defvar org-todo-statistics-hook nil
12930 "Hook that is run whenever Org thinks TODO statistics should be updated.
12931 This hook runs even if there is no statistics cookie present, in which case
12932 `org-after-todo-statistics-hook' would not run.")
12934 (defun org-todo-trigger-tag-changes (state)
12935 "Apply the changes defined in `org-todo-state-tags-triggers'."
12936 (let ((l org-todo-state-tags-triggers)
12937 changes)
12938 (when (or (not state) (equal state ""))
12939 (setq changes (append changes (cdr (assoc "" l)))))
12940 (when (and (stringp state) (> (length state) 0))
12941 (setq changes (append changes (cdr (assoc state l)))))
12942 (when (member state org-not-done-keywords)
12943 (setq changes (append changes (cdr (assoc 'todo l)))))
12944 (when (member state org-done-keywords)
12945 (setq changes (append changes (cdr (assoc 'done l)))))
12946 (dolist (c changes)
12947 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12949 (defun org-local-logging (value)
12950 "Get logging settings from a property VALUE."
12951 ;; Directly set the variables, they are already local.
12952 (setq org-log-done nil
12953 org-log-repeat nil
12954 org-todo-log-states nil)
12955 (dolist (w (org-split-string value))
12956 (let (a)
12957 (cond
12958 ((setq a (assoc w org-startup-options))
12959 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12960 (set (nth 1 a) (nth 2 a))))
12961 ((setq a (org-extract-log-state-settings w))
12962 (and (member (car a) org-todo-keywords-1)
12963 (push a org-todo-log-states)))))))
12965 (defun org-get-todo-sequence-head (kwd)
12966 "Return the head of the TODO sequence to which KWD belongs.
12967 If KWD is not set, check if there is a text property remembering the
12968 right sequence."
12969 (let (p)
12970 (cond
12971 ((not kwd)
12972 (or (get-text-property (point-at-bol) 'org-todo-head)
12973 (progn
12974 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12975 nil (point-at-eol)))
12976 (get-text-property p 'org-todo-head))))
12977 ((not (member kwd org-todo-keywords-1))
12978 (car org-todo-keywords-1))
12979 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12981 (defun org-fast-todo-selection ()
12982 "Fast TODO keyword selection with single keys.
12983 Returns the new TODO keyword, or nil if no state change should occur."
12984 (let* ((fulltable org-todo-key-alist)
12985 (done-keywords org-done-keywords) ;; needed for the faces.
12986 (maxlen (apply 'max (mapcar
12987 (lambda (x)
12988 (if (stringp (car x)) (string-width (car x)) 0))
12989 fulltable)))
12990 (expert nil)
12991 (fwidth (+ maxlen 3 1 3))
12992 (ncol (/ (- (window-width) 4) fwidth))
12993 tg cnt e c tbl
12994 groups ingroup)
12995 (save-excursion
12996 (save-window-excursion
12997 (if expert
12998 (set-buffer (get-buffer-create " *Org todo*"))
12999 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13000 (erase-buffer)
13001 (setq-local org-done-keywords done-keywords)
13002 (setq tbl fulltable cnt 0)
13003 (while (setq e (pop tbl))
13004 (cond
13005 ((equal e '(:startgroup))
13006 (push '() groups) (setq ingroup t)
13007 (unless (= cnt 0)
13008 (setq cnt 0)
13009 (insert "\n"))
13010 (insert "{ "))
13011 ((equal e '(:endgroup))
13012 (setq ingroup nil cnt 0)
13013 (insert "}\n"))
13014 ((equal e '(:newline))
13015 (unless (= cnt 0)
13016 (setq cnt 0)
13017 (insert "\n")
13018 (setq e (car tbl))
13019 (while (equal (car tbl) '(:newline))
13020 (insert "\n")
13021 (setq tbl (cdr tbl)))))
13023 (setq tg (car e) c (cdr e))
13024 (when ingroup (push tg (car groups)))
13025 (setq tg (org-add-props tg nil 'face
13026 (org-get-todo-face tg)))
13027 (when (and (= cnt 0) (not ingroup)) (insert " "))
13028 (insert "[" c "] " tg (make-string
13029 (- fwidth 4 (length tg)) ?\ ))
13030 (when (= (setq cnt (1+ cnt)) ncol)
13031 (insert "\n")
13032 (when ingroup (insert " "))
13033 (setq cnt 0)))))
13034 (insert "\n")
13035 (goto-char (point-min))
13036 (unless expert (org-fit-window-to-buffer))
13037 (message "[a-z..]:Set [SPC]:clear")
13038 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13039 (cond
13040 ((or (= c ?\C-g)
13041 (and (= c ?q) (not (rassoc c fulltable))))
13042 (setq quit-flag t))
13043 ((= c ?\ ) nil)
13044 ((setq e (rassoc c fulltable) tg (car e))
13046 (t (setq quit-flag t)))))))
13048 (defun org-entry-is-todo-p ()
13049 (member (org-get-todo-state) org-not-done-keywords))
13051 (defun org-entry-is-done-p ()
13052 (member (org-get-todo-state) org-done-keywords))
13054 (defun org-get-todo-state ()
13055 "Return the TODO keyword of the current subtree."
13056 (save-excursion
13057 (org-back-to-heading t)
13058 (and (looking-at org-todo-line-regexp)
13059 (match-end 2)
13060 (match-string 2))))
13062 (defun org-at-date-range-p (&optional inactive-ok)
13063 "Non-nil if point is inside a date range.
13065 When optional argument INACTIVE-OK is non-nil, also consider
13066 inactive time ranges.
13068 When this function returns a non-nil value, match data is set
13069 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13070 on INACTIVE-OK."
13071 (interactive)
13072 (save-excursion
13073 (catch 'exit
13074 (let ((pos (point)))
13075 (skip-chars-backward "^[<\r\n")
13076 (skip-chars-backward "<[")
13077 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13078 (>= (match-end 0) pos)
13079 (throw 'exit t))
13080 (skip-chars-backward "^<[\r\n")
13081 (skip-chars-backward "<[")
13082 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13083 (>= (match-end 0) pos)
13084 (throw 'exit t)))
13085 nil)))
13087 (defun org-get-repeat (&optional tagline)
13088 "Check if there is a deadline/schedule with repeater in this entry."
13089 (save-match-data
13090 (save-excursion
13091 (org-back-to-heading t)
13092 (and (re-search-forward (if tagline
13093 (concat tagline "\\s-*" org-repeat-re)
13094 org-repeat-re)
13095 (org-entry-end-position) t)
13096 (match-string-no-properties 1)))))
13098 (defvar org-last-changed-timestamp)
13099 (defvar org-last-inserted-timestamp)
13100 (defvar org-log-post-message)
13101 (defvar org-log-note-purpose)
13102 (defvar org-log-note-how nil)
13103 (defvar org-log-note-extra)
13104 (defun org-auto-repeat-maybe (done-word)
13105 "Check if the current headline contains a repeated time-stamp.
13107 If yes, set TODO state back to what it was and change the base date
13108 of repeating deadline/scheduled time stamps to new date.
13110 This function is run automatically after each state change to a DONE state."
13111 (let* ((repeat (org-get-repeat))
13112 (aa (assoc org-last-state org-todo-kwd-alist))
13113 (interpret (nth 1 aa))
13114 (head (nth 2 aa))
13115 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13116 (msg "Entry repeats: ")
13117 (org-log-done nil)
13118 (org-todo-log-states nil))
13119 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13120 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13121 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13122 org-todo-repeat-to-state)))
13123 (unless (and to-state (member to-state org-todo-keywords-1))
13124 (setq to-state (if (eq interpret 'type) org-last-state head)))
13125 (org-todo to-state))
13126 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13127 (org-entry-put nil "LAST_REPEAT" (format-time-string
13128 (org-time-stamp-format t t))))
13129 (when org-log-repeat
13130 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13131 (memq 'org-add-log-note post-command-hook))
13132 ;; We are already setup for some record.
13133 (when (eq org-log-repeat 'note)
13134 ;; Make sure we take a note, not only a time stamp.
13135 (setq org-log-note-how 'note))
13136 ;; Set up for taking a record.
13137 (org-add-log-setup 'state
13138 (or done-word (car org-done-keywords))
13139 org-last-state
13140 org-log-repeat)))
13141 (org-back-to-heading t)
13142 (org-add-planning-info nil nil 'closed)
13143 (let ((regexp (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13144 org-deadline-time-regexp "\\)\\|\\("
13145 org-ts-regexp "\\)"))
13146 (end (save-excursion (outline-next-heading) (point))))
13147 (while (re-search-forward regexp end t)
13148 (let ((type (cond ((match-end 1) org-scheduled-string)
13149 ((match-end 3) org-deadline-string)
13150 (t "Plain:")))
13151 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13152 (cond
13153 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13154 ;; Time-stamps without a repeater are usually skipped.
13155 ;; However, a SCHEDULED time-stamp without one is
13156 ;; removed, as it is considered as no longer relevant.
13157 (when (equal type org-scheduled-string)
13158 (org-remove-timestamp-with-keyword type)))
13160 (let ((n (string-to-number (match-string 2 ts)))
13161 (what (match-string 3 ts)))
13162 (when (equal what "w") (setq n (* n 7) what "d"))
13163 (when (and (equal what "h")
13164 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13165 ts)))
13166 (user-error
13167 "Cannot repeat in Repeat in %d hour(s) because no hour has \
13168 been set"
13170 ;; Preparation, see if we need to modify the start
13171 ;; date for the change.
13172 (when (match-end 1)
13173 (let ((time (save-match-data (org-time-string-to-time ts))))
13174 (cond
13175 ((equal (match-string 1 ts) ".")
13176 ;; Shift starting date to today
13177 (org-timestamp-change
13178 (- (org-today) (time-to-days time))
13179 'day))
13180 ((equal (match-string 1 ts) "+")
13181 (let ((nshiftmax 10)
13182 (nshift 0))
13183 (while (or (= nshift 0)
13184 (<= (time-to-days time)
13185 (time-to-days (current-time))))
13186 (when (= (cl-incf nshift) nshiftmax)
13187 (or (y-or-n-p
13188 (format "%d repeater intervals were not \
13189 enough to shift date past today. Continue? "
13190 nshift))
13191 (user-error "Abort")))
13192 (org-timestamp-change n (cdr (assoc what whata)))
13193 (org-at-timestamp-p t)
13194 (setq ts (match-string 1))
13195 (setq time
13196 (save-match-data
13197 (org-time-string-to-time ts)))))
13198 (org-timestamp-change (- n) (cdr (assoc what whata)))
13199 ;; Rematch, so that we have everything in place
13200 ;; for the real shift.
13201 (org-at-timestamp-p t)
13202 (setq ts (match-string 1))
13203 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13204 ts)))))
13205 (save-excursion
13206 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13207 (setq msg
13208 (concat
13209 msg type " " org-last-changed-timestamp " "))))))))
13210 (setq org-log-post-message msg)
13211 (message "%s" msg))))
13213 (defun org-show-todo-tree (arg)
13214 "Make a compact tree which shows all headlines marked with TODO.
13215 The tree will show the lines where the regexp matches, and all higher
13216 headlines above the match.
13217 With a \\[universal-argument] prefix, prompt for a regexp to match.
13218 With a numeric prefix N, construct a sparse tree for the Nth element
13219 of `org-todo-keywords-1'."
13220 (interactive "P")
13221 (let ((case-fold-search nil)
13222 (kwd-re
13223 (cond ((null arg) org-not-done-regexp)
13224 ((equal arg '(4))
13225 (let ((kwd
13226 (completing-read "Keyword (or KWD1|KWD2|...): "
13227 (mapcar #'list org-todo-keywords-1))))
13228 (concat "\\("
13229 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13230 "\\)\\>")))
13231 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13232 (regexp-quote (nth (1- (prefix-numeric-value arg))
13233 org-todo-keywords-1)))
13234 (t (user-error "Invalid prefix argument: %s" arg)))))
13235 (message "%d TODO entries found"
13236 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13238 (defun org-deadline (arg &optional time)
13239 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13240 With one universal prefix argument, remove any deadline from the item.
13241 With two universal prefix arguments, prompt for a warning delay.
13242 With argument TIME, set the deadline at the corresponding date. TIME
13243 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13244 (interactive "P")
13245 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13246 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13247 'region-start-level 'region))
13248 org-loop-over-headlines-in-active-region)
13249 (org-map-entries
13250 `(org-deadline ',arg ,time)
13251 org-loop-over-headlines-in-active-region
13252 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13253 (let* ((old-date (org-entry-get nil "DEADLINE"))
13254 (old-date-time (when old-date (org-time-string-to-time old-date)))
13255 (repeater (and old-date
13256 (string-match
13257 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13258 old-date)
13259 (match-string 1 old-date))))
13260 (cond
13261 ((equal arg '(4))
13262 (when (and old-date org-log-redeadline)
13263 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13264 (org-remove-timestamp-with-keyword org-deadline-string)
13265 (message "Item no longer has a deadline."))
13266 ((equal arg '(16))
13267 (save-excursion
13268 (org-back-to-heading t)
13269 (if (re-search-forward
13270 org-deadline-time-regexp
13271 (save-excursion (outline-next-heading) (point)) t)
13272 (let* ((rpl0 (match-string 1))
13273 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13274 (replace-match
13275 (concat org-deadline-string
13276 " <" rpl
13277 (format " -%dd"
13278 (abs
13279 (- (time-to-days
13280 (save-match-data
13281 (org-read-date nil t nil "Warn starting from" old-date-time)))
13282 (time-to-days old-date-time))))
13283 ">") t t))
13284 (user-error "No deadline information to update"))))
13286 (org-add-planning-info 'deadline time 'closed)
13287 (when (and old-date
13288 org-log-redeadline
13289 (not (equal old-date org-last-inserted-timestamp)))
13290 (org-add-log-setup
13291 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13292 (when repeater
13293 (save-excursion
13294 (org-back-to-heading t)
13295 (when (re-search-forward (concat org-deadline-string " "
13296 org-last-inserted-timestamp)
13297 (save-excursion
13298 (outline-next-heading) (point)) t)
13299 (goto-char (1- (match-end 0)))
13300 (insert " " repeater)
13301 (setq org-last-inserted-timestamp
13302 (concat (substring org-last-inserted-timestamp 0 -1)
13303 " " repeater
13304 (substring org-last-inserted-timestamp -1))))))
13305 (message "Deadline on %s" org-last-inserted-timestamp))))))
13307 (defun org-schedule (arg &optional time)
13308 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13309 With one universal prefix argument, remove any scheduling date from the item.
13310 With two universal prefix arguments, prompt for a delay cookie.
13311 With argument TIME, scheduled at the corresponding date. TIME can
13312 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13313 (interactive "P")
13314 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13315 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13316 'region-start-level 'region))
13317 org-loop-over-headlines-in-active-region)
13318 (org-map-entries
13319 `(org-schedule ',arg ,time)
13320 org-loop-over-headlines-in-active-region
13321 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13322 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13323 (old-date-time (when old-date (org-time-string-to-time old-date)))
13324 (repeater (and old-date
13325 (string-match
13326 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13327 old-date)
13328 (match-string 1 old-date))))
13329 (cond
13330 ((equal arg '(4))
13331 (progn
13332 (when (and old-date org-log-reschedule)
13333 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13334 (org-remove-timestamp-with-keyword org-scheduled-string)
13335 (message "Item is no longer scheduled.")))
13336 ((equal arg '(16))
13337 (save-excursion
13338 (org-back-to-heading t)
13339 (if (re-search-forward
13340 org-scheduled-time-regexp
13341 (save-excursion (outline-next-heading) (point)) t)
13342 (let* ((rpl0 (match-string 1))
13343 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13344 (replace-match
13345 (concat org-scheduled-string
13346 " <" rpl
13347 (format " -%dd"
13348 (abs
13349 (- (time-to-days
13350 (save-match-data
13351 (org-read-date nil t nil "Delay until" old-date-time)))
13352 (time-to-days old-date-time))))
13353 ">") t t))
13354 (user-error "No scheduled information to update"))))
13356 (org-add-planning-info 'scheduled time 'closed)
13357 (when (and old-date
13358 org-log-reschedule
13359 (not (equal old-date org-last-inserted-timestamp)))
13360 (org-add-log-setup
13361 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13362 (when repeater
13363 (save-excursion
13364 (org-back-to-heading t)
13365 (when (re-search-forward (concat org-scheduled-string " "
13366 org-last-inserted-timestamp)
13367 (save-excursion
13368 (outline-next-heading) (point)) t)
13369 (goto-char (1- (match-end 0)))
13370 (insert " " repeater)
13371 (setq org-last-inserted-timestamp
13372 (concat (substring org-last-inserted-timestamp 0 -1)
13373 " " repeater
13374 (substring org-last-inserted-timestamp -1))))))
13375 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13377 (defun org-get-scheduled-time (pom &optional inherit)
13378 "Get the scheduled time as a time tuple, of a format suitable
13379 for calling org-schedule with, or if there is no scheduling,
13380 returns nil."
13381 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13382 (when time
13383 (apply 'encode-time (org-parse-time-string time)))))
13385 (defun org-get-deadline-time (pom &optional inherit)
13386 "Get the deadline as a time tuple, of a format suitable for
13387 calling org-deadline with, or if there is no scheduling, returns
13388 nil."
13389 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13390 (when time
13391 (apply 'encode-time (org-parse-time-string time)))))
13393 (defun org-remove-timestamp-with-keyword (keyword)
13394 "Remove all time stamps with KEYWORD in the current entry."
13395 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13396 beg)
13397 (save-excursion
13398 (org-back-to-heading t)
13399 (setq beg (point))
13400 (outline-next-heading)
13401 (while (re-search-backward re beg t)
13402 (replace-match "")
13403 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13404 (equal (char-before) ?\ ))
13405 (backward-delete-char 1)
13406 (when (string-match "^[ \t]*$" (buffer-substring
13407 (point-at-bol) (point-at-eol)))
13408 (delete-region (point-at-bol)
13409 (min (point-max) (1+ (point-at-eol))))))))))
13411 (defvar org-time-was-given) ; dynamically scoped parameter
13412 (defvar org-end-time-was-given) ; dynamically scoped parameter
13414 (defun org-at-planning-p ()
13415 "Non-nil when point is on a planning info line."
13416 ;; This is as accurate and faster than `org-element-at-point' since
13417 ;; planning info location is fixed in the section.
13418 (org-with-wide-buffer
13419 (beginning-of-line)
13420 (and (org-looking-at-p org-planning-line-re)
13421 (eq (point)
13422 (ignore-errors
13423 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13424 (org-back-to-heading t)
13425 (org-with-limited-levels (org-back-to-heading t)))
13426 (line-beginning-position 2))))))
13428 (defun org-add-planning-info (what &optional time &rest remove)
13429 "Insert new timestamp with keyword in the planning line.
13430 WHAT indicates what kind of time stamp to add. It is a symbol
13431 among `closed', `deadline', `scheduled' and nil. TIME indicates
13432 the time to use. If none is given, the user is prompted for
13433 a date. REMOVE indicates what kind of entries to remove. An old
13434 WHAT entry will also be removed."
13435 (let (org-time-was-given org-end-time-was-given default-time default-input)
13436 (catch 'exit
13437 (when (and (memq what '(scheduled deadline))
13438 (or (not time)
13439 (and (stringp time)
13440 (string-match "^[-+]+[0-9]" time))))
13441 ;; Try to get a default date/time from existing timestamp
13442 (save-excursion
13443 (org-back-to-heading t)
13444 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13445 (when (re-search-forward (if (eq what 'scheduled)
13446 org-scheduled-time-regexp
13447 org-deadline-time-regexp)
13448 end t)
13449 (setq ts (match-string 1)
13450 default-time (apply 'encode-time (org-parse-time-string ts))
13451 default-input (and ts (org-get-compact-tod ts)))))))
13452 (when what
13453 (setq time
13454 (if (stringp time)
13455 ;; This is a string (relative or absolute), set
13456 ;; proper date.
13457 (apply #'encode-time
13458 (org-read-date-analyze
13459 time default-time (decode-time default-time)))
13460 ;; If necessary, get the time from the user
13461 (or time (org-read-date nil 'to-time nil nil
13462 default-time default-input)))))
13464 (org-with-wide-buffer
13465 (org-back-to-heading t)
13466 (forward-line)
13467 (unless (bolp) (insert "\n"))
13468 (cond ((org-looking-at-p org-planning-line-re)
13469 ;; Move to current indentation.
13470 (skip-chars-forward " \t")
13471 ;; Check if we have to remove something.
13472 (dolist (type (if what (cons what remove) remove))
13473 (save-excursion
13474 (when (re-search-forward
13475 (cl-case type
13476 (closed org-closed-time-regexp)
13477 (deadline org-deadline-time-regexp)
13478 (scheduled org-scheduled-time-regexp)
13479 (otherwise
13480 (error "Invalid planning type: %s" type)))
13481 (line-end-position) t)
13482 ;; Delete until next keyword or end of line.
13483 (delete-region
13484 (match-beginning 0)
13485 (if (re-search-forward org-keyword-time-not-clock-regexp
13486 (line-end-position)
13488 (match-beginning 0)
13489 (line-end-position))))))
13490 ;; If there is nothing more to add and no more keyword
13491 ;; is left, remove the line completely.
13492 (if (and (org-looking-at-p "[ \t]*$") (not what))
13493 (delete-region (line-beginning-position)
13494 (line-beginning-position 2))
13495 ;; If we removed last keyword, do not leave trailing
13496 ;; white space at the end of line.
13497 (let ((p (point)))
13498 (save-excursion
13499 (end-of-line)
13500 (unless (= (skip-chars-backward " \t" p) 0)
13501 (delete-region (point) (line-end-position)))))))
13502 ((not what) (throw 'exit nil)) ; Nothing to do.
13503 (t (insert-before-markers "\n")
13504 (backward-char 1)
13505 (when org-adapt-indentation
13506 (org-indent-to-column (1+ (org-outline-level))))))
13507 (when what
13508 ;; Insert planning keyword.
13509 (insert (cl-case what
13510 (closed org-closed-string)
13511 (deadline org-deadline-string)
13512 (scheduled org-scheduled-string)
13513 (otherwise (error "Invalid planning type: %s" what)))
13514 " ")
13515 ;; Insert associated timestamp.
13516 (let ((ts (org-insert-time-stamp
13517 time
13518 (or org-time-was-given
13519 (and (eq what 'closed) org-log-done-with-time))
13520 (eq what 'closed)
13521 nil nil (list org-end-time-was-given))))
13522 (unless (eolp) (insert " "))
13523 ts))))))
13525 (defvar org-log-note-marker (make-marker)
13526 "Marker pointing at the entry where the note is to be inserted.")
13527 (defvar org-log-note-purpose nil)
13528 (defvar org-log-note-state nil)
13529 (defvar org-log-note-previous-state nil)
13530 (defvar org-log-note-extra nil)
13531 (defvar org-log-note-window-configuration nil)
13532 (defvar org-log-note-return-to (make-marker))
13533 (defvar org-log-note-effective-time nil
13534 "Remembered current time so that dynamically scoped
13535 `org-extend-today-until' affects timestamps in state change log")
13537 (defvar org-log-post-message nil
13538 "Message to be displayed after a log note has been stored.
13539 The auto-repeater uses this.")
13541 (defun org-add-note ()
13542 "Add a note to the current entry.
13543 This is done in the same way as adding a state change note."
13544 (interactive)
13545 (org-add-log-setup 'note))
13547 (defun org-log-beginning (&optional create)
13548 "Return expected start of log notes in current entry.
13549 When optional argument CREATE is non-nil, the function creates
13550 a drawer to store notes, if necessary. Returned position ignores
13551 narrowing."
13552 (org-with-wide-buffer
13553 (let ((drawer (org-log-into-drawer)))
13554 (cond
13555 (drawer
13556 (org-end-of-meta-data)
13557 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13558 (end (if (org-at-heading-p) (point)
13559 (save-excursion (outline-next-heading) (point))))
13560 (case-fold-search t))
13561 (catch 'exit
13562 ;; Try to find existing drawer.
13563 (while (re-search-forward regexp end t)
13564 (let ((element (org-element-at-point)))
13565 (when (eq (org-element-type element) 'drawer)
13566 (let ((cend (org-element-property :contents-end element)))
13567 (when (and (not org-log-states-order-reversed) cend)
13568 (goto-char cend)))
13569 (throw 'exit nil))))
13570 ;; No drawer found. Create one, if permitted.
13571 (when create
13572 (unless (bolp) (insert "\n"))
13573 (let ((beg (point)))
13574 (insert ":" drawer ":\n:END:\n")
13575 (org-indent-region beg (point)))
13576 (end-of-line -1)))))
13578 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13579 (skip-chars-forward " \t\n")
13580 (beginning-of-line)
13581 (unless org-log-states-order-reversed
13582 (org-skip-over-state-notes)
13583 (skip-chars-backward " \t\n")
13584 (forward-line)))))
13585 (if (bolp) (point) (line-beginning-position 2))))
13587 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13588 "Set up the post command hook to take a note.
13589 If this is about to TODO state change, the new state is expected in STATE.
13590 HOW is an indicator what kind of note should be created.
13591 EXTRA is additional text that will be inserted into the notes buffer."
13592 (move-marker org-log-note-marker (point))
13593 (setq org-log-note-purpose purpose
13594 org-log-note-state state
13595 org-log-note-previous-state prev-state
13596 org-log-note-how how
13597 org-log-note-extra extra
13598 org-log-note-effective-time (org-current-effective-time))
13599 (add-hook 'post-command-hook 'org-add-log-note 'append))
13601 (defun org-skip-over-state-notes ()
13602 "Skip past the list of State notes in an entry."
13603 (when (ignore-errors (goto-char (org-in-item-p)))
13604 (let* ((struct (org-list-struct))
13605 (prevs (org-list-prevs-alist struct))
13606 (regexp
13607 (concat "[ \t]*- +"
13608 (replace-regexp-in-string
13609 " +" " +"
13610 (org-replace-escapes
13611 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13612 `(("%d" . ,org-ts-regexp-inactive)
13613 ("%D" . ,org-ts-regexp)
13614 ("%s" . "\"\\S-+\"")
13615 ("%S" . "\"\\S-+\"")
13616 ("%t" . ,org-ts-regexp-inactive)
13617 ("%T" . ,org-ts-regexp)
13618 ("%u" . ".*?")
13619 ("%U" . ".*?")))))))
13620 (while (org-looking-at-p regexp)
13621 (goto-char (or (org-list-get-next-item (point) struct prevs)
13622 (org-list-get-item-end (point) struct)))))))
13624 (defun org-add-log-note (&optional _purpose)
13625 "Pop up a window for taking a note, and add this note later."
13626 (remove-hook 'post-command-hook 'org-add-log-note)
13627 (setq org-log-note-window-configuration (current-window-configuration))
13628 (delete-other-windows)
13629 (move-marker org-log-note-return-to (point))
13630 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13631 (goto-char org-log-note-marker)
13632 (org-switch-to-buffer-other-window "*Org Note*")
13633 (erase-buffer)
13634 (if (memq org-log-note-how '(time state))
13635 (let (current-prefix-arg) (org-store-log-note))
13636 (let ((org-inhibit-startup t)) (org-mode))
13637 (insert (format "# Insert note for %s.
13638 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13639 (cond
13640 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13641 ((eq org-log-note-purpose 'done) "closed todo item")
13642 ((eq org-log-note-purpose 'state)
13643 (format "state change from \"%s\" to \"%s\""
13644 (or org-log-note-previous-state "")
13645 (or org-log-note-state "")))
13646 ((eq org-log-note-purpose 'reschedule)
13647 "rescheduling")
13648 ((eq org-log-note-purpose 'delschedule)
13649 "no longer scheduled")
13650 ((eq org-log-note-purpose 'redeadline)
13651 "changing deadline")
13652 ((eq org-log-note-purpose 'deldeadline)
13653 "removing deadline")
13654 ((eq org-log-note-purpose 'refile)
13655 "refiling")
13656 ((eq org-log-note-purpose 'note)
13657 "this entry")
13658 (t (error "This should not happen")))))
13659 (when org-log-note-extra (insert org-log-note-extra))
13660 (setq-local org-finish-function 'org-store-log-note)
13661 (run-hooks 'org-log-buffer-setup-hook)))
13663 (defvar org-note-abort nil) ; dynamically scoped
13664 (defun org-store-log-note ()
13665 "Finish taking a log note, and insert it to where it belongs."
13666 (let ((txt (prog1 (buffer-string)
13667 (kill-buffer)))
13668 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13669 lines)
13670 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13671 (setq txt (replace-match "" t t txt)))
13672 (when (string-match "\\s-+\\'" txt)
13673 (setq txt (replace-match "" t t txt)))
13674 (setq lines (org-split-string txt "\n"))
13675 (when (org-string-nw-p note)
13676 (setq note
13677 (org-replace-escapes
13678 note
13679 (list (cons "%u" (user-login-name))
13680 (cons "%U" user-full-name)
13681 (cons "%t" (format-time-string
13682 (org-time-stamp-format 'long 'inactive)
13683 org-log-note-effective-time))
13684 (cons "%T" (format-time-string
13685 (org-time-stamp-format 'long nil)
13686 org-log-note-effective-time))
13687 (cons "%d" (format-time-string
13688 (org-time-stamp-format nil 'inactive)
13689 org-log-note-effective-time))
13690 (cons "%D" (format-time-string
13691 (org-time-stamp-format nil nil)
13692 org-log-note-effective-time))
13693 (cons "%s" (cond
13694 ((not org-log-note-state) "")
13695 ((org-string-match-p org-ts-regexp
13696 org-log-note-state)
13697 (format "\"[%s]\""
13698 (substring org-log-note-state 1 -1)))
13699 (t (format "\"%s\"" org-log-note-state))))
13700 (cons "%S"
13701 (cond
13702 ((not org-log-note-previous-state) "")
13703 ((org-string-match-p org-ts-regexp
13704 org-log-note-previous-state)
13705 (format "\"[%s]\""
13706 (substring
13707 org-log-note-previous-state 1 -1)))
13708 (t (format "\"%s\""
13709 org-log-note-previous-state)))))))
13710 (when lines (setq note (concat note " \\\\")))
13711 (push note lines))
13712 (when (and lines (not (or current-prefix-arg org-note-abort)))
13713 (with-current-buffer (marker-buffer org-log-note-marker)
13714 (org-with-wide-buffer
13715 ;; Find location for the new note.
13716 (goto-char org-log-note-marker)
13717 (set-marker org-log-note-marker nil)
13718 (goto-char (org-log-beginning t))
13719 ;; Make sure point is at the beginning of an empty line.
13720 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13721 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13722 ;; In an existing list, add a new item at the top level.
13723 ;; Otherwise, indent line like a regular one.
13724 (let ((itemp (org-in-item-p)))
13725 (if itemp
13726 (org-indent-line-to
13727 (let ((struct (save-excursion
13728 (goto-char itemp) (org-list-struct))))
13729 (org-list-get-ind (org-list-get-top-point struct) struct)))
13730 (org-indent-line)))
13731 (insert (org-list-bullet-string "-") (pop lines))
13732 (let ((ind (org-list-item-body-column (line-beginning-position))))
13733 (dolist (line lines)
13734 (insert "\n")
13735 (org-indent-line-to ind)
13736 (insert line)))
13737 (message "Note stored")
13738 (org-back-to-heading t)
13739 (org-cycle-hide-drawers 'children))
13740 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13741 ;; from within `org-add-log-note' because `buffer-undo-list'
13742 ;; is then modified outside of `org-with-remote-undo'.
13743 (when (eq this-command 'org-agenda-todo)
13744 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13745 ;; Don't add undo information when called from `org-agenda-todo'.
13746 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13747 (set-window-configuration org-log-note-window-configuration)
13748 (with-current-buffer (marker-buffer org-log-note-return-to)
13749 (goto-char org-log-note-return-to))
13750 (move-marker org-log-note-return-to nil)
13751 (when org-log-post-message (message "%s" org-log-post-message))))
13753 (defun org-remove-empty-drawer-at (pos)
13754 "Remove an empty drawer at position POS.
13755 POS may also be a marker."
13756 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13757 (org-with-wide-buffer
13758 (goto-char pos)
13759 (let ((drawer (org-element-at-point)))
13760 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13761 (not (org-element-property :contents-begin drawer)))
13762 (delete-region (org-element-property :begin drawer)
13763 (progn (goto-char (org-element-property :end drawer))
13764 (skip-chars-backward " \r\t\n")
13765 (forward-line)
13766 (point))))))))
13768 (defvar org-ts-type nil)
13769 (defun org-sparse-tree (&optional arg type)
13770 "Create a sparse tree, prompt for the details.
13771 This command can create sparse trees. You first need to select the type
13772 of match used to create the tree:
13774 t Show all TODO entries.
13775 T Show entries with a specific TODO keyword.
13776 m Show entries selected by a tags/property match.
13777 p Enter a property name and its value (both with completion on existing
13778 names/values) and show entries with that property.
13779 r Show entries matching a regular expression (`/' can be used as well).
13780 b Show deadlines and scheduled items before a date.
13781 a Show deadlines and scheduled items after a date.
13782 d Show deadlines due within `org-deadline-warning-days'.
13783 D Show deadlines and scheduled items between a date range."
13784 (interactive "P")
13785 (setq type (or type org-sparse-tree-default-date-type))
13786 (setq org-ts-type type)
13787 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13788 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13789 \[c]ycle through date types: %s"
13790 (cl-case type
13791 (all "all timestamps")
13792 (scheduled "only scheduled")
13793 (deadline "only deadline")
13794 (active "only active timestamps")
13795 (inactive "only inactive timestamps")
13796 (closed "with a closed time-stamp")
13797 (otherwise "scheduled/deadline")))
13798 (let ((answer (read-char-exclusive)))
13799 (cl-case answer
13801 (org-sparse-tree
13803 (cadr
13804 (memq type '(nil all scheduled deadline active inactive closed)))))
13805 (?d (call-interactively 'org-check-deadlines))
13806 (?b (call-interactively 'org-check-before-date))
13807 (?a (call-interactively 'org-check-after-date))
13808 (?D (call-interactively 'org-check-dates-range))
13809 (?t (call-interactively 'org-show-todo-tree))
13810 (?T (org-show-todo-tree '(4)))
13811 (?m (call-interactively 'org-match-sparse-tree))
13812 ((?p ?P)
13813 (let* ((kwd (completing-read
13814 "Property: " (mapcar #'list (org-buffer-property-keys))))
13815 (value (completing-read
13816 "Value: " (mapcar #'list (org-property-values kwd)))))
13817 (unless (string-match "\\`{.*}\\'" value)
13818 (setq value (concat "\"" value "\"")))
13819 (org-match-sparse-tree arg (concat kwd "=" value))))
13820 ((?r ?R ?/) (call-interactively 'org-occur))
13821 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13823 (defvar-local org-occur-highlights nil
13824 "List of overlays used for occur matches.")
13825 (defvar-local org-occur-parameters nil
13826 "Parameters of the active org-occur calls.
13827 This is a list, each call to org-occur pushes as cons cell,
13828 containing the regular expression and the callback, onto the list.
13829 The list can contain several entries if `org-occur' has been called
13830 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13831 will only contain one set of parameters. When the highlights are
13832 removed (for example with `C-c C-c', or with the next edit (depending
13833 on `org-remove-highlights-with-change'), this variable is emptied
13834 as well.")
13836 (defun org-occur (regexp &optional keep-previous callback)
13837 "Make a compact tree which shows all matches of REGEXP.
13838 The tree will show the lines where the regexp matches, and all higher
13839 headlines above the match. It will also show the heading after the match,
13840 to make sure editing the matching entry is easy.
13841 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13842 call to `org-occur' will be kept, to allow stacking of calls to this
13843 command.
13844 If CALLBACK is non-nil, it is a function which is called to confirm
13845 that the match should indeed be shown."
13846 (interactive "sRegexp: \nP")
13847 (when (equal regexp "")
13848 (user-error "Regexp cannot be empty"))
13849 (unless keep-previous
13850 (org-remove-occur-highlights nil nil t))
13851 (push (cons regexp callback) org-occur-parameters)
13852 (let ((cnt 0))
13853 (save-excursion
13854 (goto-char (point-min))
13855 (when (or (not keep-previous) ; do not want to keep
13856 (not org-occur-highlights)) ; no previous matches
13857 ;; hide everything
13858 (org-overview))
13859 (while (re-search-forward regexp nil t)
13860 (backward-char) ;; FIXME: Match timestamps at the end of a headline
13861 (when (or (not callback)
13862 (save-match-data (funcall callback)))
13863 (setq cnt (1+ cnt))
13864 (when org-highlight-sparse-tree-matches
13865 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13866 (org-show-context 'occur-tree))))
13867 (when org-remove-highlights-with-change
13868 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13869 nil 'local))
13870 (unless org-sparse-tree-open-archived-trees
13871 (org-hide-archived-subtrees (point-min) (point-max)))
13872 (run-hooks 'org-occur-hook)
13873 (when (org-called-interactively-p 'interactive)
13874 (message "%d match(es) for regexp %s" cnt regexp))
13875 cnt))
13877 (defun org-occur-next-match (&optional n _reset)
13878 "Function for `next-error-function' to find sparse tree matches.
13879 N is the number of matches to move, when negative move backwards.
13880 This function always goes back to the starting point when no
13881 match is found."
13882 (let* ((limit (if (< n 0) (point-min) (point-max)))
13883 (search-func (if (< n 0)
13884 'previous-single-char-property-change
13885 'next-single-char-property-change))
13886 (n (abs n))
13887 (pos (point))
13889 (catch 'exit
13890 (while (setq p1 (funcall search-func (point) 'org-type))
13891 (when (equal p1 limit)
13892 (goto-char pos)
13893 (user-error "No more matches"))
13894 (when (equal (get-char-property p1 'org-type) 'org-occur)
13895 (setq n (1- n))
13896 (when (= n 0)
13897 (goto-char p1)
13898 (throw 'exit (point))))
13899 (goto-char p1))
13900 (goto-char p1)
13901 (user-error "No more matches"))))
13903 (defun org-show-context (&optional key)
13904 "Make sure point and context are visible.
13905 Optional argument KEY, when non-nil, is a symbol. See
13906 `org-show-context-detail' for allowed values and how much is to
13907 be shown."
13908 (org-show-set-visibility
13909 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13910 ((cdr (assq key org-show-context-detail)))
13911 (t (cdr (assq 'default org-show-context-detail))))))
13913 (defun org-show-set-visibility (detail)
13914 "Set visibility around point according to DETAIL.
13915 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13916 `tree', `canonical' or t. See `org-show-context-detail' for more
13917 information."
13918 (unless (org-before-first-heading-p)
13919 ;; Show current heading and possibly its entry, following headline
13920 ;; or all children.
13921 (if (and (org-at-heading-p) (not (eq detail 'local)))
13922 (org-flag-heading nil)
13923 (org-show-entry)
13924 (org-with-limited-levels
13925 (cl-case detail
13926 ((tree canonical t) (org-show-children))
13927 ((nil minimal ancestors))
13928 (t (save-excursion
13929 (outline-next-heading)
13930 (org-flag-heading nil))))))
13931 ;; Show all siblings.
13932 (when (eq detail 'lineage) (org-show-siblings))
13933 ;; Show ancestors, possibly with their children.
13934 (when (memq detail '(ancestors lineage tree canonical t))
13935 (save-excursion
13936 (while (org-up-heading-safe)
13937 (org-flag-heading nil)
13938 (when (memq detail '(canonical t)) (org-show-entry))
13939 (when (memq detail '(tree canonical t)) (org-show-children)))))))
13941 (defvar org-reveal-start-hook nil
13942 "Hook run before revealing a location.")
13944 (defun org-reveal (&optional siblings)
13945 "Show current entry, hierarchy above it, and the following headline.
13947 This can be used to show a consistent set of context around
13948 locations exposed with `org-show-context'.
13950 With optional argument SIBLINGS, on each level of the hierarchy all
13951 siblings are shown. This repairs the tree structure to what it would
13952 look like when opened with hierarchical calls to `org-cycle'.
13954 With double optional argument \\[universal-argument] \\[universal-argument], \
13955 go to the parent and show the
13956 entire tree."
13957 (interactive "P")
13958 (run-hooks 'org-reveal-start-hook)
13959 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13960 ((equal siblings '(16))
13961 (save-excursion
13962 (when (org-up-heading-safe)
13963 (org-show-subtree)
13964 (run-hook-with-args 'org-cycle-hook 'subtree))))
13965 (t (org-show-set-visibility 'lineage))))
13967 (defun org-highlight-new-match (beg end)
13968 "Highlight from BEG to END and mark the highlight is an occur headline."
13969 (let ((ov (make-overlay beg end)))
13970 (overlay-put ov 'face 'secondary-selection)
13971 (overlay-put ov 'org-type 'org-occur)
13972 (push ov org-occur-highlights)))
13974 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13975 "Remove the occur highlights from the buffer.
13976 BEG and END are ignored. If NOREMOVE is nil, remove this function
13977 from the `before-change-functions' in the current buffer."
13978 (interactive)
13979 (unless org-inhibit-highlight-removal
13980 (mapc #'delete-overlay org-occur-highlights)
13981 (setq org-occur-highlights nil)
13982 (setq org-occur-parameters nil)
13983 (unless noremove
13984 (remove-hook 'before-change-functions
13985 'org-remove-occur-highlights 'local))))
13987 ;;;; Priorities
13989 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13990 "Regular expression matching the priority indicator.")
13992 (defvar org-remove-priority-next-time nil)
13994 (defun org-priority-up ()
13995 "Increase the priority of the current item."
13996 (interactive)
13997 (org-priority 'up))
13999 (defun org-priority-down ()
14000 "Decrease the priority of the current item."
14001 (interactive)
14002 (org-priority 'down))
14004 (defun org-priority (&optional action _show)
14005 "Change the priority of an item.
14006 ACTION can be `set', `up', `down', or a character."
14007 (interactive "P")
14008 (if (equal action '(4))
14009 (org-show-priority)
14010 (unless org-enable-priority-commands
14011 (user-error "Priority commands are disabled"))
14012 (setq action (or action 'set))
14013 (let (current new news have remove)
14014 (save-excursion
14015 (org-back-to-heading t)
14016 (when (looking-at org-priority-regexp)
14017 (setq current (string-to-char (match-string 2))
14018 have t))
14019 (cond
14020 ((eq action 'remove)
14021 (setq remove t new ?\ ))
14022 ((or (eq action 'set)
14023 (if (featurep 'xemacs) (characterp action) (integerp action)))
14024 (if (not (eq action 'set))
14025 (setq new action)
14026 (message "Priority %c-%c, SPC to remove: "
14027 org-highest-priority org-lowest-priority)
14028 (save-match-data
14029 (setq new (read-char-exclusive))))
14030 (when (and (= (upcase org-highest-priority) org-highest-priority)
14031 (= (upcase org-lowest-priority) org-lowest-priority))
14032 (setq new (upcase new)))
14033 (cond ((equal new ?\ ) (setq remove t))
14034 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14035 (user-error "Priority must be between `%c' and `%c'"
14036 org-highest-priority org-lowest-priority))))
14037 ((eq action 'up)
14038 (setq new (if have
14039 (1- current) ; normal cycling
14040 ;; last priority was empty
14041 (if (eq last-command this-command)
14042 org-lowest-priority ; wrap around empty to lowest
14043 ;; default
14044 (if org-priority-start-cycle-with-default
14045 org-default-priority
14046 (1- org-default-priority))))))
14047 ((eq action 'down)
14048 (setq new (if have
14049 (1+ current) ; normal cycling
14050 ;; last priority was empty
14051 (if (eq last-command this-command)
14052 org-highest-priority ; wrap around empty to highest
14053 ;; default
14054 (if org-priority-start-cycle-with-default
14055 org-default-priority
14056 (1+ org-default-priority))))))
14057 (t (user-error "Invalid action")))
14058 (when (or (< (upcase new) org-highest-priority)
14059 (> (upcase new) org-lowest-priority))
14060 (if (and (memq action '(up down))
14061 (not have) (not (eq last-command this-command)))
14062 ;; `new' is from default priority
14063 (error
14064 "The default can not be set, see `org-default-priority' why")
14065 ;; normal cycling: `new' is beyond highest/lowest priority
14066 ;; and is wrapped around to the empty priority
14067 (setq remove t)))
14068 (setq news (format "%c" new))
14069 (if have
14070 (if remove
14071 (replace-match "" t t nil 1)
14072 (replace-match news t t nil 2))
14073 (if remove
14074 (user-error "No priority cookie found in line")
14075 (let ((case-fold-search nil))
14076 (looking-at org-todo-line-regexp))
14077 (if (match-end 2)
14078 (progn
14079 (goto-char (match-end 2))
14080 (insert " [#" news "]"))
14081 (goto-char (match-beginning 3))
14082 (insert "[#" news "] "))))
14083 (org-set-tags nil 'align))
14084 (if remove
14085 (message "Priority removed")
14086 (message "Priority of current item set to %s" news)))))
14088 (defun org-show-priority ()
14089 "Show the priority of the current item.
14090 This priority is composed of the main priority given with the [#A] cookies,
14091 and by additional input from the age of a schedules or deadline entry."
14092 (interactive)
14093 (let ((pri (if (eq major-mode 'org-agenda-mode)
14094 (org-get-at-bol 'priority)
14095 (save-excursion
14096 (save-match-data
14097 (beginning-of-line)
14098 (and (looking-at org-heading-regexp)
14099 (org-get-priority (match-string 0))))))))
14100 (message "Priority is %d" (if pri pri -1000))))
14102 (defun org-get-priority (s)
14103 "Find priority cookie and return priority."
14104 (save-match-data
14105 (if (functionp org-get-priority-function)
14106 (funcall org-get-priority-function)
14107 (if (not (string-match org-priority-regexp s))
14108 (* 1000 (- org-lowest-priority org-default-priority))
14109 (* 1000 (- org-lowest-priority
14110 (string-to-char (match-string 2 s))))))))
14112 ;;;; Tags
14114 (defvar org-agenda-archives-mode)
14115 (defvar org-map-continue-from nil
14116 "Position from where mapping should continue.
14117 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14119 (defvar org-scanner-tags nil
14120 "The current tag list while the tags scanner is running.")
14122 (defvar org-trust-scanner-tags nil
14123 "Should `org-get-tags-at' use the tags for the scanner.
14124 This is for internal dynamical scoping only.
14125 When this is non-nil, the function `org-get-tags-at' will return the value
14126 of `org-scanner-tags' instead of building the list by itself. This
14127 can lead to large speed-ups when the tags scanner is used in a file with
14128 many entries, and when the list of tags is retrieved, for example to
14129 obtain a list of properties. Building the tags list for each entry in such
14130 a file becomes an N^2 operation - but with this variable set, it scales
14131 as N.")
14133 (defvar org--matcher-tags-todo-only nil)
14135 (defun org-scan-tags (action matcher todo-only &optional start-level)
14136 "Scan headline tags with inheritance and produce output ACTION.
14138 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14139 or `agenda' to produce an entry list for an agenda view. It can also be
14140 a Lisp form or a function that should be called at each matched headline, in
14141 this case the return value is a list of all return values from these calls.
14143 MATCHER is a function accepting three arguments, returning
14144 a non-nil value whenever a given set of tags qualifies a headline
14145 for inclusion. See `org-make-tags-matcher' for more information.
14146 As a special case, it can also be set to t (respectively nil) in
14147 order to match all (respectively none) headline.
14149 When TODO-ONLY is non-nil, only lines with a not-done TODO
14150 keyword are included in the output.
14152 START-LEVEL can be a string with asterisks, reducing the scope to
14153 headlines matching this string."
14154 (require 'org-agenda)
14155 (let* ((re (concat "^"
14156 (if start-level
14157 ;; Get the correct level to match
14158 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14159 org-outline-regexp)
14160 " *\\(\\<\\("
14161 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14162 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14163 (props (list 'face 'default
14164 'done-face 'org-agenda-done
14165 'undone-face 'default
14166 'mouse-face 'highlight
14167 'org-not-done-regexp org-not-done-regexp
14168 'org-todo-regexp org-todo-regexp
14169 'org-complex-heading-regexp org-complex-heading-regexp
14170 'help-echo
14171 (format "mouse-2 or RET jump to org file %s"
14172 (abbreviate-file-name
14173 (or (buffer-file-name (buffer-base-buffer))
14174 (buffer-name (buffer-base-buffer)))))))
14175 (org-map-continue-from nil)
14176 lspos tags tags-list
14177 (tags-alist (list (cons 0 org-file-tags)))
14178 (llast 0) rtn rtn1 level category i txt
14179 todo marker entry priority
14180 ts-date ts-date-type ts-date-pair)
14181 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14182 (setq action (list 'lambda nil action)))
14183 (save-excursion
14184 (goto-char (point-min))
14185 (when (eq action 'sparse-tree)
14186 (org-overview)
14187 (org-remove-occur-highlights))
14188 (while (let (case-fold-search)
14189 (re-search-forward re nil t))
14190 (setq org-map-continue-from nil)
14191 (catch :skip
14192 (setq todo
14193 ;; TODO: is the 1-2 difference a bug?
14194 (when (match-end 1) (org-match-string-no-properties 2))
14195 tags (when (match-end 4) (org-match-string-no-properties 4)))
14196 (goto-char (setq lspos (match-beginning 0)))
14197 (setq level (org-reduced-level (org-outline-level))
14198 category (org-get-category))
14199 (when (eq action 'agenda)
14200 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14201 ts-date (car ts-date-pair)
14202 ts-date-type (cdr ts-date-pair)))
14203 (setq i llast llast level)
14204 ;; remove tag lists from same and sublevels
14205 (while (>= i level)
14206 (when (setq entry (assoc i tags-alist))
14207 (setq tags-alist (delete entry tags-alist)))
14208 (setq i (1- i)))
14209 ;; add the next tags
14210 (when tags
14211 (setq tags (org-split-string tags ":")
14212 tags-alist
14213 (cons (cons level tags) tags-alist)))
14214 ;; compile tags for current headline
14215 (setq tags-list
14216 (if org-use-tag-inheritance
14217 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14218 tags)
14219 org-scanner-tags tags-list)
14220 (when org-use-tag-inheritance
14221 (setcdr (car tags-alist)
14222 (mapcar (lambda (x)
14223 (setq x (copy-sequence x))
14224 (org-add-prop-inherited x))
14225 (cdar tags-alist))))
14226 (when (and tags org-use-tag-inheritance
14227 (or (not (eq t org-use-tag-inheritance))
14228 org-tags-exclude-from-inheritance))
14229 ;; Selective inheritance, remove uninherited ones.
14230 (setcdr (car tags-alist)
14231 (org-remove-uninherited-tags (cdar tags-alist))))
14232 (when (and
14234 ;; eval matcher only when the todo condition is OK
14235 (and (or (not todo-only) (member todo org-not-done-keywords))
14236 (if (functionp matcher)
14237 (let ((case-fold-search t) (org-trust-scanner-tags t))
14238 (funcall matcher todo tags-list level))
14239 matcher))
14241 ;; Call the skipper, but return t if it does not
14242 ;; skip, so that the `and' form continues evaluating.
14243 (progn
14244 (unless (eq action 'sparse-tree) (org-agenda-skip))
14247 ;; Check if timestamps are deselecting this entry
14248 (or (not todo-only)
14249 (and (member todo org-not-done-keywords)
14250 (or (not org-agenda-tags-todo-honor-ignore-options)
14251 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14253 ;; select this headline
14254 (cond
14255 ((eq action 'sparse-tree)
14256 (and org-highlight-sparse-tree-matches
14257 (org-get-heading) (match-end 0)
14258 (org-highlight-new-match
14259 (match-beginning 1) (match-end 1)))
14260 (org-show-context 'tags-tree))
14261 ((eq action 'agenda)
14262 (setq txt (org-agenda-format-item
14264 (concat
14265 (if (eq org-tags-match-list-sublevels 'indented)
14266 (make-string (1- level) ?.) "")
14267 (org-get-heading))
14268 (make-string level ?\s)
14269 category
14270 tags-list)
14271 priority (org-get-priority txt))
14272 (goto-char lspos)
14273 (setq marker (org-agenda-new-marker))
14274 (org-add-props txt props
14275 'org-marker marker 'org-hd-marker marker 'org-category category
14276 'todo-state todo
14277 'ts-date ts-date
14278 'priority priority
14279 'type (concat "tagsmatch" ts-date-type))
14280 (push txt rtn))
14281 ((functionp action)
14282 (setq org-map-continue-from nil)
14283 (save-excursion
14284 (setq rtn1 (funcall action))
14285 (push rtn1 rtn)))
14286 (t (user-error "Invalid action")))
14288 ;; if we are to skip sublevels, jump to end of subtree
14289 (unless org-tags-match-list-sublevels
14290 (org-end-of-subtree t)
14291 (backward-char 1))))
14292 ;; Get the correct position from where to continue
14293 (if org-map-continue-from
14294 (goto-char org-map-continue-from)
14295 (and (= (point) lspos) (end-of-line 1)))))
14296 (when (and (eq action 'sparse-tree)
14297 (not org-sparse-tree-open-archived-trees))
14298 (org-hide-archived-subtrees (point-min) (point-max)))
14299 (nreverse rtn)))
14301 (defun org-remove-uninherited-tags (tags)
14302 "Remove all tags that are not inherited from the list TAGS."
14303 (cond
14304 ((eq org-use-tag-inheritance t)
14305 (if org-tags-exclude-from-inheritance
14306 (org-delete-all org-tags-exclude-from-inheritance tags)
14307 tags))
14308 ((not org-use-tag-inheritance) nil)
14309 ((stringp org-use-tag-inheritance)
14310 (delq nil (mapcar
14311 (lambda (x)
14312 (if (and (string-match org-use-tag-inheritance x)
14313 (not (member x org-tags-exclude-from-inheritance)))
14314 x nil))
14315 tags)))
14316 ((listp org-use-tag-inheritance)
14317 (delq nil (mapcar
14318 (lambda (x)
14319 (if (member x org-use-tag-inheritance) x nil))
14320 tags)))))
14322 (defun org-match-sparse-tree (&optional todo-only match)
14323 "Create a sparse tree according to tags string MATCH.
14324 MATCH can contain positive and negative selection of tags, like
14325 \"+WORK+URGENT-WITHBOSS\".
14326 If optional argument TODO-ONLY is non-nil, only select lines that are
14327 also TODO lines."
14328 (interactive "P")
14329 (org-agenda-prepare-buffers (list (current-buffer)))
14330 (let ((org--matcher-tags-todo-only todo-only))
14331 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14332 org--matcher-tags-todo-only)))
14334 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14336 (defvar org-cached-props nil)
14337 (defun org-cached-entry-get (pom property)
14338 (if (or (eq t org-use-property-inheritance)
14339 (and (stringp org-use-property-inheritance)
14340 (let ((case-fold-search t))
14341 (org-string-match-p org-use-property-inheritance property)))
14342 (and (listp org-use-property-inheritance)
14343 (member-ignore-case property org-use-property-inheritance)))
14344 ;; Caching is not possible, check it directly.
14345 (org-entry-get pom property 'inherit)
14346 ;; Get all properties, so we can do complicated checks easily.
14347 (cdr (assoc-string property
14348 (or org-cached-props
14349 (setq org-cached-props (org-entry-properties pom)))
14350 t))))
14352 (defun org-global-tags-completion-table (&optional files)
14353 "Return the list of all tags in all agenda buffer/files.
14354 Optional FILES argument is a list of files which can be used
14355 instead of the agenda files."
14356 (save-excursion
14357 (org-uniquify
14358 (delq nil
14359 (apply 'append
14360 (mapcar
14361 (lambda (file)
14362 (set-buffer (find-file-noselect file))
14363 (append (org-get-buffer-tags)
14364 (mapcar (lambda (x) (if (stringp (car-safe x))
14365 (list (car-safe x)) nil))
14366 org-tag-alist)))
14367 (if (and files (car files))
14368 files
14369 (org-agenda-files))))))))
14371 (defun org-make-tags-matcher (match)
14372 "Create the TAGS/TODO matcher form for the selection string MATCH.
14374 Returns a cons of the selection string MATCH and a function
14375 implementing the matcher.
14377 The matcher is to be called at an Org entry, with point on the
14378 headline, and returns non-nil if the entry matches the selection
14379 string MATCH. It must be called with three arguments: the TODO
14380 keyword at the entry (or nil if none), the list of all tags at
14381 the entry including inherited ones and the reduced level of the
14382 headline. Additionally, the category of the entry, if any, must
14383 be specified as the text property `org-category' on the headline.
14385 This function sets the variable `org--matcher-tags-todo-only' to
14386 a non-nil value if the matcher restricts matching to TODO
14387 entries, otherwise it is not touched.
14389 See also `org-scan-tags'."
14390 (unless match
14391 ;; Get a new match request, with completion against the global
14392 ;; tags table and the local tags in current buffer.
14393 (let ((org-last-tags-completion-table
14394 (org-uniquify
14395 (delq nil (append (org-get-buffer-tags)
14396 (org-global-tags-completion-table))))))
14397 (setq match
14398 (completing-read
14399 "Match: "
14400 'org-tags-completion-function nil nil nil 'org-tags-history))))
14402 (let ((match0 match)
14403 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14404 (start 0)
14405 tagsmatch todomatch tagsmatcher todomatcher)
14407 ;; Expand group tags.
14408 (setq match (org-tags-expand match))
14410 ;; Check if there is a TODO part of this match, which would be the
14411 ;; part after a "/". To make sure that this slash is not part of
14412 ;; a property value to be matched against, we also check that
14413 ;; there is no / after that slash. First, find the last slash.
14414 (let ((s 0))
14415 (while (string-match "/+" match s)
14416 (setq start (match-beginning 0))
14417 (setq s (match-end 0))))
14418 (if (and (string-match "/+" match start)
14419 (not (string-match-p "\"" match start)))
14420 ;; Match contains also a TODO-matching request.
14421 (progn
14422 (setq tagsmatch (substring match 0 (match-beginning 0)))
14423 (setq todomatch (substring match (match-end 0)))
14424 (when (string-match "\\`!" todomatch)
14425 (setq org--matcher-tags-todo-only t)
14426 (setq todomatch (substring todomatch 1)))
14427 (when (string-match "\\`\\s-*\\'" todomatch)
14428 (setq todomatch nil)))
14429 ;; Only matching tags.
14430 (setq tagsmatch match)
14431 (setq todomatch nil))
14433 ;; Make the tags matcher.
14434 (when (org-string-nw-p tagsmatch)
14435 (let ((orlist nil)
14436 (orterms (org-split-string tagsmatch "|"))
14437 term)
14438 (while (setq term (pop orterms))
14439 (while (and (equal (substring term -1) "\\") orterms)
14440 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14441 (while (string-match re term)
14442 (let* ((rest (substring term (match-end 0)))
14443 (minus (and (match-end 1)
14444 (equal (match-string 1 term) "-")))
14445 (tag (save-match-data
14446 (replace-regexp-in-string
14447 "\\\\-" "-" (match-string 2 term))))
14448 (regexp (eq (string-to-char tag) ?{))
14449 (levelp (match-end 4))
14450 (propp (match-end 5))
14452 (cond
14453 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14454 (levelp
14455 `(,(org-op-to-function (match-string 3 term))
14456 level
14457 ,(string-to-number (match-string 4 term))))
14458 (propp
14459 (let* ((gv (pcase (upcase (match-string 5 term))
14460 ("CATEGORY"
14461 '(get-text-property (point) 'org-category))
14462 ("TODO" 'todo)
14463 (p `(org-cached-entry-get nil ,p))))
14464 (pv (match-string 7 term))
14465 (regexp (eq (string-to-char pv) ?{))
14466 (strp (eq (string-to-char pv) ?\"))
14467 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14468 (po (org-op-to-function (match-string 6 term)
14469 (if timep 'time strp))))
14470 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14471 (when timep (setq pv (org-matcher-time pv)))
14472 (cond ((and regexp (eq po 'org<>))
14473 `(not (string-match ,pv (or ,gv ""))))
14474 (regexp `(string-match ,pv (or ,gv "")))
14475 (strp `(,po (or ,gv "") ,pv))
14477 `(,po
14478 (string-to-number (or ,gv ""))
14479 ,(string-to-number pv))))))
14480 (t `(member ,tag tags-list)))))
14481 (push (if minus `(not ,mm) mm) tagsmatcher)
14482 (setq term rest)))
14483 (push `(and ,@tagsmatcher) orlist)
14484 (setq tagsmatcher nil))
14485 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14487 ;; Make the TODO matcher.
14488 (when (org-string-nw-p todomatch)
14489 (let ((orlist nil))
14490 (dolist (term (org-split-string todomatch "|"))
14491 (while (string-match re term)
14492 (let* ((minus (and (match-end 1)
14493 (equal (match-string 1 term) "-")))
14494 (kwd (match-string 2 term))
14495 (regexp (eq (string-to-char kwd) ?{))
14496 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14497 `(equal todo ,kwd))))
14498 (push (if minus `(not ,mm) mm) todomatcher))
14499 (setq term (substring term (match-end 0))))
14500 (push (if (> (length todomatcher) 1)
14501 (cons 'and todomatcher)
14502 (car todomatcher))
14503 orlist)
14504 (setq todomatcher nil))
14505 (setq todomatcher (cons 'or orlist))))
14507 ;; Return the string and function of the matcher.
14508 (let ((matcher (if todomatcher `(and ,tagsmatcher ,todomatcher)
14509 tagsmatcher)))
14510 (when org--matcher-tags-todo-only
14511 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14512 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14514 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14515 "Expand group tags in MATCH.
14517 This replaces every group tag in MATCH with a regexp tag search.
14518 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14519 will be replaced like this:
14521 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14522 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14523 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14525 Replacing by a regexp preserves the structure of the match.
14526 E.g., this expansion
14528 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14530 will match anything tagged with \"Lab\" and \"Home\", or tagged
14531 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14533 A group tag in MATCH can contain regular expressions of its own.
14534 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14535 will be replaced like this:
14537 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14539 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14540 assumed to be a single group tag, and the function will return
14541 the list of tags in this group.
14543 When DOWNCASE is non-nil, expand downcased TAGS."
14544 (if org-group-tags
14545 (let* ((case-fold-search t)
14546 (stable org-mode-syntax-table)
14547 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14548 (taggroups (if downcased
14549 (mapcar (lambda (tg) (mapcar #'downcase tg))
14550 taggroups)
14551 taggroups))
14552 (taggroups-keys (mapcar #'car taggroups))
14553 (return-match (if downcased (downcase match) match))
14554 (count 0)
14555 (work-already-expanded tags-already-expanded)
14556 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14557 ;; @ and _ are allowed as word-components in tags.
14558 (modify-syntax-entry ?@ "w" stable)
14559 (modify-syntax-entry ?_ "w" stable)
14560 ;; Temporarily replace regexp-expressions in the match-expression.
14561 (while (string-match "{.+?}" return-match)
14562 (cl-incf count)
14563 (push (match-string 0 return-match) regexps-in-match)
14564 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14565 (while (and taggroups-keys
14566 (with-syntax-table stable
14567 (string-match
14568 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14569 (regexp-opt taggroups-keys) "\\>\\)")
14570 return-match)))
14571 (let* ((dir (match-string 1 return-match))
14572 (tag (match-string 2 return-match))
14573 (tag (if downcased (downcase tag) tag)))
14574 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14575 (member tag work-already-expanded))
14576 (setq tags-in-group (assoc tag taggroups))
14577 (push tag work-already-expanded)
14578 ;; Recursively expand each tag in the group, if the tag hasn't
14579 ;; already been expanded. Restore the match-data after all recursive calls.
14580 (save-match-data
14581 (let (tags-expanded)
14582 (dolist (x (cdr tags-in-group))
14583 (if (and (member x taggroups-keys)
14584 (not (member x work-already-expanded)))
14585 (setq tags-expanded
14586 (delete-dups
14587 (append
14588 (org-tags-expand x t downcased
14589 work-already-expanded)
14590 tags-expanded)))
14591 (setq tags-expanded
14592 (append (list x) tags-expanded)))
14593 (setq work-already-expanded
14594 (delete-dups
14595 (append tags-expanded
14596 work-already-expanded))))
14597 (setq tags-in-group
14598 (delete-dups (cons (car tags-in-group)
14599 tags-expanded)))))
14600 ;; Filter tag-regexps from tags.
14601 (setq regexp-in-group-escaped
14602 (delq nil (mapcar (lambda (x)
14603 (if (stringp x)
14604 (and (equal "{" (substring x 0 1))
14605 (equal "}" (substring x -1))
14608 tags-in-group))
14609 regexp-in-group
14610 (mapcar (lambda (x)
14611 (substring x 1 -1))
14612 regexp-in-group-escaped)
14613 tags-in-group
14614 (delq nil (mapcar (lambda (x)
14615 (if (stringp x)
14616 (and (not (equal "{" (substring x 0 1)))
14617 (not (equal "}" (substring x -1)))
14620 tags-in-group)))
14621 ;; If single-as-list, do no more in the while-loop.
14622 (if (not single-as-list)
14623 (progn
14624 (when regexp-in-group
14625 (setq regexp-in-group
14626 (concat "\\|"
14627 (mapconcat 'identity regexp-in-group
14628 "\\|"))))
14629 (setq tags-in-group
14630 (concat dir
14631 "{\\<"
14632 (regexp-opt tags-in-group)
14633 "\\>"
14634 regexp-in-group
14635 "}"))
14636 (when (stringp tags-in-group)
14637 (org-add-props tags-in-group '(grouptag t)))
14638 (setq return-match
14639 (replace-match tags-in-group t t return-match)))
14640 (setq tags-in-group
14641 (append regexp-in-group-escaped tags-in-group))))
14642 (setq taggroups-keys (delete tag taggroups-keys))))
14643 ;; Add the regular expressions back into the match-expression again.
14644 (while regexps-in-match
14645 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14646 (pop regexps-in-match)
14647 return-match t t))
14648 (cl-decf count))
14649 (if single-as-list
14650 (if tags-in-group tags-in-group (list return-match))
14651 return-match))
14652 (if single-as-list
14653 (list (if downcased (downcase match) match))
14654 match)))
14656 (defun org-op-to-function (op &optional stringp)
14657 "Turn an operator into the appropriate function."
14658 (setq op
14659 (cond
14660 ((equal op "<" ) '(< string< org-time<))
14661 ((equal op ">" ) '(> org-string> org-time>))
14662 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14663 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14664 ((member op '("=" "==")) '(= string= org-time=))
14665 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14666 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14668 (defun org<> (a b) (not (= a b)))
14669 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14670 (defun org-string>= (a b) (not (string< a b)))
14671 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14672 (defun org-string<> (a b) (not (string= a b)))
14673 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14674 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14675 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14676 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14677 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14678 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14679 (defun org-2ft (s)
14680 "Convert S to a floating point time.
14681 If S is already a number, just return it. If it is a string, parse
14682 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14683 (cond
14684 ((numberp s) s)
14685 ((stringp s)
14686 (condition-case nil
14687 (float-time (apply 'encode-time (org-parse-time-string s)))
14688 (error 0.)))
14689 (t 0.)))
14691 (defun org-time-today ()
14692 "Time in seconds today at 0:00.
14693 Returns the float number of seconds since the beginning of the
14694 epoch to the beginning of today (00:00)."
14695 (float-time (apply 'encode-time
14696 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14698 (defun org-matcher-time (s)
14699 "Interpret a time comparison value."
14700 (save-match-data
14701 (cond
14702 ((string= s "<now>") (float-time))
14703 ((string= s "<today>") (org-time-today))
14704 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14705 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14706 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14707 (+ (org-time-today)
14708 (* (string-to-number (match-string 1 s))
14709 (cdr (assoc (match-string 2 s)
14710 '(("d" . 86400.0) ("w" . 604800.0)
14711 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14712 (t (org-2ft s)))))
14714 (defun org-match-any-p (re list)
14715 "Does re match any element of list?"
14716 (setq list (mapcar (lambda (x) (string-match re x)) list))
14717 (delq nil list))
14719 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14720 (defvar org-tags-overlay (make-overlay 1 1))
14721 (org-detach-overlay org-tags-overlay)
14723 (defun org-get-local-tags-at (&optional pos)
14724 "Get a list of tags defined in the current headline."
14725 (org-get-tags-at pos 'local))
14727 (defun org-get-local-tags ()
14728 "Get a list of tags defined in the current headline."
14729 (org-get-tags-at nil 'local))
14731 (defun org-get-tags-at (&optional pos local)
14732 "Get a list of all headline tags applicable at POS.
14733 POS defaults to point. If tags are inherited, the list contains
14734 the targets in the same sequence as the headlines appear, i.e.
14735 the tags of the current headline come last.
14736 When LOCAL is non-nil, only return tags from the current headline,
14737 ignore inherited ones."
14738 (interactive)
14739 (if (and org-trust-scanner-tags
14740 (or (not pos) (equal pos (point)))
14741 (not local))
14742 org-scanner-tags
14743 (let (tags ltags lastpos parent)
14744 (save-excursion
14745 (save-restriction
14746 (widen)
14747 (goto-char (or pos (point)))
14748 (save-match-data
14749 (catch 'done
14750 (condition-case nil
14751 (progn
14752 (org-back-to-heading t)
14753 (while (not (equal lastpos (point)))
14754 (setq lastpos (point))
14755 (when (looking-at
14756 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14757 (setq ltags (org-split-string
14758 (org-match-string-no-properties 1) ":"))
14759 (when parent
14760 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14761 (setq tags (append
14762 (if parent
14763 (org-remove-uninherited-tags ltags)
14764 ltags)
14765 tags)))
14766 (or org-use-tag-inheritance (throw 'done t))
14767 (when local (throw 'done t))
14768 (or (org-up-heading-safe) (error nil))
14769 (setq parent t)))
14770 (error nil)))))
14771 (if local
14772 tags
14773 (reverse (delete-dups
14774 (reverse (append
14775 (org-remove-uninherited-tags
14776 org-file-tags)
14777 tags)))))))))
14779 (defun org-add-prop-inherited (s)
14780 (add-text-properties 0 (length s) '(inherited t) s)
14783 (defun org-toggle-tag (tag &optional onoff)
14784 "Toggle the tag TAG for the current line.
14785 If ONOFF is `on' or `off', don't toggle but set to this state."
14786 (let (res current)
14787 (save-excursion
14788 (org-back-to-heading t)
14789 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14790 (point-at-eol) t)
14791 (progn
14792 (setq current (match-string 1))
14793 (replace-match ""))
14794 (setq current ""))
14795 (setq current (nreverse (org-split-string current ":")))
14796 (cond
14797 ((eq onoff 'on)
14798 (setq res t)
14799 (or (member tag current) (push tag current)))
14800 ((eq onoff 'off)
14801 (or (not (member tag current)) (setq current (delete tag current))))
14802 (t (if (member tag current)
14803 (setq current (delete tag current))
14804 (setq res t)
14805 (push tag current))))
14806 (end-of-line 1)
14807 (if current
14808 (progn
14809 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14810 (org-set-tags nil t))
14811 (delete-horizontal-space))
14812 (run-hooks 'org-after-tags-change-hook))
14813 res))
14815 (defun org-align-tags-here (to-col)
14816 ;; Assumes that this is a headline
14817 "Align tags on the current headline to TO-COL."
14818 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14819 (beginning-of-line 1)
14820 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14821 (< pos (match-beginning 2)))
14822 (progn
14823 (setq tags-l (- (match-end 2) (match-beginning 2)))
14824 (goto-char (match-beginning 1))
14825 (insert " ")
14826 (delete-region (point) (1+ (match-beginning 2)))
14827 (setq ncol (max (current-column)
14828 (1+ col)
14829 (if (> to-col 0)
14830 to-col
14831 (- (abs to-col) tags-l))))
14832 (setq p (point))
14833 (insert (make-string (- ncol (current-column)) ?\ ))
14834 (setq ncol (current-column))
14835 (when indent-tabs-mode (tabify p (point-at-eol)))
14836 (org-move-to-column (min ncol col)))
14837 (goto-char pos))))
14839 (defun org-set-tags-command (&optional arg just-align)
14840 "Call the set-tags command for the current entry."
14841 (interactive "P")
14842 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14843 (org-set-tags arg just-align)
14844 (save-excursion
14845 (unless (and (org-region-active-p)
14846 org-loop-over-headlines-in-active-region)
14847 (org-back-to-heading t))
14848 (org-set-tags arg just-align))))
14850 (defun org-set-tags-to (data)
14851 "Set the tags of the current entry to DATA, replacing the current tags.
14852 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14853 If DATA is nil or the empty string, any tags will be removed."
14854 (interactive "sTags: ")
14855 (setq data
14856 (cond
14857 ((eq data nil) "")
14858 ((equal data "") "")
14859 ((stringp data)
14860 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14861 ":"))
14862 ((listp data)
14863 (concat ":" (mapconcat 'identity data ":") ":"))))
14864 (when data
14865 (save-excursion
14866 (org-back-to-heading t)
14867 (when (looking-at org-complex-heading-regexp)
14868 (if (match-end 5)
14869 (progn
14870 (goto-char (match-beginning 5))
14871 (insert data)
14872 (delete-region (point) (point-at-eol))
14873 (org-set-tags nil 'align))
14874 (goto-char (point-at-eol))
14875 (insert " " data)
14876 (org-set-tags nil 'align)))
14877 (beginning-of-line 1)
14878 (when (looking-at ".*?\\([ \t]+\\)$")
14879 (delete-region (match-beginning 1) (match-end 1))))))
14881 (defun org-align-all-tags ()
14882 "Align the tags i all headings."
14883 (interactive)
14884 (save-excursion
14885 (or (ignore-errors (org-back-to-heading t))
14886 (outline-next-heading))
14887 (if (org-at-heading-p)
14888 (org-set-tags t)
14889 (message "No headings"))))
14891 (defvar org-indent-indentation-per-level)
14892 (defun org-set-tags (&optional arg just-align)
14893 "Set the tags for the current headline.
14894 With prefix ARG, realign all tags in headings in the current buffer.
14895 When JUST-ALIGN is non-nil, only align tags."
14896 (interactive "P")
14897 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14898 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14899 'region-start-level
14900 'region))
14901 org-loop-over-headlines-in-active-region)
14902 (org-map-entries
14903 ;; We don't use ARG and JUST-ALIGN here because these args
14904 ;; are not useful when looping over headlines.
14905 #'org-set-tags
14906 org-loop-over-headlines-in-active-region
14908 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
14909 (let ((org-setting-tags t))
14910 (if arg
14911 (save-excursion
14912 (goto-char (point-min))
14913 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14914 (while (re-search-forward org-outline-regexp-bol nil t)
14915 (org-set-tags nil t)
14916 (end-of-line)))
14917 (message "All tags realigned to column %d" org-tags-column))
14918 (let* ((current (org-get-tags-string))
14919 (col (current-column))
14920 (tags
14921 (if just-align current
14922 ;; Get a new set of tags from the user.
14923 (save-excursion
14924 (let* ((table
14925 (setq
14926 org-last-tags-completion-table
14927 (append
14928 org-tag-persistent-alist
14929 (or org-tag-alist (org-get-buffer-tags))
14930 (and
14931 org-complete-tags-always-offer-all-agenda-tags
14932 (org-global-tags-completion-table
14933 (org-agenda-files))))))
14934 (current-tags (org-split-string current ":"))
14935 (inherited-tags
14936 (nreverse (nthcdr (length current-tags)
14937 (nreverse (org-get-tags-at))))))
14938 (replace-regexp-in-string
14939 "\\([-+&]+\\|,\\)"
14941 (if (or (eq t org-use-fast-tag-selection)
14942 (and org-use-fast-tag-selection
14943 (delq nil (mapcar #'cdr table))))
14944 (org-fast-tag-selection
14945 current-tags inherited-tags table
14946 (and org-fast-tag-selection-include-todo
14947 org-todo-key-alist))
14948 (let ((org-add-colon-after-tag-completion
14949 (< 1 (length table))))
14950 (org-trim
14951 (completing-read
14952 "Tags: "
14953 #'org-tags-completion-function
14954 nil nil current 'org-tags-history))))))))))
14956 (when org-tags-sort-function
14957 (setq tags
14958 (mapconcat
14959 #'identity
14960 (sort (org-split-string tags (org-re "[^[:alnum:]_@#%]+"))
14961 org-tags-sort-function)
14962 ":")))
14964 (if (not (org-string-nw-p tags)) (setq tags "")
14965 (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
14966 (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
14968 ;; Insert new tags at the correct column
14969 (beginning-of-line)
14970 (let ((level (if (looking-at org-outline-regexp)
14971 (- (match-end 0) (point) 1)
14972 1)))
14973 (cond
14974 ((and (equal current "") (equal tags "")))
14975 ((re-search-forward
14976 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14977 (line-end-position)
14979 (if (equal tags "") (replace-match "" t t)
14980 (goto-char (match-beginning 0))
14981 (let* ((c0 (current-column))
14982 ;; Compute offset for the case of org-indent-mode
14983 ;; active.
14984 (di (if (org-bound-and-true-p org-indent-mode)
14985 (* (1- org-indent-indentation-per-level)
14986 (1- level))
14988 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
14989 (tc (+ org-tags-column
14990 (if (> org-tags-column 0) (- di) di)))
14991 (c1 (max (1+ c0)
14992 (if (> tc 0) tc
14993 (- (- tc) (string-width tags)))))
14994 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
14995 (replace-match rpl t t)
14996 (when (and (not (featurep 'xemacs)) indent-tabs-mode)
14997 (tabify p0 (point))))))
14998 (t (error "Tags alignment failed"))))
14999 (org-move-to-column col))
15000 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15002 (defun org-change-tag-in-region (beg end tag off)
15003 "Add or remove TAG for each entry in the region.
15004 This works in the agenda, and also in an org-mode buffer."
15005 (interactive
15006 (list (region-beginning) (region-end)
15007 (let ((org-last-tags-completion-table
15008 (if (derived-mode-p 'org-mode)
15009 (org-uniquify
15010 (delq nil (append (org-get-buffer-tags)
15011 (org-global-tags-completion-table))))
15012 (org-global-tags-completion-table))))
15013 (completing-read
15014 "Tag: " 'org-tags-completion-function nil nil nil
15015 'org-tags-history))
15016 (progn
15017 (message "[s]et or [r]emove? ")
15018 (equal (read-char-exclusive) ?r))))
15019 (when (fboundp 'deactivate-mark) (deactivate-mark))
15020 (let ((agendap (equal major-mode 'org-agenda-mode))
15021 l1 l2 m buf pos newhead (cnt 0))
15022 (goto-char end)
15023 (setq l2 (1- (org-current-line)))
15024 (goto-char beg)
15025 (setq l1 (org-current-line))
15026 (cl-loop for l from l1 to l2 do
15027 (org-goto-line l)
15028 (setq m (get-text-property (point) 'org-hd-marker))
15029 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15030 (and agendap m))
15031 (setq buf (if agendap (marker-buffer m) (current-buffer))
15032 pos (if agendap m (point)))
15033 (with-current-buffer buf
15034 (save-excursion
15035 (save-restriction
15036 (goto-char pos)
15037 (setq cnt (1+ cnt))
15038 (org-toggle-tag tag (if off 'off 'on))
15039 (setq newhead (org-get-heading)))))
15040 (and agendap (org-agenda-change-all-lines newhead m))))
15041 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15043 (defun org-tags-completion-function (string _predicate &optional flag)
15044 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15045 (confirm (lambda (x) (stringp (car x)))))
15046 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15047 (setq s1 (match-string 1 string)
15048 s2 (match-string 2 string))
15049 (setq s1 "" s2 string))
15050 (cond
15051 ((eq flag nil)
15052 ;; try completion
15053 (setq rtn (try-completion s2 ctable confirm))
15054 (when (stringp rtn)
15055 (setq rtn
15056 (concat s1 s2 (substring rtn (length s2))
15057 (if (and org-add-colon-after-tag-completion
15058 (assoc rtn ctable))
15059 ":" ""))))
15060 rtn)
15061 ((eq flag t)
15062 ;; all-completions
15063 (all-completions s2 ctable confirm))
15064 ((eq flag 'lambda)
15065 ;; exact match?
15066 (assoc s2 ctable)))))
15068 (defun org-fast-tag-insert (kwd tags face &optional end)
15069 "Insert KDW, and the TAGS, the latter with face FACE.
15070 Also insert END."
15071 (insert (format "%-12s" (concat kwd ":"))
15072 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15073 (or end "")))
15075 (defun org-fast-tag-show-exit (flag)
15076 (save-excursion
15077 (org-goto-line 3)
15078 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15079 (replace-match ""))
15080 (when flag
15081 (end-of-line 1)
15082 (org-move-to-column (- (window-width) 19) t)
15083 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15085 (defun org-set-current-tags-overlay (current prefix)
15086 "Add an overlay to CURRENT tag with PREFIX."
15087 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15088 (if (featurep 'xemacs)
15089 (org-overlay-display org-tags-overlay (concat prefix s)
15090 'secondary-selection)
15091 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15092 (org-overlay-display org-tags-overlay (concat prefix s)))))
15094 (defvar org-last-tag-selection-key nil)
15095 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15096 "Fast tag selection with single keys.
15097 CURRENT is the current list of tags in the headline, INHERITED is the
15098 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15099 possibly with grouping information. TODO-TABLE is a similar table with
15100 TODO keywords, should these have keys assigned to them.
15101 If the keys are nil, a-z are automatically assigned.
15102 Returns the new tags string, or nil to not change the current settings."
15103 (let* ((fulltable (append table todo-table))
15104 (maxlen (apply 'max (mapcar
15105 (lambda (x)
15106 (if (stringp (car x)) (string-width (car x)) 0))
15107 fulltable)))
15108 (buf (current-buffer))
15109 (expert (eq org-fast-tag-selection-single-key 'expert))
15110 (buffer-tags nil)
15111 (fwidth (+ maxlen 3 1 3))
15112 (ncol (/ (- (window-width) 4) fwidth))
15113 (i-face 'org-done)
15114 (c-face 'org-todo)
15115 tg cnt e c char c1 c2 ntable tbl rtn
15116 ov-start ov-end ov-prefix
15117 (exit-after-next org-fast-tag-selection-single-key)
15118 (done-keywords org-done-keywords)
15119 groups ingroup intaggroup)
15120 (save-excursion
15121 (beginning-of-line 1)
15122 (if (looking-at
15123 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15124 (setq ov-start (match-beginning 1)
15125 ov-end (match-end 1)
15126 ov-prefix "")
15127 (setq ov-start (1- (point-at-eol))
15128 ov-end (1+ ov-start))
15129 (skip-chars-forward "^\n\r")
15130 (setq ov-prefix
15131 (concat
15132 (buffer-substring (1- (point)) (point))
15133 (if (> (current-column) org-tags-column)
15135 (make-string (- org-tags-column (current-column)) ?\ ))))))
15136 (move-overlay org-tags-overlay ov-start ov-end)
15137 (save-window-excursion
15138 (if expert
15139 (set-buffer (get-buffer-create " *Org tags*"))
15140 (delete-other-windows)
15141 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15142 (org-switch-to-buffer-other-window " *Org tags*"))
15143 (erase-buffer)
15144 (setq-local org-done-keywords done-keywords)
15145 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15146 (org-fast-tag-insert "Current" current c-face "\n\n")
15147 (org-fast-tag-show-exit exit-after-next)
15148 (org-set-current-tags-overlay current ov-prefix)
15149 (setq tbl fulltable char ?a cnt 0)
15150 (while (setq e (pop tbl))
15151 (cond
15152 ((eq (car e) :startgroup)
15153 (push '() groups) (setq ingroup t)
15154 (unless (zerop cnt)
15155 (setq cnt 0)
15156 (insert "\n"))
15157 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15158 ((eq (car e) :endgroup)
15159 (setq ingroup nil cnt 0)
15160 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15161 ((eq (car e) :startgrouptag)
15162 (setq intaggroup t)
15163 (unless (zerop cnt)
15164 (setq cnt 0)
15165 (insert "\n"))
15166 (insert "[ "))
15167 ((eq (car e) :endgrouptag)
15168 (setq intaggroup nil cnt 0)
15169 (insert "]\n"))
15170 ((equal e '(:newline))
15171 (unless (zerop cnt)
15172 (setq cnt 0)
15173 (insert "\n")
15174 (setq e (car tbl))
15175 (while (equal (car tbl) '(:newline))
15176 (insert "\n")
15177 (setq tbl (cdr tbl)))))
15178 ((equal e '(:grouptags)) (insert " : "))
15180 (setq tg (copy-sequence (car e)) c2 nil)
15181 (if (cdr e)
15182 (setq c (cdr e))
15183 ;; automatically assign a character.
15184 (setq c1 (string-to-char
15185 (downcase (substring
15186 tg (if (= (string-to-char tg) ?@) 1 0)))))
15187 (if (or (rassoc c1 ntable) (rassoc c1 table))
15188 (while (or (rassoc char ntable) (rassoc char table))
15189 (setq char (1+ char)))
15190 (setq c2 c1))
15191 (setq c (or c2 char)))
15192 (when ingroup (push tg (car groups)))
15193 (setq tg (org-add-props tg nil 'face
15194 (cond
15195 ((not (assoc tg table))
15196 (org-get-todo-face tg))
15197 ((member tg current) c-face)
15198 ((member tg inherited) i-face))))
15199 (when (equal (caar tbl) :grouptags)
15200 (org-add-props tg nil 'face 'org-tag-group))
15201 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15202 (insert "[" c "] " tg (make-string
15203 (- fwidth 4 (length tg)) ?\ ))
15204 (push (cons tg c) ntable)
15205 (when (= (cl-incf cnt) ncol)
15206 (insert "\n")
15207 (when (or ingroup intaggroup) (insert " "))
15208 (setq cnt 0)))))
15209 (setq ntable (nreverse ntable))
15210 (insert "\n")
15211 (goto-char (point-min))
15212 (unless expert (org-fit-window-to-buffer))
15213 (setq rtn
15214 (catch 'exit
15215 (while t
15216 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15217 (if (not groups) "no " "")
15218 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15219 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15220 (setq org-last-tag-selection-key c)
15221 (cond
15222 ((= c ?\r) (throw 'exit t))
15223 ((= c ?!)
15224 (setq groups (not groups))
15225 (goto-char (point-min))
15226 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15227 ((= c ?\C-c)
15228 (if (not expert)
15229 (org-fast-tag-show-exit
15230 (setq exit-after-next (not exit-after-next)))
15231 (setq expert nil)
15232 (delete-other-windows)
15233 (set-window-buffer (split-window-vertically) " *Org tags*")
15234 (org-switch-to-buffer-other-window " *Org tags*")
15235 (org-fit-window-to-buffer)))
15236 ((or (= c ?\C-g)
15237 (and (= c ?q) (not (rassoc c ntable))))
15238 (org-detach-overlay org-tags-overlay)
15239 (setq quit-flag t))
15240 ((= c ?\ )
15241 (setq current nil)
15242 (when exit-after-next (setq exit-after-next 'now)))
15243 ((= c ?\t)
15244 (condition-case nil
15245 (setq tg (completing-read
15246 "Tag: "
15247 (or buffer-tags
15248 (with-current-buffer buf
15249 (setq buffer-tags
15250 (org-get-buffer-tags))))))
15251 (quit (setq tg "")))
15252 (when (string-match "\\S-" tg)
15253 (add-to-list 'buffer-tags (list tg))
15254 (if (member tg current)
15255 (setq current (delete tg current))
15256 (push tg current)))
15257 (when exit-after-next (setq exit-after-next 'now)))
15258 ((setq e (rassoc c todo-table) tg (car e))
15259 (with-current-buffer buf
15260 (save-excursion (org-todo tg)))
15261 (when exit-after-next (setq exit-after-next 'now)))
15262 ((setq e (rassoc c ntable) tg (car e))
15263 (if (member tg current)
15264 (setq current (delete tg current))
15265 (cl-loop for g in groups do
15266 (when (member tg g)
15267 (dolist (x g) (setq current (delete x current)))))
15268 (push tg current))
15269 (when exit-after-next (setq exit-after-next 'now))))
15271 ;; Create a sorted list
15272 (setq current
15273 (sort current
15274 (lambda (a b)
15275 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15276 (when (eq exit-after-next 'now) (throw 'exit t))
15277 (goto-char (point-min))
15278 (beginning-of-line 2)
15279 (delete-region (point) (point-at-eol))
15280 (org-fast-tag-insert "Current" current c-face)
15281 (org-set-current-tags-overlay current ov-prefix)
15282 (while (re-search-forward
15283 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15284 (setq tg (match-string 1))
15285 (add-text-properties
15286 (match-beginning 1) (match-end 1)
15287 (list 'face
15288 (cond
15289 ((member tg current) c-face)
15290 ((member tg inherited) i-face)
15291 (t (get-text-property (match-beginning 1) 'face))))))
15292 (goto-char (point-min)))))
15293 (org-detach-overlay org-tags-overlay)
15294 (if rtn
15295 (mapconcat 'identity current ":")
15296 nil))))
15298 (defun org-get-tags-string ()
15299 "Get the TAGS string in the current headline."
15300 (unless (org-at-heading-p t)
15301 (user-error "Not on a heading"))
15302 (save-excursion
15303 (beginning-of-line 1)
15304 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15305 (org-match-string-no-properties 1)
15306 "")))
15308 (defun org-get-tags ()
15309 "Get the list of tags specified in the current headline."
15310 (org-split-string (org-get-tags-string) ":"))
15312 (defun org-get-buffer-tags ()
15313 "Get a table of all tags used in the buffer, for completion."
15314 (org-with-wide-buffer
15315 (goto-char (point-min))
15316 (let ((tag-re (concat org-outline-regexp-bol
15317 "\\(?:.*?[ \t]\\)?"
15318 (org-re ":\\([[:alnum:]_@#%:]+\\):[ \t]*$")))
15319 tags)
15320 (while (re-search-forward tag-re nil t)
15321 (dolist (tag (org-split-string (org-match-string-no-properties 1) ":"))
15322 (push tag tags)))
15323 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15325 ;;;; The mapping API
15327 (defvar org-agenda-skip-comment-trees)
15328 (defvar org-agenda-skip-function)
15329 (defun org-map-entries (func &optional match scope &rest skip)
15330 "Call FUNC at each headline selected by MATCH in SCOPE.
15332 FUNC is a function or a lisp form. The function will be called without
15333 arguments, with the cursor positioned at the beginning of the headline.
15334 The return values of all calls to the function will be collected and
15335 returned as a list.
15337 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15338 does not need to preserve point. After evaluation, the cursor will be
15339 moved to the end of the line (presumably of the headline of the
15340 processed entry) and search continues from there. Under some
15341 circumstances, this may not produce the wanted results. For example,
15342 if you have removed (e.g. archived) the current (sub)tree it could
15343 mean that the next entry will be skipped entirely. In such cases, you
15344 can specify the position from where search should continue by making
15345 FUNC set the variable `org-map-continue-from' to the desired buffer
15346 position.
15348 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15349 Only headlines that are matched by this query will be considered during
15350 the iteration. When MATCH is nil or t, all headlines will be
15351 visited by the iteration.
15353 SCOPE determines the scope of this command. It can be any of:
15355 nil The current buffer, respecting the restriction if any
15356 tree The subtree started with the entry at point
15357 region The entries within the active region, if any
15358 region-start-level
15359 The entries within the active region, but only those at
15360 the same level than the first one.
15361 file The current buffer, without restriction
15362 file-with-archives
15363 The current buffer, and any archives associated with it
15364 agenda All agenda files
15365 agenda-with-archives
15366 All agenda files with any archive files associated with them
15367 \(file1 file2 ...)
15368 If this is a list, all files in the list will be scanned
15370 The remaining args are treated as settings for the skipping facilities of
15371 the scanner. The following items can be given here:
15373 archive skip trees with the archive tag
15374 comment skip trees with the COMMENT keyword
15375 function or Emacs Lisp form:
15376 will be used as value for `org-agenda-skip-function', so
15377 whenever the function returns a position, FUNC will not be
15378 called for that entry and search will continue from the
15379 position returned
15381 If your function needs to retrieve the tags including inherited tags
15382 at the *current* entry, you can use the value of the variable
15383 `org-scanner-tags' which will be much faster than getting the value
15384 with `org-get-tags-at'. If your function gets properties with
15385 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15386 to t around the call to `org-entry-properties' to get the same speedup.
15387 Note that if your function moves around to retrieve tags and properties at
15388 a *different* entry, you cannot use these techniques."
15389 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15390 (not (org-region-active-p)))
15391 (let* ((org-agenda-archives-mode nil) ; just to make sure
15392 (org-agenda-skip-archived-trees (memq 'archive skip))
15393 (org-agenda-skip-comment-trees (memq 'comment skip))
15394 (org-agenda-skip-function
15395 (car (org-delete-all '(comment archive) skip)))
15396 (org-tags-match-list-sublevels t)
15397 (start-level (eq scope 'region-start-level))
15398 matcher res
15399 org-todo-keywords-for-agenda
15400 org-done-keywords-for-agenda
15401 org-todo-keyword-alist-for-agenda
15402 org-tag-alist-for-agenda
15403 org--matcher-tags-todo-only)
15405 (cond
15406 ((eq match t) (setq matcher t))
15407 ((eq match nil) (setq matcher t))
15408 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15410 (save-excursion
15411 (save-restriction
15412 (cond ((eq scope 'tree)
15413 (org-back-to-heading t)
15414 (org-narrow-to-subtree)
15415 (setq scope nil))
15416 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15417 (org-region-active-p))
15418 ;; If needed, set start-level to a string like "2"
15419 (when start-level
15420 (save-excursion
15421 (goto-char (region-beginning))
15422 (unless (org-at-heading-p) (outline-next-heading))
15423 (setq start-level (org-current-level))))
15424 (narrow-to-region (region-beginning)
15425 (save-excursion
15426 (goto-char (region-end))
15427 (unless (and (bolp) (org-at-heading-p))
15428 (outline-next-heading))
15429 (point)))
15430 (setq scope nil)))
15432 (if (not scope)
15433 (progn
15434 (org-agenda-prepare-buffers
15435 (and buffer-file-name (list buffer-file-name)))
15436 (setq res
15437 (org-scan-tags
15438 func matcher org--matcher-tags-todo-only start-level)))
15439 ;; Get the right scope
15440 (cond
15441 ((and scope (listp scope) (symbolp (car scope)))
15442 (setq scope (eval scope)))
15443 ((eq scope 'agenda)
15444 (setq scope (org-agenda-files t)))
15445 ((eq scope 'agenda-with-archives)
15446 (setq scope (org-agenda-files t))
15447 (setq scope (org-add-archive-files scope)))
15448 ((eq scope 'file)
15449 (setq scope (and buffer-file-name (list buffer-file-name))))
15450 ((eq scope 'file-with-archives)
15451 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15452 (org-agenda-prepare-buffers scope)
15453 (dolist (file scope)
15454 (with-current-buffer (org-find-base-buffer-visiting file)
15455 (save-excursion
15456 (save-restriction
15457 (widen)
15458 (goto-char (point-min))
15459 (setq res
15460 (append
15462 (org-scan-tags
15463 func matcher org--matcher-tags-todo-only))))))))))
15464 res)))
15466 ;;; Properties API
15468 (defconst org-special-properties
15469 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15470 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15471 "The special properties valid in Org mode.
15472 These are properties that are not defined in the property drawer,
15473 but in some other way.")
15475 (defconst org-default-properties
15476 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15477 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15478 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15479 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15480 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15481 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15482 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15483 "Some properties that are used by Org mode for various purposes.
15484 Being in this list makes sure that they are offered for completion.")
15486 (defun org--valid-property-p (property)
15487 "Non nil when string PROPERTY is a valid property name."
15488 (not
15489 (or (equal property "")
15490 (org-string-match-p "\\s-" property))))
15492 (defun org--update-property-plist (key val props)
15493 "Associate KEY to VAL in alist PROPS.
15494 Modifications are made by side-effect. Return new alist."
15495 (let* ((appending (string= (substring key -1) "+"))
15496 (key (if appending (substring key 0 -1) key))
15497 (old (assoc-string key props t)))
15498 (if (not old) (cons (cons key val) props)
15499 (setcdr old (if appending (concat (cdr old) " " val) val))
15500 props)))
15502 (defun org-get-property-block (&optional beg force)
15503 "Return the (beg . end) range of the body of the property drawer.
15504 BEG is the beginning of the current subtree, or of the part
15505 before the first headline. If it is not given, it will be found.
15506 If the drawer does not exist, create it if FORCE is non-nil, or
15507 return nil."
15508 (org-with-wide-buffer
15509 (when beg (goto-char beg))
15510 (unless (org-before-first-heading-p)
15511 (let ((beg (cond (beg)
15512 ((or (not (featurep 'org-inlinetask))
15513 (org-inlinetask-in-task-p))
15514 (org-back-to-heading t))
15515 (t (org-with-limited-levels (org-back-to-heading t))))))
15516 (forward-line)
15517 (when (org-looking-at-p org-planning-line-re) (forward-line))
15518 (cond ((looking-at org-property-drawer-re)
15519 (forward-line)
15520 (cons (point) (progn (goto-char (match-end 0))
15521 (line-beginning-position))))
15522 (force
15523 (goto-char beg)
15524 (org-insert-property-drawer)
15525 (let ((pos (save-excursion (search-forward ":END:")
15526 (line-beginning-position))))
15527 (cons pos pos))))))))
15529 (defun org-at-property-p ()
15530 "Non-nil when point is inside a property drawer.
15531 See `org-property-re' for match data, if applicable."
15532 (save-excursion
15533 (beginning-of-line)
15534 (and (looking-at org-property-re)
15535 (let ((property-drawer (save-match-data (org-get-property-block))))
15536 (and property-drawer
15537 (>= (point) (car property-drawer))
15538 (< (point) (cdr property-drawer)))))))
15540 (defun org-property-action ()
15541 "Do an action on properties."
15542 (interactive)
15543 (unless (org-at-property-p) (user-error "Not at a property"))
15544 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15545 (let ((c (read-char-exclusive)))
15546 (cl-case c
15547 (?s (call-interactively #'org-set-property))
15548 (?d (call-interactively #'org-delete-property))
15549 (?D (call-interactively #'org-delete-property-globally))
15550 (?c (call-interactively #'org-compute-property-at-point))
15551 (otherwise (user-error "No such property action %c" c)))))
15553 (defun org-inc-effort ()
15554 "Increment the value of the effort property in the current entry."
15555 (interactive)
15556 (org-set-effort nil t))
15558 (defvar org-clock-effort) ; Defined in org-clock.el.
15559 (defvar org-clock-current-task) ; Defined in org-clock.el.
15560 (defun org-set-effort (&optional value increment)
15561 "Set the effort property of the current entry.
15562 With numerical prefix arg, use the nth allowed value, 0 stands for the
15563 10th allowed value.
15565 When INCREMENT is non-nil, set the property to the next allowed value."
15566 (interactive "P")
15567 (when (equal value 0) (setq value 10))
15568 (let* ((completion-ignore-case t)
15569 (prop org-effort-property)
15570 (cur (org-entry-get nil prop))
15571 (allowed (org-property-get-allowed-values nil prop 'table))
15572 (existing (mapcar 'list (org-property-values prop)))
15573 (heading (nth 4 (org-heading-components)))
15575 (val (cond
15576 ((stringp value) value)
15577 ((and allowed (integerp value))
15578 (or (car (nth (1- value) allowed))
15579 (car (org-last allowed))))
15580 ((and allowed increment)
15581 (or (cl-caadr (member (list cur) allowed))
15582 (user-error "Allowed effort values are not set")))
15583 (allowed
15584 (message "Select 1-9,0, [RET%s]: %s"
15585 (if cur (concat "=" cur) "")
15586 (mapconcat 'car allowed " "))
15587 (setq rpl (read-char-exclusive))
15588 (if (equal rpl ?\r)
15590 (setq rpl (- rpl ?0))
15591 (when (equal rpl 0) (setq rpl 10))
15592 (if (and (> rpl 0) (<= rpl (length allowed)))
15593 (car (nth (1- rpl) allowed))
15594 (org-completing-read "Effort: " allowed nil))))
15596 (let (org-completion-use-ido org-completion-use-iswitchb)
15597 (org-completing-read
15598 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15599 (concat "[" cur "]") "")
15600 ": ")
15601 existing nil nil "" nil cur))))))
15602 (unless (equal (org-entry-get nil prop) val)
15603 (org-entry-put nil prop val))
15604 (org-refresh-property
15605 '((effort . identity)
15606 (effort-minutes . org-duration-string-to-minutes))
15607 val)
15608 (when (string= heading org-clock-current-task)
15609 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15610 (org-clock-update-mode-line))
15611 (message "%s is now %s" prop val)))
15613 (defun org-entry-properties (&optional pom which)
15614 "Get all properties of the current entry.
15616 When POM is a buffer position, get all properties from the entry
15617 there instead.
15619 This includes the TODO keyword, the tags, time strings for
15620 deadline, scheduled, and clocking, and any additional properties
15621 defined in the entry.
15623 If WHICH is nil or `all', get all properties. If WHICH is
15624 `special' or `standard', only get that subclass. If WHICH is
15625 a string, only get that property.
15627 Return value is an alist. Keys are properties, as upcased
15628 strings."
15629 (org-with-point-at pom
15630 (when (and (derived-mode-p 'org-mode)
15631 (ignore-errors (org-back-to-heading t)))
15632 (catch 'exit
15633 (let* ((beg (point))
15634 (specific (and (stringp which) (upcase which)))
15635 (which (cond ((not specific) which)
15636 ((member specific org-special-properties) 'special)
15637 (t 'standard)))
15638 props)
15639 ;; Get the special properties, like TODO and TAGS.
15640 (when (memq which '(nil all special))
15641 (when (or (not specific) (string= specific "CLOCKSUM"))
15642 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15643 (when clocksum
15644 (push (cons "CLOCKSUM"
15645 (org-columns-number-to-string
15646 (/ (float clocksum) 60.) 'add_times))
15647 props)))
15648 (when specific (throw 'exit props)))
15649 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15650 (let ((clocksumt (get-text-property (point)
15651 :org-clock-minutes-today)))
15652 (when clocksumt
15653 (push (cons "CLOCKSUM_T"
15654 (org-columns-number-to-string
15655 (/ (float clocksumt) 60.) 'add_times))
15656 props)))
15657 (when specific (throw 'exit props)))
15658 (when (or (not specific) (string= specific "ITEM"))
15659 (when (looking-at org-complex-heading-regexp)
15660 (push (cons "ITEM"
15661 (concat
15662 (org-match-string-no-properties 1)
15663 (let ((title (org-match-string-no-properties 4)))
15664 (when (org-string-nw-p title)
15665 (concat " " (org-remove-tabs title))))))
15666 props))
15667 (when specific (throw 'exit props)))
15668 (when (or (not specific) (string= specific "TODO"))
15669 (let ((case-fold-search nil))
15670 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15671 (push (cons "TODO" (org-match-string-no-properties 2)) props)))
15672 (when specific (throw 'exit props)))
15673 (when (or (not specific) (string= specific "PRIORITY"))
15674 (push (cons "PRIORITY"
15675 (if (looking-at org-priority-regexp)
15676 (org-match-string-no-properties 2)
15677 (char-to-string org-default-priority)))
15678 props)
15679 (when specific (throw 'exit props)))
15680 (when (or (not specific) (string= specific "FILE"))
15681 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15682 props)
15683 (when specific (throw 'exit props)))
15684 (when (or (not specific) (string= specific "TAGS"))
15685 (let ((value (org-string-nw-p (org-get-tags-string))))
15686 (when value (push (cons "TAGS" value) props)))
15687 (when specific (throw 'exit props)))
15688 (when (or (not specific) (string= specific "ALLTAGS"))
15689 (let ((value (org-get-tags-at)))
15690 (when value
15691 (push (cons "ALLTAGS"
15692 (format ":%s:" (mapconcat #'identity value ":")))
15693 props)))
15694 (when specific (throw 'exit props)))
15695 (when (or (not specific) (string= specific "BLOCKED"))
15696 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15697 (when specific (throw 'exit props)))
15698 (when (or (not specific)
15699 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15700 (forward-line)
15701 (when (org-looking-at-p org-planning-line-re)
15702 (end-of-line)
15703 (let ((bol (line-beginning-position))
15704 ;; Backward compatibility: time keywords used to
15705 ;; be configurable (before 8.3). Make sure we
15706 ;; get the correct keyword.
15707 (key-assoc `(("CLOSED" . ,org-closed-string)
15708 ("DEADLINE" . ,org-deadline-string)
15709 ("SCHEDULED" . ,org-scheduled-string))))
15710 (dolist (pair (if specific (list (assoc specific key-assoc))
15711 key-assoc))
15712 (save-excursion
15713 (when (search-backward (cdr pair) bol t)
15714 (goto-char (match-end 0))
15715 (skip-chars-forward " \t")
15716 (and (looking-at org-ts-regexp-both)
15717 (push (cons (car pair)
15718 (org-match-string-no-properties 0))
15719 props)))))))
15720 (when specific (throw 'exit props)))
15721 (when (or (not specific)
15722 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15723 (let ((find-ts
15724 (lambda (end ts)
15725 ;; Fix next time-stamp before END. TS is the
15726 ;; list of time-stamps found so far.
15727 (let ((ts ts)
15728 (regexp (cond
15729 ((string= specific "TIMESTAMP")
15730 org-ts-regexp)
15731 ((string= specific "TIMESTAMP_IA")
15732 org-ts-regexp-inactive)
15733 ((assoc "TIMESTAMP_IA" ts)
15734 org-ts-regexp)
15735 ((assoc "TIMESTAMP" ts)
15736 org-ts-regexp-inactive)
15737 (t org-ts-regexp-both))))
15738 (catch 'next
15739 (while (re-search-forward regexp end t)
15740 (backward-char)
15741 (let ((object (org-element-context)))
15742 ;; Accept to match timestamps in node
15743 ;; properties, too.
15744 (when (memq (org-element-type object)
15745 '(node-property timestamp))
15746 (let ((type
15747 (org-element-property :type object)))
15748 (cond
15749 ((and (memq type '(active active-range))
15750 (not (equal specific "TIMESTAMP_IA")))
15751 (unless (assoc "TIMESTAMP" ts)
15752 (push (cons "TIMESTAMP"
15753 (org-element-property
15754 :raw-value object))
15756 (when specific (throw 'exit ts))))
15757 ((and (memq type '(inactive inactive-range))
15758 (not (string= specific "TIMESTAMP")))
15759 (unless (assoc "TIMESTAMP_IA" ts)
15760 (push (cons "TIMESTAMP_IA"
15761 (org-element-property
15762 :raw-value object))
15764 (when specific (throw 'exit ts))))))
15765 ;; Both timestamp types are found,
15766 ;; move to next part.
15767 (when (= (length ts) 2) (throw 'next ts)))))
15768 ts)))))
15769 (goto-char beg)
15770 ;; First look for timestamps within headline.
15771 (let ((ts (funcall find-ts (line-end-position) nil)))
15772 (if (= (length ts) 2) (setq props (nconc ts props))
15773 (forward-line)
15774 ;; Then find timestamps in the section, skipping
15775 ;; planning line.
15776 (when (org-looking-at-p org-planning-line-re)
15777 (forward-line))
15778 (let ((end (save-excursion (outline-next-heading))))
15779 (setq props (nconc (funcall find-ts end ts) props))))))))
15780 ;; Get the standard properties, like :PROP:.
15781 (when (memq which '(nil all standard))
15782 ;; If we are looking after a specific property, delegate
15783 ;; to `org-entry-get', which is faster. However, make an
15784 ;; exception for "CATEGORY", since it can be also set
15785 ;; through keywords (i.e. #+CATEGORY).
15786 (if (and specific (not (equal specific "CATEGORY")))
15787 (let ((value (org-entry-get beg specific nil t)))
15788 (throw 'exit (and value (list (cons specific value)))))
15789 (let ((range (org-get-property-block beg)))
15790 (when range
15791 (let ((end (cdr range)) seen-base)
15792 (goto-char (car range))
15793 ;; Unlike to `org--update-property-plist', we
15794 ;; handle the case where base values is found
15795 ;; after its extension. We also forbid standard
15796 ;; properties to be named as special properties.
15797 (while (re-search-forward org-property-re end t)
15798 (let* ((key (upcase (org-match-string-no-properties 2)))
15799 (extendp (org-string-match-p "\\+\\'" key))
15800 (key-base (if extendp (substring key 0 -1) key))
15801 (value (org-match-string-no-properties 3)))
15802 (cond
15803 ((member-ignore-case key-base org-special-properties))
15804 (extendp
15805 (setq props
15806 (org--update-property-plist key value props)))
15807 ((member key seen-base))
15808 (t (push key seen-base)
15809 (let ((p (assoc-string key props t)))
15810 (if p (setcdr p (concat value " " (cdr p)))
15811 (push (cons key value) props))))))))))))
15812 (unless (assoc "CATEGORY" props)
15813 (push (cons "CATEGORY" (org-get-category beg)) props)
15814 (when (string= specific "CATEGORY") (throw 'exit props)))
15815 ;; Return value.
15816 props)))))
15818 (defun org-property--local-values (property literal-nil)
15819 "Return value for PROPERTY in current entry.
15820 Value is a list whose care is the base value for PROPERTY and cdr
15821 a list of accumulated values. Return nil if neither is found in
15822 the entry. Also return nil when PROPERTY is set to \"nil\",
15823 unless LITERAL-NIL is non-nil."
15824 (let ((range (org-get-property-block)))
15825 (when range
15826 (goto-char (car range))
15827 (let* ((case-fold-search t)
15828 (end (cdr range))
15829 (value
15830 ;; Base value.
15831 (save-excursion
15832 (let ((v (and (re-search-forward
15833 (org-re-property property nil t) end t)
15834 (org-match-string-no-properties 3))))
15835 (list (if literal-nil v (org-not-nil v)))))))
15836 ;; Find additional values.
15837 (let* ((property+ (org-re-property (concat property "+") nil t)))
15838 (while (re-search-forward property+ end t)
15839 (push (org-match-string-no-properties 3) value)))
15840 ;; Return final values.
15841 (and (not (equal value '(nil))) (nreverse value))))))
15843 (defun org-entry-get (pom property &optional inherit literal-nil)
15844 "Get value of PROPERTY for entry or content at point-or-marker POM.
15846 If INHERIT is non-nil and the entry does not have the property,
15847 then also check higher levels of the hierarchy. If INHERIT is
15848 the symbol `selective', use inheritance only if the setting in
15849 `org-use-property-inheritance' selects PROPERTY for inheritance.
15851 If the property is present but empty, the return value is the
15852 empty string. If the property is not present at all, nil is
15853 returned. In any other case, return the value as a string.
15854 Search is case-insensitive.
15856 If LITERAL-NIL is set, return the string value \"nil\" as
15857 a string, do not interpret it as the list atom nil. This is used
15858 for inheritance when a \"nil\" value can supersede a non-nil
15859 value higher up the hierarchy."
15860 (org-with-point-at pom
15861 (cond
15862 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15863 ;; We need a special property. Use `org-entry-properties' to
15864 ;; retrieve it, but specify the wanted property.
15865 (cdr (assoc-string property (org-entry-properties nil property))))
15866 ((and inherit
15867 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15868 (org-entry-get-with-inheritance property literal-nil))
15870 (let* ((local (org-property--local-values property literal-nil))
15871 (value (and local (mapconcat #'identity (delq nil local) " "))))
15872 (if literal-nil value (org-not-nil value)))))))
15874 (defun org-property-or-variable-value (var &optional inherit)
15875 "Check if there is a property fixing the value of VAR.
15876 If yes, return this value. If not, return the current value of the variable."
15877 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15878 (if (and prop (stringp prop) (string-match "\\S-" prop))
15879 (read prop)
15880 (symbol-value var))))
15882 (defun org-entry-delete (pom property)
15883 "Delete PROPERTY from entry at point-or-marker POM.
15884 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15885 non-nil when a property was removed."
15886 (unless (member property org-special-properties)
15887 (org-with-point-at pom
15888 (let ((range (org-get-property-block)))
15889 (when range
15890 (let* ((begin (car range))
15891 (origin (cdr range))
15892 (end (copy-marker origin))
15893 (re (org-re-property
15894 (concat (regexp-quote property) "\\+?") t t)))
15895 (goto-char begin)
15896 (while (re-search-forward re end t)
15897 (delete-region (match-beginning 0) (line-beginning-position 2)))
15898 ;; If drawer is empty, remove it altogether.
15899 (when (= begin end)
15900 (delete-region (line-beginning-position 0)
15901 (line-beginning-position 2)))
15902 ;; Return non-nil if some property was removed.
15903 (prog1 (/= end origin) (set-marker end nil))))))))
15905 ;; Multi-values properties are properties that contain multiple values
15906 ;; These values are assumed to be single words, separated by whitespace.
15907 (defun org-entry-add-to-multivalued-property (pom property value)
15908 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15909 (let* ((old (org-entry-get pom property))
15910 (values (and old (org-split-string old "[ \t]"))))
15911 (setq value (org-entry-protect-space value))
15912 (unless (member value values)
15913 (setq values (append values (list value)))
15914 (org-entry-put pom property
15915 (mapconcat 'identity values " ")))))
15917 (defun org-entry-remove-from-multivalued-property (pom property value)
15918 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15919 (let* ((old (org-entry-get pom property))
15920 (values (and old (org-split-string old "[ \t]"))))
15921 (setq value (org-entry-protect-space value))
15922 (when (member value values)
15923 (setq values (delete value values))
15924 (org-entry-put pom property
15925 (mapconcat 'identity values " ")))))
15927 (defun org-entry-member-in-multivalued-property (pom property value)
15928 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15929 (let* ((old (org-entry-get pom property))
15930 (values (and old (org-split-string old "[ \t]"))))
15931 (setq value (org-entry-protect-space value))
15932 (member value values)))
15934 (defun org-entry-get-multivalued-property (pom property)
15935 "Return a list of values in a multivalued property."
15936 (let* ((value (org-entry-get pom property))
15937 (values (and value (org-split-string value "[ \t]"))))
15938 (mapcar 'org-entry-restore-space values)))
15940 (defun org-entry-put-multivalued-property (pom property &rest values)
15941 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15942 VALUES should be a list of strings. Spaces will be protected."
15943 (org-entry-put pom property
15944 (mapconcat 'org-entry-protect-space values " "))
15945 (let* ((value (org-entry-get pom property))
15946 (values (and value (org-split-string value "[ \t]"))))
15947 (mapcar 'org-entry-restore-space values)))
15949 (defun org-entry-protect-space (s)
15950 "Protect spaces and newline in string S."
15951 (while (string-match " " s)
15952 (setq s (replace-match "%20" t t s)))
15953 (while (string-match "\n" s)
15954 (setq s (replace-match "%0A" t t s)))
15957 (defun org-entry-restore-space (s)
15958 "Restore spaces and newline in string S."
15959 (while (string-match "%20" s)
15960 (setq s (replace-match " " t t s)))
15961 (while (string-match "%0A" s)
15962 (setq s (replace-match "\n" t t s)))
15965 (defvar org-entry-property-inherited-from (make-marker)
15966 "Marker pointing to the entry from where a property was inherited.
15967 Each call to `org-entry-get-with-inheritance' will set this marker to the
15968 location of the entry where the inheritance search matched. If there was
15969 no match, the marker will point nowhere.
15970 Note that also `org-entry-get' calls this function, if the INHERIT flag
15971 is set.")
15973 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15974 "Get PROPERTY of entry or content at point, search higher levels if needed.
15975 The search will stop at the first ancestor which has the property defined.
15976 If the value found is \"nil\", return nil to show that the property
15977 should be considered as undefined (this is the meaning of nil here).
15978 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15979 (move-marker org-entry-property-inherited-from nil)
15980 (org-with-wide-buffer
15981 (let (value)
15982 (catch 'exit
15983 (while t
15984 (let ((v (org-property--local-values property literal-nil)))
15985 (when v
15986 (setq value
15987 (concat (mapconcat #'identity (delq nil v) " ")
15988 (and value " ")
15989 value)))
15990 (cond
15991 ((car v)
15992 (org-back-to-heading t)
15993 (move-marker org-entry-property-inherited-from (point))
15994 (throw 'exit nil))
15995 ((org-up-heading-safe))
15997 (let ((global
15998 (cdr (or (assoc-string property org-file-properties t)
15999 (assoc-string property org-global-properties t)
16000 (assoc-string property org-global-properties-fixed t)))))
16001 (cond ((not global))
16002 (value (setq value (concat global " " value)))
16003 (t (setq value global))))
16004 (throw 'exit nil))))))
16005 (if literal-nil value (org-not-nil value)))))
16007 (defvar org-property-changed-functions nil
16008 "Hook called when the value of a property has changed.
16009 Each hook function should accept two arguments, the name of the property
16010 and the new value.")
16012 (defun org-entry-put (pom property value)
16013 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16015 If the value is nil, it is converted to the empty string. If it
16016 is not a string, an error is raised. Also raise an error on
16017 invalid property names.
16019 PROPERTY can be any regular property (see
16020 `org-special-properties'). It can also be \"TODO\",
16021 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16023 For the last two properties, VALUE may have any of the special
16024 values \"earlier\" and \"later\". The function then increases or
16025 decreases scheduled or deadline date by one day."
16026 (cond ((null value) (setq value ""))
16027 ((not (stringp value)) (error "Properties values should be strings"))
16028 ((not (org--valid-property-p property))
16029 (user-error "Invalid property name: \"%s\"" property)))
16030 (org-with-point-at pom
16031 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16032 (org-back-to-heading t)
16033 (org-with-limited-levels (org-back-to-heading t)))
16034 (let ((beg (point)))
16035 (cond
16036 ((equal property "TODO")
16037 (cond ((not (org-string-nw-p value)) (setq value 'none))
16038 ((not (member value org-todo-keywords-1))
16039 (user-error "\"%s\" is not a valid TODO state" value)))
16040 (org-todo value)
16041 (org-set-tags nil 'align))
16042 ((equal property "PRIORITY")
16043 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16044 (org-set-tags nil 'align))
16045 ((equal property "SCHEDULED")
16046 (forward-line)
16047 (if (and (org-looking-at-p org-planning-line-re)
16048 (re-search-forward
16049 org-scheduled-time-regexp (line-end-position) t))
16050 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16051 ((string= value "later") (org-timestamp-change 1 'day))
16052 ((string= value "") (org-schedule '(4)))
16053 (t (org-schedule nil value)))
16054 (if (member value '("earlier" "later" ""))
16055 (call-interactively #'org-schedule)
16056 (org-schedule nil value))))
16057 ((equal property "DEADLINE")
16058 (forward-line)
16059 (if (and (org-looking-at-p org-planning-line-re)
16060 (re-search-forward
16061 org-deadline-time-regexp (line-end-position) t))
16062 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16063 ((string= value "later") (org-timestamp-change 1 'day))
16064 ((string= value "") (org-deadline '(4)))
16065 (t (org-deadline nil value)))
16066 (if (member value '("earlier" "later" ""))
16067 (call-interactively #'org-deadline)
16068 (org-deadline nil value))))
16069 ((member property org-special-properties)
16070 (error "The %s property cannot be set with `org-entry-put'" property))
16072 (let* ((range (org-get-property-block beg 'force))
16073 (end (cdr range))
16074 (case-fold-search t))
16075 (goto-char (car range))
16076 (if (re-search-forward (org-re-property property nil t) end t)
16077 (progn (delete-region (match-beginning 0) (match-end 0))
16078 (goto-char (match-beginning 0)))
16079 (goto-char end)
16080 (insert "\n")
16081 (backward-char))
16082 (insert ":" property ":")
16083 (when value (insert " " value))
16084 (org-indent-line)))))
16085 (run-hook-with-args 'org-property-changed-functions property value)))
16087 (defun org-buffer-property-keys
16088 (&optional specials defaults columns ignore-malformed)
16089 "Get all property keys in the current buffer.
16091 When SPECIALS is non-nil, also list the special properties that
16092 reflect things like tags and TODO state.
16094 When DEFAULTS is non-nil, also include properties that has
16095 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16096 DESCRIPTION, LOCATION, and LOGGING and others.
16098 When COLUMNS in non-nil, also include property names given in
16099 COLUMN formats in the current buffer.
16101 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16102 automatically performed, such drawers will be silently ignored."
16103 (let ((case-fold-search t)
16104 (props (append
16105 (and specials org-special-properties)
16106 (and defaults (cons org-effort-property org-default-properties))
16107 nil)))
16108 (org-with-wide-buffer
16109 (goto-char (point-min))
16110 (while (re-search-forward org-property-start-re nil t)
16111 (let ((range (org-get-property-block)))
16112 (catch 'skip
16113 (unless range
16114 (when (and (not ignore-malformed)
16115 (not (org-before-first-heading-p))
16116 (y-or-n-p (format "Malformed drawer at %d, repair?"
16117 (line-beginning-position))))
16118 (org-get-property-block nil t))
16119 (throw 'skip nil))
16120 (goto-char (car range))
16121 (let ((begin (car range))
16122 (end (cdr range)))
16123 ;; Make sure that found property block is not located
16124 ;; before current point, as it would generate an infloop.
16125 ;; It can happen, for example, in the following
16126 ;; situation:
16128 ;; * Headline
16129 ;; :PROPERTIES:
16130 ;; ...
16131 ;; :END:
16132 ;; *************** Inlinetask
16133 ;; #+BEGIN_EXAMPLE
16134 ;; :PROPERTIES:
16135 ;; #+END_EXAMPLE
16137 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16138 (while (< (point) end)
16139 (let ((p (progn (looking-at org-property-re)
16140 (org-match-string-no-properties 2))))
16141 ;; Only add true property name, not extension symbol.
16142 (push (if (not (org-string-match-p "\\+\\'" p)) p
16143 (substring p 0 -1))
16144 props))
16145 (forward-line))))
16146 (outline-next-heading)))
16147 (when columns
16148 (goto-char (point-min))
16149 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16150 (let ((element (org-element-at-point)))
16151 (when (memq (org-element-type element) '(keyword node-property))
16152 (let ((value (org-element-property :value element))
16153 (start 0))
16154 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16155 (setq start (match-end 0))
16156 (let ((p (org-match-string-no-properties 1 value)))
16157 (unless (member-ignore-case p org-special-properties)
16158 (push p props))))))))))
16159 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16161 (defun org-property-values (key)
16162 "List all non-nil values of property KEY in current buffer."
16163 (org-with-wide-buffer
16164 (goto-char (point-min))
16165 (let ((case-fold-search t)
16166 (re (org-re-property key))
16167 values)
16168 (while (re-search-forward re nil t)
16169 (push (org-entry-get (point) key) values))
16170 (delete-dups values))))
16172 (defun org-insert-property-drawer ()
16173 "Insert a property drawer into the current entry."
16174 (org-with-wide-buffer
16175 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16176 (org-back-to-heading t)
16177 (org-with-limited-levels (org-back-to-heading t)))
16178 (forward-line)
16179 (when (org-looking-at-p org-planning-line-re) (forward-line))
16180 (unless (org-looking-at-p org-property-drawer-re)
16181 ;; Make sure we start editing a line from current entry, not from
16182 ;; next one. It prevents extending text properties or overlays
16183 ;; belonging to the latter.
16184 (when (bolp) (backward-char))
16185 (let ((begin (1+ (point)))
16186 (inhibit-read-only t))
16187 (insert "\n:PROPERTIES:\n:END:")
16188 (when (eobp) (insert "\n"))
16189 (org-indent-region begin (point))))))
16191 (defun org-insert-drawer (&optional arg drawer)
16192 "Insert a drawer at point.
16194 When optional argument ARG is non-nil, insert a property drawer.
16196 Optional argument DRAWER, when non-nil, is a string representing
16197 drawer's name. Otherwise, the user is prompted for a name.
16199 If a region is active, insert the drawer around that region
16200 instead.
16202 Point is left between drawer's boundaries."
16203 (interactive "P")
16204 (let* ((drawer (if arg "PROPERTIES"
16205 (or drawer (read-from-minibuffer "Drawer: ")))))
16206 (cond
16207 ;; With C-u, fall back on `org-insert-property-drawer'
16208 (arg (org-insert-property-drawer))
16209 ;; Check validity of suggested drawer's name.
16210 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
16211 (user-error "Invalid drawer name"))
16212 ;; With an active region, insert a drawer at point.
16213 ((not (org-region-active-p))
16214 (progn
16215 (unless (bolp) (insert "\n"))
16216 (insert (format ":%s:\n\n:END:\n" drawer))
16217 (forward-line -2)))
16218 ;; Otherwise, insert the drawer at point
16220 (let ((rbeg (region-beginning))
16221 (rend (copy-marker (region-end))))
16222 (unwind-protect
16223 (progn
16224 (goto-char rbeg)
16225 (beginning-of-line)
16226 (when (save-excursion
16227 (re-search-forward org-outline-regexp-bol rend t))
16228 (user-error "Drawers cannot contain headlines"))
16229 ;; Position point at the beginning of the first
16230 ;; non-blank line in region. Insert drawer's opening
16231 ;; there, then indent it.
16232 (org-skip-whitespace)
16233 (beginning-of-line)
16234 (insert ":" drawer ":\n")
16235 (forward-line -1)
16236 (indent-for-tab-command)
16237 ;; Move point to the beginning of the first blank line
16238 ;; after the last non-blank line in region. Insert
16239 ;; drawer's closing, then indent it.
16240 (goto-char rend)
16241 (skip-chars-backward " \r\t\n")
16242 (insert "\n:END:")
16243 (deactivate-mark t)
16244 (indent-for-tab-command)
16245 (unless (eolp) (insert "\n")))
16246 ;; Clear marker, whatever the outcome of insertion is.
16247 (set-marker rend nil)))))))
16249 (defvar org-property-set-functions-alist nil
16250 "Property set function alist.
16251 Each entry should have the following format:
16253 (PROPERTY . READ-FUNCTION)
16255 The read function will be called with the same argument as
16256 `org-completing-read'.")
16258 (defun org-set-property-function (property)
16259 "Get the function that should be used to set PROPERTY.
16260 This is computed according to `org-property-set-functions-alist'."
16261 (or (cdr (assoc property org-property-set-functions-alist))
16262 'org-completing-read))
16264 (defun org-read-property-value (property)
16265 "Read PROPERTY value from user."
16266 (let* ((completion-ignore-case t)
16267 (allowed (org-property-get-allowed-values nil property 'table))
16268 (cur (org-entry-get nil property))
16269 (prompt (concat property " value"
16270 (if (and cur (string-match "\\S-" cur))
16271 (concat " [" cur "]") "") ": "))
16272 (set-function (org-set-property-function property))
16273 (val (if allowed
16274 (funcall set-function prompt allowed nil
16275 (not (get-text-property 0 'org-unrestricted
16276 (caar allowed))))
16277 (let (org-completion-use-ido org-completion-use-iswitchb)
16278 (funcall set-function prompt
16279 (mapcar 'list (org-property-values property))
16280 nil nil "" nil cur)))))
16281 (org-trim val)))
16283 (defvar org-last-set-property nil)
16284 (defvar org-last-set-property-value nil)
16285 (defun org-read-property-name ()
16286 "Read a property name."
16287 (let ((completion-ignore-case t)
16288 (default-prop (or (and (org-at-property-p)
16289 (org-match-string-no-properties 2))
16290 org-last-set-property)))
16291 (org-completing-read
16292 (concat "Property"
16293 (if default-prop (concat " [" default-prop "]") "")
16294 ": ")
16295 (mapcar #'list (org-buffer-property-keys nil t t))
16296 nil nil nil nil default-prop)))
16298 (defun org-set-property-and-value (use-last)
16299 "Allow to set [PROPERTY]: [value] direction from prompt.
16300 When use-default, don't even ask, just use the last
16301 \"[PROPERTY]: [value]\" string from the history."
16302 (interactive "P")
16303 (let* ((completion-ignore-case t)
16304 (pv (or (and use-last org-last-set-property-value)
16305 (org-completing-read
16306 "Enter a \"[Property]: [value]\" pair: "
16307 nil nil nil nil nil
16308 org-last-set-property-value)))
16309 prop val)
16310 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16311 (setq prop (match-string 1 pv)
16312 val (match-string 2 pv))
16313 (org-set-property prop val))))
16315 (defun org-set-property (property value)
16316 "In the current entry, set PROPERTY to VALUE.
16318 When called interactively, this will prompt for a property name, offering
16319 completion on existing and default properties. And then it will prompt
16320 for a value, offering completion either on allowed values (via an inherited
16321 xxx_ALL property) or on existing values in other instances of this property
16322 in the current file.
16324 Throw an error when trying to set a property with an invalid name."
16325 (interactive (list nil nil))
16326 (let ((property (or property (org-read-property-name))))
16327 ;; `org-entry-put' also makes the following check, but this one
16328 ;; avoids polluting `org-last-set-property' and
16329 ;; `org-last-set-property-value' needlessly.
16330 (unless (org--valid-property-p property)
16331 (user-error "Invalid property name: \"%s\"" property))
16332 (let ((value (or value (org-read-property-value property)))
16333 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16334 (setq org-last-set-property property)
16335 (setq org-last-set-property-value (concat property ": " value))
16336 ;; Possibly postprocess the inserted value:
16337 (when fn (setq value (funcall fn value)))
16338 (unless (equal (org-entry-get nil property) value)
16339 (org-entry-put nil property value)))))
16341 (defun org-find-property (property &optional value)
16342 "Find first entry in buffer that sets PROPERTY.
16344 When optional argument VALUE is non-nil, only consider an entry
16345 if it contains PROPERTY set to this value. If PROPERTY should be
16346 explicitly set to nil, use string \"nil\" for VALUE.
16348 Return position where the entry begins, or nil if there is no
16349 such entry. If narrowing is in effect, only search the visible
16350 part of the buffer."
16351 (save-excursion
16352 (goto-char (point-min))
16353 (let ((case-fold-search t)
16354 (re (org-re-property property nil (not value) value)))
16355 (catch 'exit
16356 (while (re-search-forward re nil t)
16357 (when (if value (org-at-property-p)
16358 (org-entry-get (point) property nil t))
16359 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16361 (defun org-delete-property (property)
16362 "In the current entry, delete PROPERTY."
16363 (interactive
16364 (let* ((completion-ignore-case t)
16365 (cat (org-entry-get (point) "CATEGORY"))
16366 (props0 (org-entry-properties nil 'standard))
16367 (props (if cat props0
16368 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16369 (prop (if (< 1 (length props))
16370 (completing-read "Property: " props nil t)
16371 (caar props))))
16372 (list prop)))
16373 (if (not property)
16374 (message "No property to delete in this entry")
16375 (org-entry-delete nil property)
16376 (message "Property \"%s\" deleted" property)))
16378 (defun org-delete-property-globally (property)
16379 "Remove PROPERTY globally, from all entries.
16380 This function ignores narrowing, if any."
16381 (interactive
16382 (let* ((completion-ignore-case t)
16383 (prop (completing-read
16384 "Globally remove property: "
16385 (mapcar #'list (org-buffer-property-keys)))))
16386 (list prop)))
16387 (org-with-wide-buffer
16388 (goto-char (point-min))
16389 (let ((count 0)
16390 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16391 (while (re-search-forward re nil t)
16392 (when (org-entry-delete (point) property) (cl-incf count)))
16393 (message "Property \"%s\" removed from %d entries" property count))))
16395 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16397 (defun org-compute-property-at-point ()
16398 "Compute the property at point.
16399 This looks for an enclosing column format, extracts the operator and
16400 then applies it to the property in the column format's scope."
16401 (interactive)
16402 (unless (org-at-property-p)
16403 (user-error "Not at a property"))
16404 (let ((prop (org-match-string-no-properties 2)))
16405 (org-columns-get-format-and-top-level)
16406 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16407 (user-error "No operator defined for property %s" prop))
16408 (org-columns-compute prop)))
16410 (defvar org-property-allowed-value-functions nil
16411 "Hook for functions supplying allowed values for a specific property.
16412 The functions must take a single argument, the name of the property, and
16413 return a flat list of allowed values. If \":ETC\" is one of
16414 the values, this means that these values are intended as defaults for
16415 completion, but that other values should be allowed too.
16416 The functions must return nil if they are not responsible for this
16417 property.")
16419 (defun org-property-get-allowed-values (pom property &optional table)
16420 "Get allowed values for the property PROPERTY.
16421 When TABLE is non-nil, return an alist that can directly be used for
16422 completion."
16423 (let (vals)
16424 (cond
16425 ((equal property "TODO")
16426 (setq vals (org-with-point-at pom
16427 (append org-todo-keywords-1 '("")))))
16428 ((equal property "PRIORITY")
16429 (let ((n org-lowest-priority))
16430 (while (>= n org-highest-priority)
16431 (push (char-to-string n) vals)
16432 (setq n (1- n)))))
16433 ((equal property "CATEGORY"))
16434 ((member property org-special-properties))
16435 ((setq vals (run-hook-with-args-until-success
16436 'org-property-allowed-value-functions property)))
16438 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16439 (when (and vals (string-match "\\S-" vals))
16440 (setq vals (car (read-from-string (concat "(" vals ")"))))
16441 (setq vals (mapcar (lambda (x)
16442 (cond ((stringp x) x)
16443 ((numberp x) (number-to-string x))
16444 ((symbolp x) (symbol-name x))
16445 (t "???")))
16446 vals)))))
16447 (when (member ":ETC" vals)
16448 (setq vals (remove ":ETC" vals))
16449 (org-add-props (car vals) '(org-unrestricted t)))
16450 (if table (mapcar 'list vals) vals)))
16452 (defun org-property-previous-allowed-value (&optional _previous)
16453 "Switch to the next allowed value for this property."
16454 (interactive)
16455 (org-property-next-allowed-value t))
16457 (defun org-property-next-allowed-value (&optional previous)
16458 "Switch to the next allowed value for this property."
16459 (interactive)
16460 (unless (org-at-property-p)
16461 (user-error "Not at a property"))
16462 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16463 (key (match-string 2))
16464 (value (match-string 3))
16465 (allowed (or (org-property-get-allowed-values (point) key)
16466 (and (member value '("[ ]" "[-]" "[X]"))
16467 '("[ ]" "[X]"))))
16468 (heading (save-match-data (nth 4 (org-heading-components))))
16469 nval)
16470 (unless allowed
16471 (user-error "Allowed values for this property have not been defined"))
16472 (when previous (setq allowed (reverse allowed)))
16473 (when (member value allowed)
16474 (setq nval (car (cdr (member value allowed)))))
16475 (setq nval (or nval (car allowed)))
16476 (when (equal nval value)
16477 (user-error "Only one allowed value for this property"))
16478 (org-at-property-p)
16479 (replace-match (concat " :" key ": " nval) t t)
16480 (org-indent-line)
16481 (beginning-of-line 1)
16482 (skip-chars-forward " \t")
16483 (when (equal prop org-effort-property)
16484 (org-refresh-property
16485 '((effort . identity)
16486 (effort-minutes . org-duration-string-to-minutes))
16487 nval)
16488 (when (string= org-clock-current-task heading)
16489 (setq org-clock-effort nval)
16490 (org-clock-update-mode-line)))
16491 (run-hook-with-args 'org-property-changed-functions key nval)))
16493 (defun org-find-olp (path &optional this-buffer)
16494 "Return a marker pointing to the entry at outline path OLP.
16495 If anything goes wrong, throw an error.
16496 You can wrap this call to catch the error like this:
16498 \(condition-case msg
16499 \(org-mobile-locate-entry (match-string 4))
16500 \(error (nth 1 msg)))
16502 The return value will then be either a string with the error message,
16503 or a marker if everything is OK.
16505 If THIS-BUFFER is set, the outline path does not contain a file,
16506 only headings."
16507 (let* ((file (if this-buffer buffer-file-name (pop path)))
16508 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16509 (level 1)
16510 (lmin 1)
16511 (lmax 1)
16512 end found flevel)
16513 (unless buffer (error "File not found :%s" file))
16514 (with-current-buffer buffer
16515 (org-with-wide-buffer
16516 (goto-char (point-min))
16517 (dolist (heading path)
16518 (let ((re (format org-complex-heading-regexp-format
16519 (regexp-quote heading)))
16520 (cnt 0))
16521 (while (re-search-forward re end t)
16522 (setq level (- (match-end 1) (match-beginning 1)))
16523 (when (and (>= level lmin) (<= level lmax))
16524 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16525 (when (= cnt 0)
16526 (error "Heading not found on level %d: %s" lmax heading))
16527 (when (> cnt 1)
16528 (error "Heading not unique on level %d: %s" lmax heading))
16529 (goto-char found)
16530 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16531 (setq end (save-excursion (org-end-of-subtree t t)))))
16532 (when (org-at-heading-p)
16533 (point-marker))))))
16535 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16536 "Find node HEADING in BUFFER.
16537 Return a marker to the heading if it was found, or nil if not.
16538 If POS-ONLY is set, return just the position instead of a marker.
16540 The heading text must match exact, but it may have a TODO keyword,
16541 a priority cookie and tags in the standard locations."
16542 (with-current-buffer (or buffer (current-buffer))
16543 (save-excursion
16544 (save-restriction
16545 (widen)
16546 (goto-char (point-min))
16547 (let (case-fold-search)
16548 (when (re-search-forward
16549 (format org-complex-heading-regexp-format
16550 (regexp-quote heading)) nil t)
16551 (if pos-only
16552 (match-beginning 0)
16553 (move-marker (make-marker) (match-beginning 0)))))))))
16555 (defun org-find-exact-heading-in-directory (heading &optional dir)
16556 "Find Org node headline HEADING in all .org files in directory DIR.
16557 When the target headline is found, return a marker to this location."
16558 (let ((files (directory-files (or dir default-directory)
16559 t "\\`[^.#].*\\.org\\'"))
16560 visiting m buffer)
16561 (catch 'found
16562 (dolist (file files)
16563 (message "trying %s" file)
16564 (setq visiting (org-find-base-buffer-visiting file))
16565 (setq buffer (or visiting (find-file-noselect file)))
16566 (setq m (org-find-exact-headline-in-buffer
16567 heading buffer))
16568 (when (and (not m) (not visiting)) (kill-buffer buffer))
16569 (and m (throw 'found m))))))
16571 (defun org-find-entry-with-id (ident)
16572 "Locate the entry that contains the ID property with exact value IDENT.
16573 IDENT can be a string, a symbol or a number, this function will search for
16574 the string representation of it.
16575 Return the position where this entry starts, or nil if there is no such entry."
16576 (interactive "sID: ")
16577 (let ((id (cond
16578 ((stringp ident) ident)
16579 ((symbolp ident) (symbol-name ident))
16580 ((numberp ident) (number-to-string ident))
16581 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16582 (org-with-wide-buffer (org-find-property "ID" id))))
16584 ;;;; Timestamps
16586 (defvar org-last-changed-timestamp nil)
16587 (defvar org-last-inserted-timestamp nil
16588 "The last time stamp inserted with `org-insert-time-stamp'.")
16589 (defvar org-ts-what) ; dynamically scoped parameter
16591 (defun org-time-stamp (arg &optional inactive)
16592 "Prompt for a date/time and insert a time stamp.
16594 If the user specifies a time like HH:MM or if this command is
16595 called with at least one prefix argument, the time stamp contains
16596 the date and the time. Otherwise, only the date is included.
16598 All parts of a date not specified by the user are filled in from
16599 the timestamp at point, if any, or the current date/time
16600 otherwise.
16602 If there is already a timestamp at the cursor, it is replaced.
16604 With two universal prefix arguments, insert an active timestamp
16605 with the current time without prompting the user.
16607 When called from lisp, the timestamp is inactive if INACTIVE is
16608 non-nil."
16609 (interactive "P")
16610 (let* ((ts (cond
16611 ((org-at-date-range-p t)
16612 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16613 ((org-at-timestamp-p t) (match-string 0))))
16614 ;; Default time is either the timestamp at point or today.
16615 ;; When entering a range, only the range start is considered.
16616 (default-time (if (not ts) (current-time)
16617 (apply #'encode-time (org-parse-time-string ts))))
16618 (default-input (and ts (org-get-compact-tod ts)))
16619 (repeater (and ts
16620 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16621 (match-string 0 ts)))
16622 org-time-was-given
16623 org-end-time-was-given
16624 (time
16625 (and (if (equal arg '(16)) (current-time)
16626 ;; Preserve `this-command' and `last-command'.
16627 (let ((this-command this-command)
16628 (last-command last-command))
16629 (org-read-date
16630 arg 'totime nil nil default-time default-input
16631 inactive))))))
16632 (cond
16633 ((and ts
16634 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16635 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16636 (insert "--")
16637 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16639 ;; Make sure we're on a timestamp. When in the middle of a date
16640 ;; range, move arbitrarily to range end.
16641 (unless (org-at-timestamp-p t)
16642 (skip-chars-forward "-")
16643 (org-at-timestamp-p t))
16644 (replace-match "")
16645 (setq org-last-changed-timestamp
16646 (org-insert-time-stamp
16647 time (or org-time-was-given arg)
16648 inactive nil nil (list org-end-time-was-given)))
16649 (when repeater
16650 (backward-char)
16651 (insert " " repeater)
16652 (setq org-last-changed-timestamp
16653 (concat (substring org-last-inserted-timestamp 0 -1)
16654 " " repeater ">")))
16655 (message "Timestamp updated"))
16656 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16657 (t (org-insert-time-stamp
16658 time (or org-time-was-given arg) inactive nil nil
16659 (list org-end-time-was-given))))))
16661 ;; FIXME: can we use this for something else, like computing time differences?
16662 (defun org-get-compact-tod (s)
16663 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16664 (let* ((t1 (match-string 1 s))
16665 (h1 (string-to-number (match-string 2 s)))
16666 (m1 (string-to-number (match-string 3 s)))
16667 (t2 (and (match-end 4) (match-string 5 s)))
16668 (h2 (and t2 (string-to-number (match-string 6 s))))
16669 (m2 (and t2 (string-to-number (match-string 7 s))))
16670 dh dm)
16671 (if (not t2)
16673 (setq dh (- h2 h1) dm (- m2 m1))
16674 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16675 (concat t1 "+" (number-to-string dh)
16676 (and (/= 0 dm) (format ":%02d" dm)))))))
16678 (defun org-time-stamp-inactive (&optional arg)
16679 "Insert an inactive time stamp.
16680 An inactive time stamp is enclosed in square brackets instead of angle
16681 brackets. It is inactive in the sense that it does not trigger agenda entries,
16682 does not link to the calendar and cannot be changed with the S-cursor keys.
16683 So these are more for recording a certain time/date."
16684 (interactive "P")
16685 (org-time-stamp arg 'inactive))
16687 (defvar org-date-ovl (make-overlay 1 1))
16688 (overlay-put org-date-ovl 'face 'org-date-selected)
16689 (org-detach-overlay org-date-ovl)
16691 (defvar org-ans1) ; dynamically scoped parameter
16692 (defvar org-ans2) ; dynamically scoped parameter
16694 (defvar org-plain-time-of-day-regexp) ; defined below
16696 (defvar org-overriding-default-time nil) ; dynamically scoped
16697 (defvar org-read-date-overlay nil)
16698 (defvar org-dcst nil) ; dynamically scoped
16699 (defvar org-read-date-history nil)
16700 (defvar org-read-date-final-answer nil)
16701 (defvar org-read-date-analyze-futurep nil)
16702 (defvar org-read-date-analyze-forced-year nil)
16703 (defvar org-read-date-inactive)
16705 (defvar org-read-date-minibuffer-local-map
16706 (let* ((map (make-sparse-keymap)))
16707 (set-keymap-parent map minibuffer-local-map)
16708 (org-defkey map (kbd ".")
16709 (lambda () (interactive)
16710 ;; Are we at the beginning of the prompt?
16711 (if (org-looking-back "^[^:]+: "
16712 (let ((inhibit-field-text-motion t))
16713 (line-beginning-position)))
16714 (org-eval-in-calendar '(calendar-goto-today))
16715 (insert "."))))
16716 (org-defkey map (kbd "C-.")
16717 (lambda () (interactive)
16718 (org-eval-in-calendar '(calendar-goto-today))))
16719 (org-defkey map [(meta shift left)]
16720 (lambda () (interactive)
16721 (org-eval-in-calendar '(calendar-backward-month 1))))
16722 (org-defkey map [(meta shift right)]
16723 (lambda () (interactive)
16724 (org-eval-in-calendar '(calendar-forward-month 1))))
16725 (org-defkey map [(meta shift up)]
16726 (lambda () (interactive)
16727 (org-eval-in-calendar '(calendar-backward-year 1))))
16728 (org-defkey map [(meta shift down)]
16729 (lambda () (interactive)
16730 (org-eval-in-calendar '(calendar-forward-year 1))))
16731 (org-defkey map [?\e (shift left)]
16732 (lambda () (interactive)
16733 (org-eval-in-calendar '(calendar-backward-month 1))))
16734 (org-defkey map [?\e (shift right)]
16735 (lambda () (interactive)
16736 (org-eval-in-calendar '(calendar-forward-month 1))))
16737 (org-defkey map [?\e (shift up)]
16738 (lambda () (interactive)
16739 (org-eval-in-calendar '(calendar-backward-year 1))))
16740 (org-defkey map [?\e (shift down)]
16741 (lambda () (interactive)
16742 (org-eval-in-calendar '(calendar-forward-year 1))))
16743 (org-defkey map [(shift up)]
16744 (lambda () (interactive)
16745 (org-eval-in-calendar '(calendar-backward-week 1))))
16746 (org-defkey map [(shift down)]
16747 (lambda () (interactive)
16748 (org-eval-in-calendar '(calendar-forward-week 1))))
16749 (org-defkey map [(shift left)]
16750 (lambda () (interactive)
16751 (org-eval-in-calendar '(calendar-backward-day 1))))
16752 (org-defkey map [(shift right)]
16753 (lambda () (interactive)
16754 (org-eval-in-calendar '(calendar-forward-day 1))))
16755 (org-defkey map "!"
16756 (lambda () (interactive)
16757 (org-eval-in-calendar '(diary-view-entries))
16758 (message "")))
16759 (org-defkey map ">"
16760 (lambda () (interactive)
16761 (org-eval-in-calendar '(calendar-scroll-left 1))))
16762 (org-defkey map "<"
16763 (lambda () (interactive)
16764 (org-eval-in-calendar '(calendar-scroll-right 1))))
16765 (org-defkey map "\C-v"
16766 (lambda () (interactive)
16767 (org-eval-in-calendar
16768 '(calendar-scroll-left-three-months 1))))
16769 (org-defkey map "\M-v"
16770 (lambda () (interactive)
16771 (org-eval-in-calendar
16772 '(calendar-scroll-right-three-months 1))))
16773 map)
16774 "Keymap for minibuffer commands when using `org-read-date'.")
16776 (defvar org-def)
16777 (defvar org-defdecode)
16778 (defvar org-with-time)
16780 (defvar calendar-setup) ; Dynamically scoped.
16781 (defun org-read-date (&optional with-time to-time from-string prompt
16782 default-time default-input inactive)
16783 "Read a date, possibly a time, and make things smooth for the user.
16784 The prompt will suggest to enter an ISO date, but you can also enter anything
16785 which will at least partially be understood by `parse-time-string'.
16786 Unrecognized parts of the date will default to the current day, month, year,
16787 hour and minute. If this command is called to replace a timestamp at point,
16788 or to enter the second timestamp of a range, the default time is taken
16789 from the existing stamp. Furthermore, the command prefers the future,
16790 so if you are giving a date where the year is not given, and the day-month
16791 combination is already past in the current year, it will assume you
16792 mean next year. For details, see the manual. A few examples:
16794 3-2-5 --> 2003-02-05
16795 feb 15 --> currentyear-02-15
16796 2/15 --> currentyear-02-15
16797 sep 12 9 --> 2009-09-12
16798 12:45 --> today 12:45
16799 22 sept 0:34 --> currentyear-09-22 0:34
16800 12 --> currentyear-currentmonth-12
16801 Fri --> nearest Friday after today
16802 -Tue --> last Tuesday
16803 etc.
16805 Furthermore you can specify a relative date by giving, as the *first* thing
16806 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16807 change in days weeks, months, years.
16808 With a single plus or minus, the date is relative to today. With a double
16809 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16810 +4d --> four days from today
16811 +4 --> same as above
16812 +2w --> two weeks from today
16813 ++5 --> five days from default date
16815 The function understands only English month and weekday abbreviations.
16817 While prompting, a calendar is popped up - you can also select the
16818 date with the mouse (button 1). The calendar shows a period of three
16819 months. To scroll it to other months, use the keys `>' and `<'.
16820 If you don't like the calendar, turn it off with
16821 (setq org-read-date-popup-calendar nil)
16823 With optional argument TO-TIME, the date will immediately be converted
16824 to an internal time.
16825 With an optional argument WITH-TIME, the prompt will suggest to
16826 also insert a time. Note that when WITH-TIME is not set, you can
16827 still enter a time, and this function will inform the calling routine
16828 about this change. The calling routine may then choose to change the
16829 format used to insert the time stamp into the buffer to include the time.
16830 With optional argument FROM-STRING, read from this string instead from
16831 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16832 the time/date that is used for everything that is not specified by the
16833 user."
16834 (require 'parse-time)
16835 (let* ((org-with-time with-time)
16836 (org-time-stamp-rounding-minutes
16837 (if (equal org-with-time '(16))
16838 '(0 0)
16839 org-time-stamp-rounding-minutes))
16840 (org-dcst org-display-custom-times)
16841 (ct (org-current-time))
16842 (org-def (or org-overriding-default-time default-time ct))
16843 (org-defdecode (decode-time org-def))
16844 (cur-frame (selected-frame))
16845 (mouse-autoselect-window nil) ; Don't let the mouse jump
16846 (calendar-setup
16847 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16848 (calendar-move-hook nil)
16849 (calendar-view-diary-initially-flag nil)
16850 (calendar-view-holidays-initially-flag nil)
16851 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16852 ;; Rationalize `org-def' and `org-defdecode', if required.
16853 (when (< (nth 2 org-defdecode) org-extend-today-until)
16854 (setf (nth 2 org-defdecode) -1)
16855 (setf (nth 1 org-defdecode) 59)
16856 (setq org-def (apply #'encode-time org-defdecode))
16857 (setq org-defdecode (decode-time org-def)))
16858 (let* ((timestr (format-time-string
16859 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16860 org-def))
16861 (prompt (concat (if prompt (concat prompt " ") "")
16862 (format "Date+time [%s]: " timestr))))
16863 (cond
16864 (from-string (setq ans from-string))
16865 (org-read-date-popup-calendar
16866 (save-excursion
16867 (save-window-excursion
16868 (calendar)
16869 (when (eq calendar-setup 'calendar-only)
16870 (setq cal-frame
16871 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16872 (select-frame cal-frame))
16873 (org-eval-in-calendar '(setq cursor-type nil) t)
16874 (unwind-protect
16875 (progn
16876 (calendar-forward-day (- (time-to-days org-def)
16877 (calendar-absolute-from-gregorian
16878 (calendar-current-date))))
16879 (org-eval-in-calendar nil t)
16880 (let* ((old-map (current-local-map))
16881 (map (copy-keymap calendar-mode-map))
16882 (minibuffer-local-map
16883 (copy-keymap org-read-date-minibuffer-local-map)))
16884 (org-defkey map (kbd "RET") 'org-calendar-select)
16885 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16886 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16887 (unwind-protect
16888 (progn
16889 (use-local-map map)
16890 (setq org-read-date-inactive inactive)
16891 (add-hook 'post-command-hook 'org-read-date-display)
16892 (setq org-ans0
16893 (read-string prompt
16894 default-input
16895 'org-read-date-history
16896 nil))
16897 ;; org-ans0: from prompt
16898 ;; org-ans1: from mouse click
16899 ;; org-ans2: from calendar motion
16900 (setq ans
16901 (concat org-ans0 " " (or org-ans1 org-ans2))))
16902 (remove-hook 'post-command-hook 'org-read-date-display)
16903 (use-local-map old-map)
16904 (when org-read-date-overlay
16905 (delete-overlay org-read-date-overlay)
16906 (setq org-read-date-overlay nil)))))
16907 (bury-buffer "*Calendar*")
16908 (when cal-frame
16909 (delete-frame cal-frame)
16910 (select-frame-set-input-focus cur-frame))))))
16912 (t ; Naked prompt only
16913 (unwind-protect
16914 (setq ans (read-string prompt default-input
16915 'org-read-date-history timestr))
16916 (when org-read-date-overlay
16917 (delete-overlay org-read-date-overlay)
16918 (setq org-read-date-overlay nil))))))
16920 (setq final (org-read-date-analyze ans org-def org-defdecode))
16922 (when org-read-date-analyze-forced-year
16923 (message "Year was forced into %s"
16924 (if org-read-date-force-compatible-dates
16925 "compatible range (1970-2037)"
16926 "range representable on this machine"))
16927 (ding))
16929 ;; One round trip to get rid of 34th of August and stuff like that....
16930 (setq final (decode-time (apply 'encode-time final)))
16932 (setq org-read-date-final-answer ans)
16934 (if to-time
16935 (apply 'encode-time final)
16936 (if (and (boundp 'org-time-was-given) org-time-was-given)
16937 (format "%04d-%02d-%02d %02d:%02d"
16938 (nth 5 final) (nth 4 final) (nth 3 final)
16939 (nth 2 final) (nth 1 final))
16940 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16942 (defun org-read-date-display ()
16943 "Display the current date prompt interpretation in the minibuffer."
16944 (when org-read-date-display-live
16945 (when org-read-date-overlay
16946 (delete-overlay org-read-date-overlay))
16947 (when (minibufferp (current-buffer))
16948 (save-excursion
16949 (end-of-line 1)
16950 (while (not (equal (buffer-substring
16951 (max (point-min) (- (point) 4)) (point))
16952 " "))
16953 (insert " ")))
16954 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16955 " " (or org-ans1 org-ans2)))
16956 (org-end-time-was-given nil)
16957 (f (org-read-date-analyze ans org-def org-defdecode))
16958 (fmts (if org-dcst
16959 org-time-stamp-custom-formats
16960 org-time-stamp-formats))
16961 (fmt (if (or org-with-time
16962 (and (boundp 'org-time-was-given) org-time-was-given))
16963 (cdr fmts)
16964 (car fmts)))
16965 (txt (format-time-string fmt (apply 'encode-time f)))
16966 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16967 (txt (concat "=> " txt)))
16968 (when (and org-end-time-was-given
16969 (string-match org-plain-time-of-day-regexp txt))
16970 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16971 org-end-time-was-given
16972 (substring txt (match-end 0)))))
16973 (when org-read-date-analyze-futurep
16974 (setq txt (concat txt " (=>F)")))
16975 (setq org-read-date-overlay
16976 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16977 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16979 (defun org-read-date-analyze (ans def defdecode)
16980 "Analyze the combined answer of the date prompt."
16981 ;; FIXME: cleanup and comment
16982 ;; Pass `current-time' result to `decode-time' (instead of calling
16983 ;; without arguments) so that only `current-time' has to be
16984 ;; overriden in tests.
16985 (let ((org-def def)
16986 (org-defdecode defdecode)
16987 (nowdecode (decode-time (current-time)))
16988 delta deltan deltaw deltadef year month day
16989 hour minute second wday pm h2 m2 tl wday1
16990 iso-year iso-weekday iso-week iso-date futurep kill-year)
16991 (setq org-read-date-analyze-futurep nil
16992 org-read-date-analyze-forced-year nil)
16993 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16994 (setq ans "+0"))
16996 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16997 (setq ans (replace-match "" t t ans)
16998 deltan (car delta)
16999 deltaw (nth 1 delta)
17000 deltadef (nth 2 delta)))
17002 ;; Check if there is an iso week date in there. If yes, store the
17003 ;; info and postpone interpreting it until the rest of the parsing
17004 ;; is done.
17005 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17006 (setq iso-year (when (match-end 1)
17007 (org-small-year-to-year
17008 (string-to-number (match-string 1 ans))))
17009 iso-weekday (when (match-end 3)
17010 (string-to-number (match-string 3 ans)))
17011 iso-week (string-to-number (match-string 2 ans)))
17012 (setq ans (replace-match "" t t ans)))
17014 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17015 (when (string-match
17016 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17017 (setq year (if (match-end 2)
17018 (string-to-number (match-string 2 ans))
17019 (progn (setq kill-year t)
17020 (string-to-number (format-time-string "%Y"))))
17021 month (string-to-number (match-string 3 ans))
17022 day (string-to-number (match-string 4 ans)))
17023 (when (< year 100) (setq year (+ 2000 year)))
17024 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17025 t nil ans)))
17027 ;; Help matching dotted european dates
17028 (when (string-match
17029 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17030 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17031 (setq kill-year t)
17032 (string-to-number (format-time-string "%Y")))
17033 day (string-to-number (match-string 1 ans))
17034 month (string-to-number (match-string 2 ans))
17035 ans (replace-match (format "%04d-%02d-%02d" year month day)
17036 t nil ans)))
17038 ;; Help matching american dates, like 5/30 or 5/30/7
17039 (when (string-match
17040 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17041 (setq year (if (match-end 4)
17042 (string-to-number (match-string 4 ans))
17043 (progn (setq kill-year t)
17044 (string-to-number (format-time-string "%Y"))))
17045 month (string-to-number (match-string 1 ans))
17046 day (string-to-number (match-string 2 ans)))
17047 (when (< year 100) (setq year (+ 2000 year)))
17048 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17049 t nil ans)))
17050 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17051 ;; If there is a time with am/pm, and *no* time without it, we convert
17052 ;; so that matching will be successful.
17053 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17054 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17055 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17056 (setq hour (string-to-number (match-string 1 ans))
17057 minute (if (match-end 3)
17058 (string-to-number (match-string 3 ans))
17060 pm (equal ?p
17061 (string-to-char (downcase (match-string 4 ans)))))
17062 (if (and (= hour 12) (not pm))
17063 (setq hour 0)
17064 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17065 (setq ans (replace-match (format "%02d:%02d" hour minute)
17066 t t ans))))
17068 ;; Check if a time range is given as a duration
17069 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17070 (setq hour (string-to-number (match-string 1 ans))
17071 h2 (+ hour (string-to-number (match-string 3 ans)))
17072 minute (string-to-number (match-string 2 ans))
17073 m2 (+ minute (if (match-end 5) (string-to-number
17074 (match-string 5 ans))0)))
17075 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17076 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17077 t t ans)))
17079 ;; Check if there is a time range
17080 (when (boundp 'org-end-time-was-given)
17081 (setq org-time-was-given nil)
17082 (when (and (string-match org-plain-time-of-day-regexp ans)
17083 (match-end 8))
17084 (setq org-end-time-was-given (match-string 8 ans))
17085 (setq ans (concat (substring ans 0 (match-beginning 7))
17086 (substring ans (match-end 7))))))
17088 (setq tl (parse-time-string ans)
17089 day (or (nth 3 tl) (nth 3 org-defdecode))
17090 month
17091 (cond ((nth 4 tl))
17092 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17093 ;; Day was specified. Make sure DAY+MONTH
17094 ;; combination happens in the future.
17095 ((nth 3 tl)
17096 (setq futurep t)
17097 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17098 (nth 4 nowdecode)))
17099 (t (nth 4 org-defdecode)))
17100 year
17101 (cond ((and (not kill-year) (nth 5 tl)))
17102 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17103 ;; Month was guessed in the future and is at least
17104 ;; equal to NOWDECODE's. Fix year accordingly.
17105 (futurep
17106 (if (or (> month (nth 4 nowdecode))
17107 (>= day (nth 3 nowdecode)))
17108 (nth 5 nowdecode)
17109 (1+ (nth 5 nowdecode))))
17110 ;; Month was specified. Make sure MONTH+YEAR
17111 ;; combination happens in the future.
17112 ((nth 4 tl)
17113 (setq futurep t)
17114 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17115 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17116 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17117 (t (nth 5 nowdecode))))
17118 (t (nth 5 org-defdecode)))
17119 hour (or (nth 2 tl) (nth 2 org-defdecode))
17120 minute (or (nth 1 tl) (nth 1 org-defdecode))
17121 second (or (nth 0 tl) 0)
17122 wday (nth 6 tl))
17124 (when (and (eq org-read-date-prefer-future 'time)
17125 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17126 (equal day (nth 3 nowdecode))
17127 (equal month (nth 4 nowdecode))
17128 (equal year (nth 5 nowdecode))
17129 (nth 2 tl)
17130 (or (< (nth 2 tl) (nth 2 nowdecode))
17131 (and (= (nth 2 tl) (nth 2 nowdecode))
17132 (nth 1 tl)
17133 (< (nth 1 tl) (nth 1 nowdecode)))))
17134 (setq day (1+ day)
17135 futurep t))
17137 ;; Special date definitions below
17138 (cond
17139 (iso-week
17140 ;; There was an iso week
17141 (require 'cal-iso)
17142 (setq futurep nil)
17143 (setq year (or iso-year year)
17144 day (or iso-weekday wday 1)
17145 wday nil ; to make sure that the trigger below does not match
17146 iso-date (calendar-gregorian-from-absolute
17147 (calendar-iso-to-absolute
17148 (list iso-week day year))))
17149 ; FIXME: Should we also push ISO weeks into the future?
17150 ; (when (and org-read-date-prefer-future
17151 ; (not iso-year)
17152 ; (< (calendar-absolute-from-gregorian iso-date)
17153 ; (time-to-days (current-time))))
17154 ; (setq year (1+ year)
17155 ; iso-date (calendar-gregorian-from-absolute
17156 ; (calendar-iso-to-absolute
17157 ; (list iso-week day year)))))
17158 (setq month (car iso-date)
17159 year (nth 2 iso-date)
17160 day (nth 1 iso-date)))
17161 (deltan
17162 (setq futurep nil)
17163 (unless deltadef
17164 ;; Pass `current-time' result to `decode-time' (instead of
17165 ;; calling without arguments) so that only `current-time' has
17166 ;; to be overriden in tests.
17167 (let ((now (decode-time (current-time))))
17168 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17169 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17170 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17171 ((equal deltaw "m") (setq month (+ month deltan)))
17172 ((equal deltaw "y") (setq year (+ year deltan)))))
17173 ((and wday (not (nth 3 tl)))
17174 ;; Weekday was given, but no day, so pick that day in the week
17175 ;; on or after the derived date.
17176 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17177 (unless (equal wday wday1)
17178 (setq day (+ day (% (- wday wday1 -7) 7))))))
17179 (when (and (boundp 'org-time-was-given)
17180 (nth 2 tl))
17181 (setq org-time-was-given t))
17182 (when (< year 100) (setq year (+ 2000 year)))
17183 ;; Check of the date is representable
17184 (if org-read-date-force-compatible-dates
17185 (progn
17186 (when (< year 1970)
17187 (setq year 1970 org-read-date-analyze-forced-year t))
17188 (when (> year 2037)
17189 (setq year 2037 org-read-date-analyze-forced-year t)))
17190 (condition-case nil
17191 (ignore (encode-time second minute hour day month year))
17192 (error
17193 (setq year (nth 5 org-defdecode))
17194 (setq org-read-date-analyze-forced-year t))))
17195 (setq org-read-date-analyze-futurep futurep)
17196 (list second minute hour day month year)))
17198 (defvar parse-time-weekdays)
17199 (defun org-read-date-get-relative (s today default)
17200 "Check string S for special relative date string.
17201 TODAY and DEFAULT are internal times, for today and for a default.
17202 Return shift list (N what def-flag)
17203 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17204 N is the number of WHATs to shift.
17205 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17206 the DEFAULT date rather than TODAY."
17207 (require 'parse-time)
17208 (when (and
17209 (string-match
17210 (concat
17211 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17212 "\\([0-9]+\\)?"
17213 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17214 "\\([ \t]\\|$\\)") s)
17215 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17216 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17217 (string-to-char (substring (match-string 1 s) -1))
17218 ?+))
17219 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17220 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17221 (what (if (match-end 3) (match-string 3 s) "d"))
17222 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17223 (date (if rel default today))
17224 (wday (nth 6 (decode-time date)))
17225 delta)
17226 (if wday1
17227 (progn
17228 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17229 (when (= delta 0) (setq delta 7))
17230 (when (= dir ?-)
17231 (setq delta (- delta 7))
17232 (when (= delta 0) (setq delta -7)))
17233 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17234 (list delta "d" rel))
17235 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17237 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17238 "Turn a user-specified date into the internal representation.
17239 The internal representation needed by the calendar is (month day year).
17240 This is a wrapper to handle the brain-dead convention in calendar that
17241 user function argument order change dependent on argument order."
17242 (if (boundp 'calendar-date-style)
17243 (cond
17244 ((eq calendar-date-style 'american)
17245 (list arg1 arg2 arg3))
17246 ((eq calendar-date-style 'european)
17247 (list arg2 arg1 arg3))
17248 ((eq calendar-date-style 'iso)
17249 (list arg2 arg3 arg1)))
17250 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
17251 (if (org-bound-and-true-p european-calendar-style)
17252 (list arg2 arg1 arg3)
17253 (list arg1 arg2 arg3)))))
17255 (defun org-eval-in-calendar (form &optional keepdate)
17256 "Eval FORM in the calendar window and return to current window.
17257 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
17258 otherwise stick to the current value of `org-ans2'."
17259 (let ((sf (selected-frame))
17260 (sw (selected-window)))
17261 (select-window (get-buffer-window "*Calendar*" t))
17262 (eval form)
17263 (when (and (not keepdate) (calendar-cursor-to-date))
17264 (let* ((date (calendar-cursor-to-date))
17265 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17266 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17267 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17268 (select-window sw)
17269 (org-select-frame-set-input-focus sf)))
17271 (defun org-calendar-select ()
17272 "Return to `org-read-date' with the date currently selected.
17273 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17274 (interactive)
17275 (when (calendar-cursor-to-date)
17276 (let* ((date (calendar-cursor-to-date))
17277 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17278 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17279 (when (active-minibuffer-window) (exit-minibuffer))))
17281 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17282 "Insert a date stamp for the date given by the internal TIME.
17283 See `format-time-string' for the format of TIME.
17284 WITH-HM means use the stamp format that includes the time of the day.
17285 INACTIVE means use square brackets instead of angular ones, so that the
17286 stamp will not contribute to the agenda.
17287 PRE and POST are optional strings to be inserted before and after the
17288 stamp.
17289 The command returns the inserted time stamp."
17290 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17291 stamp)
17292 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17293 (insert-before-markers (or pre ""))
17294 (when (listp extra)
17295 (setq extra (car extra))
17296 (if (and (stringp extra)
17297 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17298 (setq extra (format "-%02d:%02d"
17299 (string-to-number (match-string 1 extra))
17300 (string-to-number (match-string 2 extra))))
17301 (setq extra nil)))
17302 (when extra
17303 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17304 (insert-before-markers (setq stamp (format-time-string fmt time)))
17305 (insert-before-markers (or post ""))
17306 (setq org-last-inserted-timestamp stamp)))
17308 (defun org-toggle-time-stamp-overlays ()
17309 "Toggle the use of custom time stamp formats."
17310 (interactive)
17311 (setq org-display-custom-times (not org-display-custom-times))
17312 (unless org-display-custom-times
17313 (let ((p (point-min)) (bmp (buffer-modified-p)))
17314 (while (setq p (next-single-property-change p 'display))
17315 (when (and (get-text-property p 'display)
17316 (eq (get-text-property p 'face) 'org-date))
17317 (remove-text-properties
17318 p (setq p (next-single-property-change p 'display))
17319 '(display t))))
17320 (set-buffer-modified-p bmp)))
17321 (when (featurep 'xemacs)
17322 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17323 (org-restart-font-lock)
17324 (setq org-table-may-need-update t)
17325 (if org-display-custom-times
17326 (message "Time stamps are overlaid with custom format")
17327 (message "Time stamp overlays removed")))
17329 (defun org-display-custom-time (beg end)
17330 "Overlay modified time stamp format over timestamp between BEG and END."
17331 (let* ((ts (buffer-substring beg end))
17332 t1 w1 with-hm tf time str w2 (off 0))
17333 (save-match-data
17334 (setq t1 (org-parse-time-string ts t))
17335 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17336 (setq off (- (match-end 0) (match-beginning 0)))))
17337 (setq end (- end off))
17338 (setq w1 (- end beg)
17339 with-hm (and (nth 1 t1) (nth 2 t1))
17340 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17341 time (org-fix-decoded-time t1)
17342 str (org-add-props
17343 (format-time-string
17344 (substring tf 1 -1) (apply 'encode-time time))
17345 nil 'mouse-face 'highlight)
17346 w2 (length str))
17347 (unless (= w2 w1)
17348 (add-text-properties (1+ beg) (+ 2 beg)
17349 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17350 (if (featurep 'xemacs)
17351 (progn
17352 (put-text-property beg end 'invisible t)
17353 (put-text-property beg end 'end-glyph (make-glyph str)))
17354 (put-text-property beg end 'display str))))
17356 (defun org-fix-decoded-time (time)
17357 "Set 0 instead of nil for the first 6 elements of time.
17358 Don't touch the rest."
17359 (let ((n 0))
17360 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17362 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17364 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17365 "Difference between TIMESTAMP-STRING and now in days.
17366 If SECONDS is non-nil, return the difference in seconds."
17367 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17368 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17369 (funcall fdiff (current-time)))))
17371 (defun org-deadline-close (timestamp-string &optional ndays)
17372 "Is the time in TIMESTAMP-STRING close to the current date?"
17373 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17374 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17375 (not (org-entry-is-done-p))))
17377 (defun org-get-wdays (ts &optional delay zero-delay)
17378 "Get the deadline lead time appropriate for timestring TS.
17379 When DELAY is non-nil, get the delay time for scheduled items
17380 instead of the deadline lead time. When ZERO-DELAY is non-nil
17381 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17382 don't try to find the delay cookie in the scheduled timestamp."
17383 (let ((tv (if delay org-scheduled-delay-days
17384 org-deadline-warning-days)))
17385 (cond
17386 ((or (and delay (< tv 0))
17387 (and delay zero-delay (<= tv 0))
17388 (and (not delay) (<= tv 0)))
17389 ;; Enforce this value no matter what
17390 (- tv))
17391 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17392 ;; lead time is specified.
17393 (floor (* (string-to-number (match-string 1 ts))
17394 (cdr (assoc (match-string 2 ts)
17395 '(("d" . 1) ("w" . 7)
17396 ("m" . 30.4) ("y" . 365.25)
17397 ("h" . 0.041667)))))))
17398 ;; go for the default.
17399 (t tv))))
17401 (defun org-calendar-select-mouse (ev)
17402 "Return to `org-read-date' with the date currently selected.
17403 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17404 (interactive "e")
17405 (mouse-set-point ev)
17406 (when (calendar-cursor-to-date)
17407 (let* ((date (calendar-cursor-to-date))
17408 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17409 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17410 (when (active-minibuffer-window) (exit-minibuffer))))
17412 (defun org-check-deadlines (ndays)
17413 "Check if there are any deadlines due or past due.
17414 A deadline is considered due if it happens within `org-deadline-warning-days'
17415 days from today's date. If the deadline appears in an entry marked DONE,
17416 it is not shown. The prefix arg NDAYS can be used to test that many
17417 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17418 (interactive "P")
17419 (let* ((org-warn-days
17420 (cond
17421 ((equal ndays '(4)) 100000)
17422 (ndays (prefix-numeric-value ndays))
17423 (t (abs org-deadline-warning-days))))
17424 (case-fold-search nil)
17425 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17426 (callback
17427 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17428 (message "%d deadlines past-due or due within %d days"
17429 (org-occur regexp nil callback)
17430 org-warn-days)))
17432 (defsubst org-re-timestamp (type)
17433 "Return a regexp for timestamp TYPE.
17434 Allowed values for TYPE are:
17436 all: all timestamps
17437 active: only active timestamps (<...>)
17438 inactive: only inactive timestamps ([...])
17439 scheduled: only scheduled timestamps
17440 deadline: only deadline timestamps
17441 closed: only closed time-stamps
17443 When TYPE is nil, fall back on returning a regexp that matches
17444 both scheduled and deadline timestamps."
17445 (cl-case type
17446 (all org-ts-regexp-both)
17447 (active org-ts-regexp)
17448 (inactive org-ts-regexp-inactive)
17449 (scheduled org-scheduled-time-regexp)
17450 (deadline org-deadline-time-regexp)
17451 (closed org-closed-time-regexp)
17452 (otherwise
17453 (concat "\\<"
17454 (regexp-opt (list org-deadline-string org-scheduled-string))
17455 " *<\\([^>]+\\)>"))))
17457 (defun org-check-before-date (d)
17458 "Check if there are deadlines or scheduled entries before date D."
17459 (interactive (list (org-read-date)))
17460 (let ((case-fold-search nil)
17461 (regexp (org-re-timestamp org-ts-type))
17462 (callback
17463 `(lambda ()
17464 (let ((match (match-string 1)))
17465 (and ,(if (memq org-ts-type '(active inactive all))
17466 '(eq (org-element-type (org-element-context)) 'timestamp)
17467 '(org-at-planning-p))
17468 (time-less-p
17469 (org-time-string-to-time match)
17470 (org-time-string-to-time d)))))))
17471 (message "%d entries before %s"
17472 (org-occur regexp nil callback)
17473 d)))
17475 (defun org-check-after-date (d)
17476 "Check if there are deadlines or scheduled entries after date D."
17477 (interactive (list (org-read-date)))
17478 (let ((case-fold-search nil)
17479 (regexp (org-re-timestamp org-ts-type))
17480 (callback
17481 `(lambda ()
17482 (let ((match (match-string 1)))
17483 (and ,(if (memq org-ts-type '(active inactive all))
17484 '(eq (org-element-type (org-element-context)) 'timestamp)
17485 '(org-at-planning-p))
17486 (not (time-less-p
17487 (org-time-string-to-time match)
17488 (org-time-string-to-time d))))))))
17489 (message "%d entries after %s"
17490 (org-occur regexp nil callback)
17491 d)))
17493 (defun org-check-dates-range (start-date end-date)
17494 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17495 (interactive (list (org-read-date nil nil nil "Range starts")
17496 (org-read-date nil nil nil "Range end")))
17497 (let ((case-fold-search nil)
17498 (regexp (org-re-timestamp org-ts-type))
17499 (callback
17500 `(lambda ()
17501 (let ((match (match-string 1)))
17502 (and
17503 ,(if (memq org-ts-type '(active inactive all))
17504 '(eq (org-element-type (org-element-context)) 'timestamp)
17505 '(org-at-planning-p))
17506 (not (time-less-p
17507 (org-time-string-to-time match)
17508 (org-time-string-to-time start-date)))
17509 (time-less-p
17510 (org-time-string-to-time match)
17511 (org-time-string-to-time end-date)))))))
17512 (message "%d entries between %s and %s"
17513 (org-occur regexp nil callback) start-date end-date)))
17515 (defun org-evaluate-time-range (&optional to-buffer)
17516 "Evaluate a time range by computing the difference between start and end.
17517 Normally the result is just printed in the echo area, but with prefix arg
17518 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17519 If the time range is actually in a table, the result is inserted into the
17520 next column.
17521 For time difference computation, a year is assumed to be exactly 365
17522 days in order to avoid rounding problems."
17523 (interactive "P")
17525 (org-clock-update-time-maybe)
17526 (save-excursion
17527 (unless (org-at-date-range-p t)
17528 (goto-char (point-at-bol))
17529 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17530 (unless (org-at-date-range-p t)
17531 (user-error "Not at a time-stamp range, and none found in current line")))
17532 (let* ((ts1 (match-string 1))
17533 (ts2 (match-string 2))
17534 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17535 (match-end (match-end 0))
17536 (time1 (org-time-string-to-time ts1))
17537 (time2 (org-time-string-to-time ts2))
17538 (t1 (org-float-time time1))
17539 (t2 (org-float-time time2))
17540 (diff (abs (- t2 t1)))
17541 (negative (< (- t2 t1) 0))
17542 ;; (ys (floor (* 365 24 60 60)))
17543 (ds (* 24 60 60))
17544 (hs (* 60 60))
17545 (fy "%dy %dd %02d:%02d")
17546 (fy1 "%dy %dd")
17547 (fd "%dd %02d:%02d")
17548 (fd1 "%dd")
17549 (fh "%02d:%02d")
17550 y d h m align)
17551 (if havetime
17552 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17554 d (floor (/ diff ds)) diff (mod diff ds)
17555 h (floor (/ diff hs)) diff (mod diff hs)
17556 m (floor (/ diff 60)))
17557 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17559 d (floor (+ (/ diff ds) 0.5))
17560 h 0 m 0))
17561 (if (not to-buffer)
17562 (message "%s" (org-make-tdiff-string y d h m))
17563 (if (org-at-table-p)
17564 (progn
17565 (goto-char match-end)
17566 (setq align t)
17567 (and (looking-at " *|") (goto-char (match-end 0))))
17568 (goto-char match-end))
17569 (when (looking-at
17570 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17571 (replace-match ""))
17572 (when negative (insert " -"))
17573 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17574 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17575 (insert " " (format fh h m))))
17576 (when align (org-table-align))
17577 (message "Time difference inserted")))))
17579 (defun org-make-tdiff-string (y d h m)
17580 (let ((fmt "")
17581 (l nil))
17582 (when (> y 0)
17583 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17584 (push y l))
17585 (when (> d 0)
17586 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17587 (push d l))
17588 (when (> h 0)
17589 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17590 (push h l))
17591 (when (> m 0)
17592 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17593 (push m l))
17594 (apply 'format fmt (nreverse l))))
17596 (defun org-time-string-to-time (s &optional buffer pos)
17597 "Convert a timestamp string into internal time."
17598 (condition-case errdata
17599 (apply 'encode-time (org-parse-time-string s))
17600 (error (error "Bad timestamp `%s'%s\nError was: %s"
17601 s (if (not (and buffer pos))
17603 (format-message " at %d in buffer `%s'" pos buffer))
17604 (cdr errdata)))))
17606 (defun org-time-string-to-seconds (s)
17607 "Convert a timestamp string to a number of seconds."
17608 (org-float-time (org-time-string-to-time s)))
17610 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17612 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17613 "Convert time stamp S to an absolute day number.
17615 If DAYNR in non-nil, and there is a specifier for a cyclic time
17616 stamp, get the closest date to DAYNR. If PREFER is
17617 `past' (respectively `future') return a date past (respectively
17618 after) or equal to DAYNR.
17620 POS is the location of time stamp S, as a buffer position in
17621 BUFFER.
17623 Diary sexp timestamps are matched against DAYNR, when non-nil.
17624 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17625 signalled."
17626 (cond
17627 ((string-match "\\`%%\\((.*)\\)" s)
17628 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17629 ;; only able to match individual dates. If it fails, raise an
17630 ;; error.
17631 (if (and daynr
17632 (org-diary-sexp-entry
17633 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17634 daynr
17635 (signal 'org-diary-sexp-no-match (list s))))
17636 ((and daynr show-all) (org-closest-date s daynr prefer))
17637 (t (time-to-days
17638 (condition-case errdata
17639 (apply #'encode-time (org-parse-time-string s))
17640 (error (error "Bad timestamp `%s'%s\nError was: %s"
17642 (if (not (and buffer pos)) ""
17643 (format-message " at %d in buffer `%s'" pos buffer))
17644 (cdr errdata))))))))
17646 (defun org-days-to-iso-week (days)
17647 "Return the iso week number."
17648 (require 'cal-iso)
17649 (car (calendar-iso-from-absolute days)))
17651 (defun org-small-year-to-year (year)
17652 "Convert 2-digit years into 4-digit years.
17653 YEAR is expanded into one of the 30 next years, if possible, or
17654 into a past one. Any year larger than 99 is returned unchanged."
17655 (if (>= year 100) year
17656 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17657 (century (/ current 100))
17658 (offset (- year (% current 100))))
17659 (cond ((> offset 30) (+ (* (1- century) 100) year))
17660 ((> offset -70) (+ (* century 100) year))
17661 (t (+ (* (1+ century) 100) year))))))
17663 (defun org-time-from-absolute (d)
17664 "Return the time corresponding to date D.
17665 D may be an absolute day number, or a calendar-type list (month day year)."
17666 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17667 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17669 (defun org-calendar-holiday ()
17670 "List of holidays, for Diary display in Org mode."
17671 (declare (special date))
17672 (require 'holidays)
17673 (let ((hl (calendar-check-holidays date)))
17674 (and hl (mapconcat #'identity hl "; "))))
17676 (defun org-diary-sexp-entry (sexp entry d)
17677 "Process a SEXP diary ENTRY for date D."
17678 (require 'diary-lib)
17679 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17680 ;; dynamically.
17681 (let* ((sexp `(let ((entry ,entry)
17682 (date ',d))
17683 ,(car (read-from-string sexp))))
17684 (result (if calendar-debug-sexp (eval sexp)
17685 (condition-case nil
17686 (eval sexp)
17687 (error
17688 (beep)
17689 (message "Bad sexp at line %d in %s: %s"
17690 (org-current-line)
17691 (buffer-file-name) sexp)
17692 (sleep-for 2))))))
17693 (cond ((stringp result) (split-string result "; "))
17694 ((and (consp result)
17695 (not (consp (cdr result)))
17696 (stringp (cdr result))) (cdr result))
17697 ((and (consp result)
17698 (stringp (car result))) result)
17699 (result entry))))
17701 (defun org-diary-to-ical-string (frombuf)
17702 "Get iCalendar entries from diary entries in buffer FROMBUF.
17703 This uses the icalendar.el library."
17704 (let* ((tmpdir (if (featurep 'xemacs)
17705 (temp-directory)
17706 temporary-file-directory))
17707 (tmpfile (make-temp-name
17708 (expand-file-name "orgics" tmpdir)))
17709 buf rtn b e)
17710 (with-current-buffer frombuf
17711 (icalendar-export-region (point-min) (point-max) tmpfile)
17712 (setq buf (find-buffer-visiting tmpfile))
17713 (set-buffer buf)
17714 (goto-char (point-min))
17715 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17716 (setq b (match-beginning 0)))
17717 (goto-char (point-max))
17718 (when (re-search-backward "^END:VEVENT" nil t)
17719 (setq e (match-end 0)))
17720 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17721 (kill-buffer buf)
17722 (delete-file tmpfile)
17723 rtn))
17725 (defun org-closest-date (start current prefer)
17726 "Return closest date to CURRENT starting from START.
17728 CURRENT and START are both time stamps.
17730 When PREFER is `past', return a date that is either CURRENT or
17731 past. When PREFER is `future', return a date that is either
17732 CURRENT or future.
17734 Only time stamps with a repeater are modified. Any other time
17735 stamp stay unchanged. In any case, return value is an absolute
17736 day number."
17737 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17738 ;; No repeater. Do not shift time stamp.
17739 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17740 (let ((value (string-to-number (match-string 1 start)))
17741 (type (match-string 2 start)))
17742 (if (= 0 value)
17743 ;; Repeater with a 0-value is considered as void.
17744 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17745 (let* ((base (org-date-to-gregorian start))
17746 (target (org-date-to-gregorian current))
17747 (sday (calendar-absolute-from-gregorian base))
17748 (cday (calendar-absolute-from-gregorian target))
17749 n1 n2)
17750 ;; If START is already past CURRENT, just return START.
17751 (if (<= cday sday) sday
17752 ;; Compute closest date before (N1) and closest date past
17753 ;; (N2) CURRENT.
17754 (pcase type
17755 ("h"
17756 (let ((missing-hours
17757 (mod (+ (- (* 24 (- cday sday))
17758 (nth 2 (org-parse-time-string start)))
17759 org-extend-today-until)
17760 value)))
17761 (setf n1 (if (= missing-hours 0) cday
17762 (- cday (1+ (/ missing-hours 24)))))
17763 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17764 ((or "d" "w")
17765 (let ((value (if (equal type "w") (* 7 value) value)))
17766 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17767 (setf n2 (+ n1 value))))
17768 ("m"
17769 (let* ((add-months
17770 (lambda (d n)
17771 ;; Add N months to gregorian date D, i.e.,
17772 ;; a list (MONTH DAY YEAR). Return a valid
17773 ;; gregorian date.
17774 (let ((m (+ (nth 0 d) n)))
17775 (list (mod m 12)
17776 (nth 1 d)
17777 (+ (/ m 12) (nth 2 d))))))
17778 (months ; Complete months to TARGET.
17779 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17780 (- (nth 0 target) (nth 0 base))
17781 ;; If START's day is greater than
17782 ;; TARGET's, remove incomplete month.
17783 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17784 value)
17785 value))
17786 (before (funcall add-months base months)))
17787 (setf n1 (calendar-absolute-from-gregorian before))
17788 (setf n2
17789 (calendar-absolute-from-gregorian
17790 (funcall add-months before value)))))
17792 (let* ((d (nth 1 base))
17793 (m (nth 0 base))
17794 (y (nth 2 base))
17795 (years ; Complete years to TARGET.
17796 (* (/ (- (nth 2 target)
17798 ;; If START's month and day are
17799 ;; greater than TARGET's, remove
17800 ;; incomplete year.
17801 (if (or (> (nth 0 target) m)
17802 (and (= (nth 0 target) m)
17803 (> (nth 1 target) d)))
17806 value)
17807 value))
17808 (before (list m d (+ y years))))
17809 (setf n1 (calendar-absolute-from-gregorian before))
17810 (setf n2 (calendar-absolute-from-gregorian
17811 (list m d (+ (nth 2 before) value)))))))
17812 ;; Handle PREFER parameter, if any.
17813 (cond
17814 ((eq prefer 'past) (if (= cday n2) n2 n1))
17815 ((eq prefer 'future) (if (= cday n1) n1 n2))
17816 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17818 (defun org-date-to-gregorian (d)
17819 "Turn any specification of date D into a Gregorian date for the calendar."
17820 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17821 ((and (listp d) (= (length d) 3)) d)
17822 ((stringp d)
17823 (let ((d (org-parse-time-string d)))
17824 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17825 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17827 (defun org-parse-time-string (s &optional nodefault)
17828 "Parse the standard Org-mode time string.
17829 This should be a lot faster than the normal `parse-time-string'.
17830 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17831 hour and minute fields will be nil if not given."
17832 (cond ((string-match org-ts-regexp0 s)
17833 (list 0
17834 (when (or (match-beginning 8) (not nodefault))
17835 (string-to-number (or (match-string 8 s) "0")))
17836 (when (or (match-beginning 7) (not nodefault))
17837 (string-to-number (or (match-string 7 s) "0")))
17838 (string-to-number (match-string 4 s))
17839 (string-to-number (match-string 3 s))
17840 (string-to-number (match-string 2 s))
17841 nil nil nil))
17842 ((string-match "^<[^>]+>$" s)
17843 (decode-time (seconds-to-time (org-matcher-time s))))
17844 (t (error "Not a standard Org-mode time string: %s" s))))
17846 (defun org-timestamp-up (&optional arg)
17847 "Increase the date item at the cursor by one.
17848 If the cursor is on the year, change the year. If it is on the month,
17849 the day or the time, change that.
17850 With prefix ARG, change by that many units."
17851 (interactive "p")
17852 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17854 (defun org-timestamp-down (&optional arg)
17855 "Decrease the date item at the cursor by one.
17856 If the cursor is on the year, change the year. If it is on the month,
17857 the day or the time, change that.
17858 With prefix ARG, change by that many units."
17859 (interactive "p")
17860 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17862 (defun org-timestamp-up-day (&optional arg)
17863 "Increase the date in the time stamp by one day.
17864 With prefix ARG, change that many days."
17865 (interactive "p")
17866 (if (and (not (org-at-timestamp-p t))
17867 (org-at-heading-p))
17868 (org-todo 'up)
17869 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17871 (defun org-timestamp-down-day (&optional arg)
17872 "Decrease the date in the time stamp by one day.
17873 With prefix ARG, change that many days."
17874 (interactive "p")
17875 (if (and (not (org-at-timestamp-p t))
17876 (org-at-heading-p))
17877 (org-todo 'down)
17878 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17880 (defun org-at-timestamp-p (&optional inactive-ok)
17881 "Non-nil if point is inside a timestamp.
17883 When optional argument INACTIVE-OK is non-nil, also consider
17884 inactive timestamps.
17886 When this function returns a non-nil value, match data is set
17887 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
17888 INACTIVE-OK."
17889 (interactive)
17890 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17891 (pos (point))
17892 (ans (or (looking-at tsr)
17893 (save-excursion
17894 (skip-chars-backward "^[<\n\r\t")
17895 (when (> (point) (point-min)) (backward-char 1))
17896 (and (looking-at tsr)
17897 (> (- (match-end 0) pos) -1))))))
17898 (and ans
17899 (boundp 'org-ts-what)
17900 (setq org-ts-what
17901 (cond
17902 ((= pos (match-beginning 0)) 'bracket)
17903 ;; Point is considered to be "on the bracket" whether
17904 ;; it's really on it or right after it.
17905 ((= pos (1- (match-end 0))) 'bracket)
17906 ((= pos (match-end 0)) 'after)
17907 ((org-pos-in-match-range pos 2) 'year)
17908 ((org-pos-in-match-range pos 3) 'month)
17909 ((org-pos-in-match-range pos 7) 'hour)
17910 ((org-pos-in-match-range pos 8) 'minute)
17911 ((or (org-pos-in-match-range pos 4)
17912 (org-pos-in-match-range pos 5)) 'day)
17913 ((and (> pos (or (match-end 8) (match-end 5)))
17914 (< pos (match-end 0)))
17915 (- pos (or (match-end 8) (match-end 5))))
17916 (t 'day))))
17917 ans))
17919 (defun org-toggle-timestamp-type ()
17920 "Toggle the type (<active> or [inactive]) of a time stamp."
17921 (interactive)
17922 (when (org-at-timestamp-p t)
17923 (let ((beg (match-beginning 0)) (end (match-end 0))
17924 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17925 (save-excursion
17926 (goto-char beg)
17927 (while (re-search-forward "[][<>]" end t)
17928 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17929 t t)))
17930 (message "Timestamp is now %sactive"
17931 (if (equal (char-after beg) ?<) "" "in")))))
17933 (defun org-at-clock-log-p nil
17934 "Is the cursor on the clock log line?"
17935 (save-excursion
17936 (move-beginning-of-line 1)
17937 (looking-at org-clock-line-re)))
17939 (defvar org-clock-history) ; defined in org-clock.el
17940 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17941 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17942 "Change the date in the time stamp at point.
17943 The date will be changed by N times WHAT. WHAT can be `day', `month',
17944 `year', `minute', `second'. If WHAT is not given, the cursor position
17945 in the timestamp determines what will be changed.
17946 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17947 (let ((origin (point)) origin-cat
17948 with-hm inactive
17949 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17950 org-ts-what
17951 extra rem
17952 ts time time0 fixnext clrgx)
17953 (unless (org-at-timestamp-p t)
17954 (user-error "Not at a timestamp"))
17955 (if (and (not what) (eq org-ts-what 'bracket))
17956 (org-toggle-timestamp-type)
17957 ;; Point isn't on brackets. Remember the part of the time-stamp
17958 ;; the point was in. Indeed, size of time-stamps may change,
17959 ;; but point must be kept in the same category nonetheless.
17960 (setq origin-cat org-ts-what)
17961 (when (and (not what) (not (eq org-ts-what 'day))
17962 org-display-custom-times
17963 (get-text-property (point) 'display)
17964 (not (get-text-property (1- (point)) 'display)))
17965 (setq org-ts-what 'day))
17966 (setq org-ts-what (or what org-ts-what)
17967 inactive (= (char-after (match-beginning 0)) ?\[)
17968 ts (match-string 0))
17969 (replace-match "")
17970 (when (string-match
17971 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17973 (setq extra (match-string 1 ts))
17974 (when suppress-tmp-delay
17975 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17976 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17977 (setq with-hm t))
17978 (setq time0 (org-parse-time-string ts))
17979 (when (and updown
17980 (eq org-ts-what 'minute)
17981 (not current-prefix-arg))
17982 ;; This looks like s-up and s-down. Change by one rounding step.
17983 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17984 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17985 (setcar (cdr time0) (+ (nth 1 time0)
17986 (if (> n 0) (- rem) (- dm rem))))))
17987 (setq time
17988 (encode-time (or (car time0) 0)
17989 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17990 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17991 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17992 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17993 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17994 (nthcdr 6 time0)))
17995 (when (and (member org-ts-what '(hour minute))
17996 extra
17997 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17998 (setq extra (org-modify-ts-extra
17999 extra
18000 (if (eq org-ts-what 'hour) 2 5)
18001 n dm)))
18002 (when (integerp org-ts-what)
18003 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18004 (when (eq what 'calendar)
18005 (let ((cal-date (org-get-date-from-calendar)))
18006 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18007 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18008 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18009 (setcar time0 (or (car time0) 0))
18010 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18011 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18012 (setq time (apply 'encode-time time0))))
18013 ;; Insert the new time-stamp, and ensure point stays in the same
18014 ;; category as before (i.e. not after the last position in that
18015 ;; category).
18016 (let ((pos (point)))
18017 ;; Stay before inserted string. `save-excursion' is of no use.
18018 (setq org-last-changed-timestamp
18019 (org-insert-time-stamp time with-hm inactive nil nil extra))
18020 (goto-char pos))
18021 (save-match-data
18022 (looking-at org-ts-regexp3)
18023 (goto-char (cond
18024 ;; `day' category ends before `hour' if any, or at
18025 ;; the end of the day name.
18026 ((eq origin-cat 'day)
18027 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18028 ((eq origin-cat 'hour) (min (match-end 7) origin))
18029 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18030 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18031 ;; `year' and `month' have both fixed size: point
18032 ;; couldn't have moved into another part.
18033 (t origin))))
18034 ;; Update clock if on a CLOCK line.
18035 (org-clock-update-time-maybe)
18036 ;; Maybe adjust the closest clock in `org-clock-history'
18037 (when org-clock-adjust-closest
18038 (if (not (and (org-at-clock-log-p)
18039 (< 1 (length (delq nil (mapcar 'marker-position
18040 org-clock-history))))))
18041 (message "No clock to adjust")
18042 (cond ((save-excursion ; fix previous clock?
18043 (re-search-backward org-ts-regexp0 nil t)
18044 (org-looking-back (concat org-clock-string " \\[")
18045 (line-beginning-position)))
18046 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18047 ((save-excursion ; fix next clock?
18048 (re-search-backward org-ts-regexp0 nil t)
18049 (looking-at (concat org-ts-regexp0 "\\] =>")))
18050 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18051 (save-window-excursion
18052 ;; Find closest clock to point, adjust the previous/next one in history
18053 (let* ((p (save-excursion (org-back-to-heading t)))
18054 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18055 (clfixnth
18056 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18057 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18058 (if (not clfixpos)
18059 (message "No clock to adjust")
18060 (save-excursion
18061 (org-goto-marker-or-bmk clfixpos)
18062 (org-show-subtree)
18063 (when (re-search-forward clrgx nil t)
18064 (goto-char (match-beginning 1))
18065 (let (org-clock-adjust-closest)
18066 (org-timestamp-change n org-ts-what updown))
18067 (message "Clock adjusted in %s for heading: %s"
18068 (file-name-nondirectory (buffer-file-name))
18069 (org-get-heading t t)))))))))
18070 ;; Try to recenter the calendar window, if any.
18071 (when (and org-calendar-follow-timestamp-change
18072 (get-buffer-window "*Calendar*" t)
18073 (memq org-ts-what '(day month year)))
18074 (org-recenter-calendar (time-to-days time))))))
18076 (defun org-modify-ts-extra (s pos n dm)
18077 "Change the different parts of the lead-time and repeat fields in timestamp."
18078 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18079 ng h m new rem)
18080 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18081 (cond
18082 ((or (org-pos-in-match-range pos 2)
18083 (org-pos-in-match-range pos 3))
18084 (setq m (string-to-number (match-string 3 s))
18085 h (string-to-number (match-string 2 s)))
18086 (if (org-pos-in-match-range pos 2)
18087 (setq h (+ h n))
18088 (setq n (* dm (org-no-warnings (signum n))))
18089 (unless (= 0 (setq rem (% m dm)))
18090 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18091 (setq m (+ m n)))
18092 (when (< m 0) (setq m (+ m 60) h (1- h)))
18093 (when (> m 59) (setq m (- m 60) h (1+ h)))
18094 (setq h (mod h 24))
18095 (setq ng 1 new (format "-%02d:%02d" h m)))
18096 ((org-pos-in-match-range pos 6)
18097 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18098 ((org-pos-in-match-range pos 5)
18099 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18101 ((org-pos-in-match-range pos 9)
18102 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18103 ((org-pos-in-match-range pos 8)
18104 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18106 (when ng
18107 (setq s (concat
18108 (substring s 0 (match-beginning ng))
18110 (substring s (match-end ng))))))
18113 (defun org-recenter-calendar (d)
18114 "If the calendar is visible, recenter it to date D."
18115 (let ((cwin (get-buffer-window "*Calendar*" t)))
18116 (when cwin
18117 (let ((calendar-move-hook nil))
18118 (with-selected-window cwin
18119 (calendar-goto-date
18120 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18122 (defun org-goto-calendar (&optional arg)
18123 "Go to the Emacs calendar at the current date.
18124 If there is a time stamp in the current line, go to that date.
18125 A prefix ARG can be used to force the current date."
18126 (interactive "P")
18127 (let ((tsr org-ts-regexp) diff
18128 (calendar-move-hook nil)
18129 (calendar-view-holidays-initially-flag nil)
18130 (calendar-view-diary-initially-flag nil))
18131 (when (or (org-at-timestamp-p)
18132 (save-excursion
18133 (beginning-of-line 1)
18134 (looking-at (concat ".*" tsr))))
18135 (let ((d1 (time-to-days (current-time)))
18136 (d2 (time-to-days
18137 (org-time-string-to-time (match-string 1)))))
18138 (setq diff (- d2 d1))))
18139 (calendar)
18140 (calendar-goto-today)
18141 (when (and diff (not arg)) (calendar-forward-day diff))))
18143 (defun org-get-date-from-calendar ()
18144 "Return a list (month day year) of date at point in calendar."
18145 (with-current-buffer "*Calendar*"
18146 (save-match-data
18147 (calendar-cursor-to-date))))
18149 (defun org-date-from-calendar ()
18150 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18151 If there is already a time stamp at the cursor position, update it."
18152 (interactive)
18153 (if (org-at-timestamp-p t)
18154 (org-timestamp-change 0 'calendar)
18155 (let ((cal-date (org-get-date-from-calendar)))
18156 (org-insert-time-stamp
18157 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18159 (defcustom org-effort-durations
18160 `(("min" . 1)
18161 ("h" . 60)
18162 ("d" . ,(* 60 8))
18163 ("w" . ,(* 60 8 5))
18164 ("m" . ,(* 60 8 5 4))
18165 ("y" . ,(* 60 8 5 40)))
18166 "Conversion factor to minutes for an effort modifier.
18168 Each entry has the form (MODIFIER . MINUTES).
18170 In an effort string, a number followed by MODIFIER is multiplied
18171 by the specified number of MINUTES to obtain an effort in
18172 minutes.
18174 For example, if the value of this variable is ((\"hours\" . 60)), then an
18175 effort string \"2hours\" is equivalent to 120 minutes."
18176 :group 'org-agenda
18177 :version "25.1"
18178 :package-version '(Org . "8.3")
18179 :type '(alist :key-type (string :tag "Modifier")
18180 :value-type (number :tag "Minutes")))
18182 (defun org-minutes-to-clocksum-string (m)
18183 "Format number of minutes as a clocksum string.
18184 The format is determined by `org-time-clocksum-format',
18185 `org-time-clocksum-use-fractional' and
18186 `org-time-clocksum-fractional-format' and
18187 `org-time-clocksum-use-effort-durations'."
18188 (let ((clocksum "")
18189 (m (round m)) ; Don't allow fractions of minutes
18190 h d w mo y fmt n)
18191 (setq h (if org-time-clocksum-use-effort-durations
18192 (cdr (assoc "h" org-effort-durations)) 60)
18193 d (if org-time-clocksum-use-effort-durations
18194 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18195 w (if org-time-clocksum-use-effort-durations
18196 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18197 mo (if org-time-clocksum-use-effort-durations
18198 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18199 y (if org-time-clocksum-use-effort-durations
18200 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18201 ;; fractional format
18202 (if org-time-clocksum-use-fractional
18203 (cond
18204 ;; single format string
18205 ((stringp org-time-clocksum-fractional-format)
18206 (format org-time-clocksum-fractional-format (/ m (float h))))
18207 ;; choice of fractional formats for different time units
18208 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18209 (> (/ (truncate m) (* y d h)) 0))
18210 (format fmt (/ m (* y d (float h)))))
18211 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18212 (> (/ (truncate m) (* mo d h)) 0))
18213 (format fmt (/ m (* mo d (float h)))))
18214 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18215 (> (/ (truncate m) (* w d h)) 0))
18216 (format fmt (/ m (* w d (float h)))))
18217 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18218 (> (/ (truncate m) (* d h)) 0))
18219 (format fmt (/ m (* d (float h)))))
18220 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18221 (> (/ (truncate m) h) 0))
18222 (format fmt (/ m (float h))))
18223 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18224 (format fmt m))
18225 ;; fall back to smallest time unit with a format
18226 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18227 (format fmt (/ m (float h))))
18228 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18229 (format fmt (/ m (* d (float h)))))
18230 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18231 (format fmt (/ m (* w d (float h)))))
18232 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18233 (format fmt (/ m (* mo d (float h)))))
18234 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18235 (format fmt (/ m (* y d (float h))))))
18236 ;; standard (non-fractional) format, with single format string
18237 (if (stringp org-time-clocksum-format)
18238 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18239 ;; separate formats components
18240 (and (setq fmt (plist-get org-time-clocksum-format :years))
18241 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18242 (plist-get org-time-clocksum-format :require-years))
18243 (setq clocksum (concat clocksum (format fmt n))
18244 m (- m (* n y d h))))
18245 (and (setq fmt (plist-get org-time-clocksum-format :months))
18246 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18247 (plist-get org-time-clocksum-format :require-months))
18248 (setq clocksum (concat clocksum (format fmt n))
18249 m (- m (* n mo d h))))
18250 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18251 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18252 (plist-get org-time-clocksum-format :require-weeks))
18253 (setq clocksum (concat clocksum (format fmt n))
18254 m (- m (* n w d h))))
18255 (and (setq fmt (plist-get org-time-clocksum-format :days))
18256 (or (> (setq n (/ (truncate m) (* d h))) 0)
18257 (plist-get org-time-clocksum-format :require-days))
18258 (setq clocksum (concat clocksum (format fmt n))
18259 m (- m (* n d h))))
18260 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18261 (or (> (setq n (/ (truncate m) h)) 0)
18262 (plist-get org-time-clocksum-format :require-hours))
18263 (setq clocksum (concat clocksum (format fmt n))
18264 m (- m (* n h))))
18265 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18266 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18267 (setq clocksum (concat clocksum (format fmt m))))
18268 ;; return formatted time duration
18269 clocksum))))
18271 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18272 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18273 "Org mode version 8.0")
18275 (defun org-hours-to-clocksum-string (n)
18276 (org-minutes-to-clocksum-string (* n 60)))
18278 (defun org-hh:mm-string-to-minutes (s)
18279 "Convert a string H:MM to a number of minutes.
18280 If the string is just a number, interpret it as minutes.
18281 In fact, the first hh:mm or number in the string will be taken,
18282 there can be extra stuff in the string.
18283 If no number is found, the return value is 0."
18284 (cond
18285 ((integerp s) s)
18286 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18287 (+ (* (string-to-number (match-string 1 s)) 60)
18288 (string-to-number (match-string 2 s))))
18289 ((string-match "\\([0-9]+\\)" s)
18290 (string-to-number (match-string 1 s)))
18291 (t 0)))
18293 (defcustom org-image-actual-width t
18294 "Should we use the actual width of images when inlining them?
18296 When set to t, always use the image width.
18298 When set to a number, use imagemagick (when available) to set
18299 the image's width to this value.
18301 When set to a number in a list, try to get the width from any
18302 #+ATTR.* keyword if it matches a width specification like
18304 #+ATTR_HTML: :width 300px
18306 and fall back on that number if none is found.
18308 When set to nil, try to get the width from an #+ATTR.* keyword
18309 and fall back on the original width if none is found.
18311 This requires Emacs >= 24.1, build with imagemagick support."
18312 :group 'org-appearance
18313 :version "24.4"
18314 :package-version '(Org . "8.0")
18315 :type '(choice
18316 (const :tag "Use the image width" t)
18317 (integer :tag "Use a number of pixels")
18318 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18319 (const :tag "Use #+ATTR* or don't resize" nil)))
18321 (defcustom org-agenda-inhibit-startup nil
18322 "Inhibit startup when preparing agenda buffers.
18323 When this variable is t, the initialization of the Org agenda
18324 buffers is inhibited: e.g. the visibility state is not set, the
18325 tables are not re-aligned, etc."
18326 :type 'boolean
18327 :version "24.3"
18328 :group 'org-agenda)
18330 (define-obsolete-variable-alias
18331 'org-agenda-ignore-drawer-properties
18332 'org-agenda-ignore-properties "25.1")
18334 (defcustom org-agenda-ignore-properties nil
18335 "Avoid updating text properties when building the agenda.
18336 Properties are used to prepare buffers for effort estimates,
18337 appointments, statistics and subtree-local categories.
18338 If you don't use these in the agenda, you can add them to this
18339 list and agenda building will be a bit faster.
18340 The value is a list, with zero or more of the symbols `effort', `appt',
18341 `stats' or `category'."
18342 :type '(set :greedy t
18343 (const effort)
18344 (const appt)
18345 (const stats)
18346 (const category))
18347 :version "25.1"
18348 :package-version '(Org . "8.3")
18349 :group 'org-agenda)
18351 (defun org-duration-string-to-minutes (s &optional output-to-string)
18352 "Convert a duration string S to minutes.
18354 A bare number is interpreted as minutes, modifiers can be set by
18355 customizing `org-effort-durations' (which see).
18357 Entries containing a colon are interpreted as H:MM by
18358 `org-hh:mm-string-to-minutes'."
18359 (let ((result 0)
18360 (re (concat "\\([0-9.]+\\) *\\("
18361 (regexp-opt (mapcar 'car org-effort-durations))
18362 "\\)")))
18363 (while (string-match re s)
18364 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18365 (string-to-number (match-string 1 s))))
18366 (setq s (replace-match "" nil t s)))
18367 (setq result (floor result))
18368 (cl-incf result (org-hh:mm-string-to-minutes s))
18369 (if output-to-string (number-to-string result) result)))
18371 ;;;; Files
18373 (defun org-save-all-org-buffers ()
18374 "Save all Org-mode buffers without user confirmation."
18375 (interactive)
18376 (message "Saving all Org-mode buffers...")
18377 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18378 (when (featurep 'org-id) (org-id-locations-save))
18379 (message "Saving all Org-mode buffers... done"))
18381 (defun org-revert-all-org-buffers ()
18382 "Revert all Org-mode buffers.
18383 Prompt for confirmation when there are unsaved changes.
18384 Be sure you know what you are doing before letting this function
18385 overwrite your changes.
18387 This function is useful in a setup where one tracks org files
18388 with a version control system, to revert on one machine after pulling
18389 changes from another. I believe the procedure must be like this:
18391 1. M-x org-save-all-org-buffers
18392 2. Pull changes from the other machine, resolve conflicts
18393 3. M-x org-revert-all-org-buffers"
18394 (interactive)
18395 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18396 (user-error "Abort"))
18397 (save-excursion
18398 (save-window-excursion
18399 (dolist (b (buffer-list))
18400 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18401 (with-current-buffer b buffer-file-name))
18402 (org-pop-to-buffer-same-window b)
18403 (revert-buffer t 'no-confirm)))
18404 (when (and (featurep 'org-id) org-id-track-globally)
18405 (org-id-locations-load)))))
18407 ;;;; Agenda files
18409 ;;;###autoload
18410 (defun org-switchb (&optional arg)
18411 "Switch between Org buffers.
18412 With one prefix argument, restrict available buffers to files.
18413 With two prefix arguments, restrict available buffers to agenda files.
18415 Defaults to `iswitchb' for buffer name completion.
18416 Set `org-completion-use-ido' to make it use ido instead."
18417 (interactive "P")
18418 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18419 ((equal arg '(16)) (org-buffer-list 'agenda))
18420 (t (org-buffer-list))))
18421 (org-completion-use-iswitchb org-completion-use-iswitchb)
18422 (org-completion-use-ido org-completion-use-ido))
18423 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18424 (setq org-completion-use-iswitchb t))
18425 (org-pop-to-buffer-same-window
18426 (completing-read "Org buffer: "
18427 (mapcar #'list (mapcar #'buffer-name blist))
18428 nil t))))
18430 ;;; Define some older names previously used for this functionality
18431 ;;;###autoload
18432 (defalias 'org-ido-switchb 'org-switchb)
18433 ;;;###autoload
18434 (defalias 'org-iswitchb 'org-switchb)
18436 (defun org-buffer-list (&optional predicate exclude-tmp)
18437 "Return a list of Org buffers.
18438 PREDICATE can be `export', `files' or `agenda'.
18440 export restrict the list to Export buffers.
18441 files restrict the list to buffers visiting Org files.
18442 agenda restrict the list to buffers visiting agenda files.
18444 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18445 (let* ((bfn nil)
18446 (agenda-files (and (eq predicate 'agenda)
18447 (mapcar 'file-truename (org-agenda-files t))))
18448 (filter
18449 (cond
18450 ((eq predicate 'files)
18451 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18452 ((eq predicate 'export)
18453 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18454 ((eq predicate 'agenda)
18455 (lambda (b)
18456 (with-current-buffer b
18457 (and (derived-mode-p 'org-mode)
18458 (setq bfn (buffer-file-name b))
18459 (member (file-truename bfn) agenda-files)))))
18460 (t (lambda (b) (with-current-buffer b
18461 (or (derived-mode-p 'org-mode)
18462 (string-match "\\*Org .*Export"
18463 (buffer-name b)))))))))
18464 (delq nil
18465 (mapcar
18466 (lambda(b)
18467 (if (and (funcall filter b)
18468 (or (not exclude-tmp)
18469 (not (string-match "tmp" (buffer-name b)))))
18471 nil))
18472 (buffer-list)))))
18474 (defun org-agenda-files (&optional unrestricted archives)
18475 "Get the list of agenda files.
18476 Optional UNRESTRICTED means return the full list even if a restriction
18477 is currently in place.
18478 When ARCHIVES is t, include all archive files that are really being
18479 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18480 `org-agenda-archives-mode' is t."
18481 (let ((files
18482 (cond
18483 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18484 ((stringp org-agenda-files) (org-read-agenda-file-list))
18485 ((listp org-agenda-files) org-agenda-files)
18486 (t (error "Invalid value of `org-agenda-files'")))))
18487 (setq files (apply 'append
18488 (mapcar (lambda (f)
18489 (if (file-directory-p f)
18490 (directory-files
18491 f t org-agenda-file-regexp)
18492 (list f)))
18493 files)))
18494 (when org-agenda-skip-unavailable-files
18495 (setq files (delq nil
18496 (mapcar (function
18497 (lambda (file)
18498 (and (file-readable-p file) file)))
18499 files))))
18500 (when (or (eq archives t)
18501 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18502 (setq files (org-add-archive-files files)))
18503 files))
18505 (defun org-agenda-file-p (&optional file)
18506 "Return non-nil, if FILE is an agenda file.
18507 If FILE is omitted, use the file associated with the current
18508 buffer."
18509 (let ((fname (or file (buffer-file-name))))
18510 (and fname
18511 (member (file-truename fname)
18512 (mapcar #'file-truename (org-agenda-files t))))))
18514 (defun org-edit-agenda-file-list ()
18515 "Edit the list of agenda files.
18516 Depending on setup, this either uses customize to edit the variable
18517 `org-agenda-files', or it visits the file that is holding the list. In the
18518 latter case, the buffer is set up in a way that saving it automatically kills
18519 the buffer and restores the previous window configuration."
18520 (interactive)
18521 (if (stringp org-agenda-files)
18522 (let ((cw (current-window-configuration)))
18523 (find-file org-agenda-files)
18524 (setq-local org-window-configuration cw)
18525 (org-add-hook 'after-save-hook
18526 (lambda ()
18527 (set-window-configuration
18528 (prog1 org-window-configuration
18529 (kill-buffer (current-buffer))))
18530 (org-install-agenda-files-menu)
18531 (message "New agenda file list installed"))
18532 nil 'local)
18533 (message "%s" (substitute-command-keys
18534 "Edit list and finish with \\[save-buffer]")))
18535 (customize-variable 'org-agenda-files)))
18537 (defun org-store-new-agenda-file-list (list)
18538 "Set new value for the agenda file list and save it correctly."
18539 (if (stringp org-agenda-files)
18540 (let ((fe (org-read-agenda-file-list t)) b u)
18541 (while (setq b (find-buffer-visiting org-agenda-files))
18542 (kill-buffer b))
18543 (with-temp-file org-agenda-files
18544 (insert
18545 (mapconcat
18546 (lambda (f) ;; Keep un-expanded entries.
18547 (if (setq u (assoc f fe))
18548 (cdr u)
18550 list "\n")
18551 "\n")))
18552 (let ((org-mode-hook nil) (org-inhibit-startup t)
18553 (org-insert-mode-line-in-empty-file nil))
18554 (setq org-agenda-files list)
18555 (customize-save-variable 'org-agenda-files org-agenda-files))))
18557 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18558 "Read the list of agenda files from a file.
18559 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18560 filenames, used by `org-store-new-agenda-file-list' to write back
18561 un-expanded file names."
18562 (when (file-directory-p org-agenda-files)
18563 (error "`org-agenda-files' cannot be a single directory"))
18564 (when (stringp org-agenda-files)
18565 (with-temp-buffer
18566 (insert-file-contents org-agenda-files)
18567 (mapcar
18568 (lambda (f)
18569 (let ((e (expand-file-name (substitute-in-file-name f)
18570 org-directory)))
18571 (if pair-with-expansion
18572 (cons e f)
18573 e)))
18574 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18576 ;;;###autoload
18577 (defun org-cycle-agenda-files ()
18578 "Cycle through the files in `org-agenda-files'.
18579 If the current buffer visits an agenda file, find the next one in the list.
18580 If the current buffer does not, find the first agenda file."
18581 (interactive)
18582 (let* ((fs (or (org-agenda-files t)
18583 (user-error "No agenda files")))
18584 (files (copy-sequence fs))
18585 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18586 file)
18587 (when tcf
18588 (while (and (setq file (pop files))
18589 (not (equal (file-truename file) tcf)))))
18590 (find-file (car (or files fs)))
18591 (when (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18593 (defun org-agenda-file-to-front (&optional to-end)
18594 "Move/add the current file to the top of the agenda file list.
18595 If the file is not present in the list, it is added to the front. If it is
18596 present, it is moved there. With optional argument TO-END, add/move to the
18597 end of the list."
18598 (interactive "P")
18599 (let ((org-agenda-skip-unavailable-files nil)
18600 (file-alist (mapcar (lambda (x)
18601 (cons (file-truename x) x))
18602 (org-agenda-files t)))
18603 (ctf (file-truename
18604 (or buffer-file-name
18605 (user-error "Please save the current buffer to a file"))))
18606 x had)
18607 (setq x (assoc ctf file-alist) had x)
18609 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18610 (if to-end
18611 (setq file-alist (append (delq x file-alist) (list x)))
18612 (setq file-alist (cons x (delq x file-alist))))
18613 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18614 (org-install-agenda-files-menu)
18615 (message "File %s to %s of agenda file list"
18616 (if had "moved" "added") (if to-end "end" "front"))))
18618 (defun org-remove-file (&optional file)
18619 "Remove current file from the list of files in variable `org-agenda-files'.
18620 These are the files which are being checked for agenda entries.
18621 Optional argument FILE means use this file instead of the current."
18622 (interactive)
18623 (let* ((org-agenda-skip-unavailable-files nil)
18624 (file (or file buffer-file-name
18625 (user-error "Current buffer does not visit a file")))
18626 (true-file (file-truename file))
18627 (afile (abbreviate-file-name file))
18628 (files (delq nil (mapcar
18629 (lambda (x)
18630 (unless (equal true-file
18631 (file-truename x))
18633 (org-agenda-files t)))))
18634 (if (not (= (length files) (length (org-agenda-files t))))
18635 (progn
18636 (org-store-new-agenda-file-list files)
18637 (org-install-agenda-files-menu)
18638 (message "Removed from Org Agenda list: %s" afile))
18639 (message "File was not in list: %s (not removed)" afile))))
18641 (defun org-file-menu-entry (file)
18642 (vector file (list 'find-file file) t))
18644 (defun org-check-agenda-file (file)
18645 "Make sure FILE exists. If not, ask user what to do."
18646 (unless (file-exists-p file)
18647 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18648 (abbreviate-file-name file))
18649 (let ((r (downcase (read-char-exclusive))))
18650 (cond
18651 ((equal r ?r)
18652 (org-remove-file file)
18653 (throw 'nextfile t))
18654 (t (user-error "Abort"))))))
18656 (defun org-get-agenda-file-buffer (file)
18657 "Get an agenda buffer visiting FILE.
18658 If the buffer needs to be created, add it to the list of buffers
18659 which might be released later."
18660 (let ((buf (org-find-base-buffer-visiting file)))
18661 (if buf
18662 buf ; just return it
18663 ;; Make a new buffer and remember it
18664 (setq buf (find-file-noselect file))
18665 (when buf (push buf org-agenda-new-buffers))
18666 buf)))
18668 (defun org-release-buffers (blist)
18669 "Release all buffers in list, asking the user for confirmation when needed.
18670 When a buffer is unmodified, it is just killed. When modified, it is saved
18671 \(if the user agrees) and then killed."
18672 (let (file)
18673 (dolist (buf blist)
18674 (setq file (buffer-file-name buf))
18675 (when (and (buffer-modified-p buf)
18676 file
18677 (y-or-n-p (format "Save file %s? " file)))
18678 (with-current-buffer buf (save-buffer)))
18679 (kill-buffer buf))))
18681 (defun org-agenda-prepare-buffers (files)
18682 "Create buffers for all agenda files, protect archived trees and comments."
18683 (interactive)
18684 (let ((pa '(:org-archived t))
18685 (pc '(:org-comment t))
18686 (pall '(:org-archived t :org-comment t))
18687 (inhibit-read-only t)
18688 (org-inhibit-startup org-agenda-inhibit-startup)
18689 (rea (concat ":" org-archive-tag ":"))
18690 re pos)
18691 (setq org-tag-alist-for-agenda nil
18692 org-tag-groups-alist-for-agenda nil)
18693 (save-excursion
18694 (save-restriction
18695 (dolist (file files)
18696 (catch 'nextfile
18697 (if (bufferp file)
18698 (set-buffer file)
18699 (org-check-agenda-file file)
18700 (set-buffer (org-get-agenda-file-buffer file)))
18701 (widen)
18702 (org-set-regexps-and-options 'tags-only)
18703 (setq pos (point))
18704 (or (memq 'category org-agenda-ignore-properties)
18705 (org-refresh-category-properties))
18706 (or (memq 'stats org-agenda-ignore-properties)
18707 (org-refresh-stats-properties))
18708 (or (memq 'effort org-agenda-ignore-properties)
18709 (org-refresh-effort-properties))
18710 (or (memq 'appt org-agenda-ignore-properties)
18711 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18712 (setq org-todo-keywords-for-agenda
18713 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18714 (setq org-done-keywords-for-agenda
18715 (append org-done-keywords-for-agenda org-done-keywords))
18716 (setq org-todo-keyword-alist-for-agenda
18717 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18718 (setq org-tag-alist-for-agenda
18719 (org-uniquify
18720 (append org-tag-alist-for-agenda
18721 org-tag-alist
18722 org-tag-persistent-alist)))
18723 (when org-group-tags
18724 (setq org-tag-groups-alist-for-agenda
18725 (org-uniquify-alist
18726 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18727 (org-with-silent-modifications
18728 (save-excursion
18729 (remove-text-properties (point-min) (point-max) pall)
18730 (when org-agenda-skip-archived-trees
18731 (goto-char (point-min))
18732 (while (re-search-forward rea nil t)
18733 (when (org-at-heading-p t)
18734 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18735 (goto-char (point-min))
18736 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18737 (while (re-search-forward re nil t)
18738 (when (save-match-data (org-in-commented-heading-p t))
18739 (add-text-properties
18740 (match-beginning 0) (org-end-of-subtree t) pc)))))
18741 (goto-char pos)))))
18742 (setq org-todo-keywords-for-agenda
18743 (org-uniquify org-todo-keywords-for-agenda))
18744 (setq org-todo-keyword-alist-for-agenda
18745 (org-uniquify org-todo-keyword-alist-for-agenda))))
18748 ;;;; CDLaTeX minor mode
18750 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18751 "Keymap for the minor `org-cdlatex-mode'.")
18753 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18754 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18755 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18756 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18757 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18759 (defvar org-cdlatex-texmathp-advice-is-done nil
18760 "Flag remembering if we have applied the advice to texmathp already.")
18762 (define-minor-mode org-cdlatex-mode
18763 "Toggle the minor `org-cdlatex-mode'.
18764 This mode supports entering LaTeX environment and math in LaTeX fragments
18765 in Org-mode.
18766 \\{org-cdlatex-mode-map}"
18767 nil " OCDL" nil
18768 (when org-cdlatex-mode
18769 (require 'cdlatex)
18770 (run-hooks 'cdlatex-mode-hook)
18771 (cdlatex-compute-tables))
18772 (unless org-cdlatex-texmathp-advice-is-done
18773 (setq org-cdlatex-texmathp-advice-is-done t)
18774 (defadvice texmathp (around org-math-always-on activate)
18775 "Always return t in org-mode buffers.
18776 This is because we want to insert math symbols without dollars even outside
18777 the LaTeX math segments. If Orgmode thinks that point is actually inside
18778 an embedded LaTeX fragment, let texmathp do its job.
18779 \\[org-cdlatex-mode-map]"
18780 (interactive)
18781 (let (p)
18782 (cond
18783 ((not (derived-mode-p 'org-mode)) ad-do-it)
18784 ((eq this-command 'cdlatex-math-symbol)
18785 (setq ad-return-value t
18786 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18788 (let ((p (org-inside-LaTeX-fragment-p)))
18789 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18790 (setq ad-return-value t
18791 texmathp-why '("Org-mode embedded math" . 0))
18792 (when p ad-do-it)))))))))
18794 (defun turn-on-org-cdlatex ()
18795 "Unconditionally turn on `org-cdlatex-mode'."
18796 (org-cdlatex-mode 1))
18798 (defun org-try-cdlatex-tab ()
18799 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18800 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18801 - inside a LaTeX fragment, or
18802 - after the first word in a line, where an abbreviation expansion could
18803 insert a LaTeX environment."
18804 (when org-cdlatex-mode
18805 (cond
18806 ;; Before any word on the line: No expansion possible.
18807 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18808 ;; Just after first word on the line: Expand it. Make sure it
18809 ;; cannot happen on headlines, though.
18810 ((save-excursion
18811 (skip-chars-backward "a-zA-Z0-9*")
18812 (skip-chars-backward " \t")
18813 (and (bolp) (not (org-at-heading-p))))
18814 (cdlatex-tab) t)
18815 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18817 (defun org-cdlatex-underscore-caret (&optional _arg)
18818 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18819 Revert to the normal definition outside of these fragments."
18820 (interactive "P")
18821 (if (org-inside-LaTeX-fragment-p)
18822 (call-interactively 'cdlatex-sub-superscript)
18823 (let (org-cdlatex-mode)
18824 (call-interactively (key-binding (vector last-input-event))))))
18826 (defun org-cdlatex-math-modify (&optional _arg)
18827 "Execute `cdlatex-math-modify' in LaTeX fragments.
18828 Revert to the normal definition outside of these fragments."
18829 (interactive "P")
18830 (if (org-inside-LaTeX-fragment-p)
18831 (call-interactively 'cdlatex-math-modify)
18832 (let (org-cdlatex-mode)
18833 (call-interactively (key-binding (vector last-input-event))))))
18835 (defun org-cdlatex-environment-indent (&optional environment item)
18836 "Execute `cdlatex-environment' and indent the inserted environment.
18838 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18840 The inserted environment is indented to current indentation
18841 unless point is at the beginning of the line, in which the
18842 environment remains unintended."
18843 (interactive)
18844 ;; cdlatex-environment always return nil. Therefore, capture output
18845 ;; first and determine if an environment was selected.
18846 (let* ((beg (point-marker))
18847 (end (copy-marker (point) t))
18848 (inserted (progn
18849 (ignore-errors (cdlatex-environment environment item))
18850 (< beg end)))
18851 ;; Figure out how many lines to move forward after the
18852 ;; environment has been inserted.
18853 (lines (when inserted
18854 (save-excursion
18855 (- (cl-loop while (< beg (point))
18856 with x = 0
18857 do (forward-line -1)
18858 (cl-incf x)
18859 finally return x)
18860 (if (progn (goto-char beg)
18861 (and (progn (skip-chars-forward " \t") (eolp))
18862 (progn (skip-chars-backward " \t") (bolp))))
18863 1 0)))))
18864 (env (org-trim (delete-and-extract-region beg end))))
18865 (when inserted
18866 ;; Get indentation of next line unless at column 0.
18867 (let ((ind (if (bolp) 0
18868 (save-excursion
18869 (org-return-indent)
18870 (prog1 (org-get-indentation)
18871 (when (progn (skip-chars-forward " \t") (eolp))
18872 (delete-region beg (point)))))))
18873 (bol (progn (skip-chars-backward " \t") (bolp))))
18874 ;; Insert a newline before environment unless at column zero
18875 ;; to "escape" the current line. Insert a newline if
18876 ;; something is one the same line as \end{ENVIRONMENT}.
18877 (insert
18878 (concat (unless bol "\n") env
18879 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18880 (unless (zerop ind)
18881 (save-excursion
18882 (goto-char beg)
18883 (while (< (point) end)
18884 (unless (eolp) (org-indent-line-to ind))
18885 (forward-line))))
18886 (goto-char beg)
18887 (forward-line lines)
18888 (org-indent-line-to ind)))
18889 (set-marker beg nil)
18890 (set-marker end nil)))
18893 ;;;; LaTeX fragments
18895 (defun org-inside-LaTeX-fragment-p ()
18896 "Test if point is inside a LaTeX fragment.
18897 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18898 sequence appearing also before point.
18899 Even though the matchers for math are configurable, this function assumes
18900 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18901 delimiters are skipped when they have been removed by customization.
18902 The return value is nil, or a cons cell with the delimiter and the
18903 position of this delimiter.
18905 This function does a reasonably good job, but can locally be fooled by
18906 for example currency specifications. For example it will assume being in
18907 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18908 fragments that are properly closed, but during editing, we have to live
18909 with the uncertainty caused by missing closing delimiters. This function
18910 looks only before point, not after."
18911 (catch 'exit
18912 (let ((pos (point))
18913 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18914 (lim (progn
18915 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18916 (point)))
18917 dd-on str (start 0) m re)
18918 (goto-char pos)
18919 (when dodollar
18920 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18921 re (nth 1 (assoc "$" org-latex-regexps)))
18922 (while (string-match re str start)
18923 (cond
18924 ((= (match-end 0) (length str))
18925 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18926 ((= (match-end 0) (- (length str) 5))
18927 (throw 'exit nil))
18928 (t (setq start (match-end 0))))))
18929 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18930 (goto-char pos)
18931 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18932 (and (match-beginning 2) (throw 'exit nil))
18933 ;; count $$
18934 (while (re-search-backward "\\$\\$" lim t)
18935 (setq dd-on (not dd-on)))
18936 (goto-char pos)
18937 (when dd-on (cons "$$" m))))))
18939 (defun org-inside-latex-macro-p ()
18940 "Is point inside a LaTeX macro or its arguments?"
18941 (save-match-data
18942 (org-in-regexp
18943 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18945 (defvar-local org-latex-fragment-image-overlays nil
18946 "List of overlays carrying the images of latex fragments.")
18948 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18949 "Remove all overlays with LaTeX fragment images in current buffer.
18950 When optional arguments BEG and END are non-nil, remove all
18951 overlays between them instead. Return t when some overlays were
18952 removed, nil otherwise."
18953 (let (removedp)
18954 (setq org-latex-fragment-image-overlays
18955 (let ((beg (or beg (point-min)))
18956 (end (or end (point-max))))
18957 (cl-remove-if
18958 (lambda (o)
18959 (cond ((not (overlay-buffer o)) (delete-overlay o) t)
18960 ((and (>= (overlay-start o) beg)
18961 (<= (overlay-end o) end))
18962 (delete-overlay o)
18963 (unless removedp (setq removedp t)))
18964 (t nil)))
18965 org-latex-fragment-image-overlays)))
18966 removedp))
18968 (define-obsolete-function-alias
18969 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18970 (defun org-toggle-latex-fragment (&optional arg)
18971 "Preview the LaTeX fragment at point, or all locally or globally.
18973 If the cursor is on a LaTeX fragment, create the image and overlay
18974 it over the source code, if there is none. Remove it otherwise.
18975 If there is no fragment at point, display all fragments in the
18976 current section.
18978 With prefix ARG, preview or clear image for all fragments in the
18979 current subtree or in the whole buffer when used before the first
18980 headline. With a double prefix ARG \\[universal-argument] \
18981 \\[universal-argument] preview or clear images
18982 for all fragments in the buffer."
18983 (interactive "P")
18984 (unless (buffer-file-name (buffer-base-buffer))
18985 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18986 (when (display-graphic-p)
18987 (catch 'exit
18988 (save-excursion
18989 (let ((window-start (window-start)) msg)
18990 (save-restriction
18991 (cond
18992 ((or (equal arg '(16))
18993 (and (equal arg '(4))
18994 (org-with-limited-levels (org-before-first-heading-p))))
18995 (if (org-remove-latex-fragment-image-overlays)
18996 (progn (message "LaTeX fragments images removed from buffer")
18997 (throw 'exit nil))
18998 (setq msg "Creating images for buffer...")))
18999 ((equal arg '(4))
19000 (org-with-limited-levels (org-back-to-heading t))
19001 (let ((beg (point))
19002 (end (progn (org-end-of-subtree t) (point))))
19003 (if (org-remove-latex-fragment-image-overlays beg end)
19004 (progn
19005 (message "LaTeX fragment images removed from subtree")
19006 (throw 'exit nil))
19007 (setq msg "Creating images for subtree...")
19008 (narrow-to-region beg end))))
19009 ((let ((datum (org-element-context)))
19010 (when (memq (org-element-type datum)
19011 '(latex-environment latex-fragment))
19012 (let* ((beg (org-element-property :begin datum))
19013 (end (org-element-property :end datum)))
19014 (if (org-remove-latex-fragment-image-overlays beg end)
19015 (progn (message "LaTeX fragment image removed")
19016 (throw 'exit nil))
19017 (narrow-to-region beg end)
19018 (setq msg "Creating image..."))))))
19020 (org-with-limited-levels
19021 (let ((beg (if (org-at-heading-p) (line-beginning-position)
19022 (outline-previous-heading)
19023 (point)))
19024 (end (progn (outline-next-heading) (point))))
19025 (if (org-remove-latex-fragment-image-overlays beg end)
19026 (progn
19027 (message "LaTeX fragment images removed from section")
19028 (throw 'exit nil))
19029 (setq msg "Creating images for section...")
19030 (narrow-to-region beg end))))))
19031 (let ((file (buffer-file-name (buffer-base-buffer))))
19032 (org-format-latex
19033 (concat org-latex-preview-ltxpng-directory
19034 (file-name-sans-extension (file-name-nondirectory file)))
19035 ;; Emacs cannot overlay images from remote hosts.
19036 ;; Create it in `temporary-file-directory' instead.
19037 (if (file-remote-p file) temporary-file-directory
19038 default-directory)
19039 'overlays msg 'forbuffer
19040 org-latex-create-formula-image-program)))
19041 ;; Work around a bug that doesn't restore window's start
19042 ;; when widening back the buffer.
19043 (set-window-start nil window-start)
19044 (message (concat msg "done")))))))
19046 (defun org-format-latex
19047 (prefix &optional dir overlays msg forbuffer processing-type)
19048 "Replace LaTeX fragments with links to an image, and produce images.
19050 When optional argument OVERLAYS is non-nil, display the image on
19051 top of the fragment instead of replacing it.
19053 PROCESSING-TYPE is the conversion method to use, as a symbol.
19055 Some of the options can be changed using the variable
19056 `org-format-latex-options', which see."
19057 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19058 (unless (eq processing-type 'verbatim)
19059 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19060 (cnt 0)
19061 checkdir-flag)
19062 (goto-char (point-min))
19063 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19064 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19065 (overlay-recenter (point-max)))
19066 (while (re-search-forward math-regexp nil t)
19067 (unless (and overlays
19068 (eq (get-char-property (point) 'org-overlay-type)
19069 'org-latex-overlay))
19070 (let* ((context (org-element-context))
19071 (type (org-element-type context)))
19072 (when (memq type '(latex-environment latex-fragment))
19073 (let ((block-type (eq type 'latex-environment))
19074 (value (org-element-property :value context))
19075 (beg (org-element-property :begin context))
19076 (end (save-excursion
19077 (goto-char (org-element-property :end context))
19078 (skip-chars-backward " \r\t\n")
19079 (point))))
19080 (cl-case processing-type
19081 (mathjax
19082 ;; Prepare for MathJax processing.
19083 (if (eq (char-after beg) ?$)
19084 (save-excursion
19085 (delete-region beg end)
19086 (insert "\\(" (substring value 1 -1) "\\)"))
19087 (goto-char end)))
19088 ((dvipng imagemagick)
19089 ;; Process to an image.
19090 (cl-incf cnt)
19091 (goto-char beg)
19092 (let* ((face (face-at-point))
19093 ;; Get the colors from the face at point.
19095 (let ((color (plist-get org-format-latex-options
19096 :foreground)))
19097 (if (and forbuffer (eq color 'auto))
19098 (face-attribute face :foreground nil 'default)
19099 color)))
19101 (let ((color (plist-get org-format-latex-options
19102 :background)))
19103 (if (and forbuffer (eq color 'auto))
19104 (face-attribute face :background nil 'default)
19105 color)))
19106 (hash (sha1 (prin1-to-string
19107 (list org-format-latex-header
19108 org-latex-default-packages-alist
19109 org-latex-packages-alist
19110 org-format-latex-options
19111 forbuffer value fg bg))))
19112 (absprefix (expand-file-name prefix dir))
19113 (linkfile (format "%s_%s.png" prefix hash))
19114 (movefile (format "%s_%s.png" absprefix hash))
19115 (sep (and block-type "\n\n"))
19116 (link (concat sep "[[file:" linkfile "]]" sep))
19117 (options
19118 (org-combine-plists
19119 org-format-latex-options
19120 `(:foreground ,fg :background ,bg))))
19121 (when msg (message msg cnt))
19122 (unless checkdir-flag ; Ensure the directory exists.
19123 (setq checkdir-flag t)
19124 (let ((todir (file-name-directory absprefix)))
19125 (unless (file-directory-p todir)
19126 (make-directory todir t))))
19127 (unless (file-exists-p movefile)
19128 (org-create-formula-image
19129 value movefile options forbuffer processing-type))
19130 (if overlays
19131 (progn
19132 (dolist (o (overlays-in beg end))
19133 (when (eq (overlay-get o 'org-overlay-type)
19134 'org-latex-overlay)
19135 (delete-overlay o)))
19136 (let ((ov (make-overlay beg end)))
19137 (overlay-put ov
19138 'org-overlay-type
19139 'org-latex-overlay)
19140 (overlay-put ov 'evaporate t)
19141 (if (featurep 'xemacs)
19142 (progn
19143 (overlay-put ov 'invisible t)
19144 (overlay-put
19145 ov 'end-glyph
19146 (make-glyph
19147 (vector 'png :file movefile))))
19148 (overlay-put
19149 ov 'display
19150 (list 'image
19151 :type 'png
19152 :file movefile
19153 :ascent 'center)))
19154 (push ov org-latex-fragment-image-overlays))
19155 (goto-char end))
19156 (delete-region beg end)
19157 (insert
19158 (org-add-props link
19159 (list 'org-latex-src
19160 (replace-regexp-in-string "\"" "" value)
19161 'org-latex-src-embed-type
19162 (if block-type 'paragraph 'character)))))))
19163 (mathml
19164 ;; Process to MathML.
19165 (unless (org-format-latex-mathml-available-p)
19166 (user-error "LaTeX to MathML converter not configured"))
19167 (cl-incf cnt)
19168 (when msg (message msg cnt))
19169 (goto-char beg)
19170 (delete-region beg end)
19171 (insert (org-format-latex-as-mathml
19172 value block-type prefix dir)))
19173 (otherwise
19174 (error "Unknown conversion type %s for LaTeX fragments"
19175 processing-type)))))))))))
19177 (defun org-create-math-formula (latex-frag &optional mathml-file)
19178 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19179 Use `org-latex-to-mathml-convert-command'. If the conversion is
19180 sucessful, return the portion between \"<math...> </math>\"
19181 elements otherwise return nil. When MATHML-FILE is specified,
19182 write the results in to that file. When invoked as an
19183 interactive command, prompt for LATEX-FRAG, with initial value
19184 set to the current active region and echo the results for user
19185 inspection."
19186 (interactive (list (let ((frag (when (org-region-active-p)
19187 (buffer-substring-no-properties
19188 (region-beginning) (region-end)))))
19189 (read-string "LaTeX Fragment: " frag nil frag))))
19190 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19191 (let* ((tmp-in-file
19192 (let ((file (file-relative-name
19193 (make-temp-name (expand-file-name "ltxmathml-in")))))
19194 (write-region latex-frag nil file)
19195 file))
19196 (tmp-out-file (file-relative-name
19197 (make-temp-name (expand-file-name "ltxmathml-out"))))
19198 (cmd (format-spec
19199 org-latex-to-mathml-convert-command
19200 `((?j . ,(and org-latex-to-mathml-jar-file
19201 (shell-quote-argument
19202 (expand-file-name
19203 org-latex-to-mathml-jar-file))))
19204 (?I . ,(shell-quote-argument tmp-in-file))
19205 (?i . ,latex-frag)
19206 (?o . ,(shell-quote-argument tmp-out-file)))))
19207 mathml shell-command-output)
19208 (when (org-called-interactively-p 'any)
19209 (unless (org-format-latex-mathml-available-p)
19210 (user-error "LaTeX to MathML converter not configured")))
19211 (message "Running %s" cmd)
19212 (setq shell-command-output (shell-command-to-string cmd))
19213 (setq mathml
19214 (when (file-readable-p tmp-out-file)
19215 (with-current-buffer (find-file-noselect tmp-out-file t)
19216 (goto-char (point-min))
19217 (when (re-search-forward
19218 (concat
19219 (regexp-quote
19220 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19221 "[^>]*?>"
19222 "\\(.\\|\n\\)*"
19223 "</math>")
19224 nil t)
19225 (prog1 (match-string 0) (kill-buffer))))))
19226 (cond
19227 (mathml
19228 (setq mathml
19229 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19230 (when mathml-file
19231 (write-region mathml nil mathml-file))
19232 (when (org-called-interactively-p 'any)
19233 (message mathml)))
19234 ((message "LaTeX to MathML conversion failed")
19235 (message shell-command-output)))
19236 (delete-file tmp-in-file)
19237 (when (file-exists-p tmp-out-file)
19238 (delete-file tmp-out-file))
19239 mathml))
19241 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19242 prefix &optional dir)
19243 "Use `org-create-math-formula' but check local cache first."
19244 (let* ((absprefix (expand-file-name prefix dir))
19245 (print-length nil) (print-level nil)
19246 (formula-id (concat
19247 "formula-"
19248 (sha1
19249 (prin1-to-string
19250 (list latex-frag
19251 org-latex-to-mathml-convert-command)))))
19252 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19253 (formula-cache-dir (file-name-directory formula-cache)))
19255 (unless (file-directory-p formula-cache-dir)
19256 (make-directory formula-cache-dir t))
19258 (unless (file-exists-p formula-cache)
19259 (org-create-math-formula latex-frag formula-cache))
19261 (if (file-exists-p formula-cache)
19262 ;; Successful conversion. Return the link to MathML file.
19263 (org-add-props
19264 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19265 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19266 'org-latex-src-embed-type (if latex-frag-type
19267 'paragraph 'character)))
19268 ;; Failed conversion. Return the LaTeX fragment verbatim
19269 latex-frag)))
19271 (defun org-create-formula-image (string tofile options buffer &optional type)
19272 "Create an image from LaTeX source using dvipng or convert.
19273 This function calls either `org-create-formula-image-with-dvipng'
19274 or `org-create-formula-image-with-imagemagick' depending on the
19275 value of `org-latex-create-formula-image-program' or on the value
19276 of the optional TYPE variable.
19278 Note: ultimately these two function should be combined as they
19279 share a good deal of logic."
19280 (org-check-external-command
19281 "latex" "needed to convert LaTeX fragments to images")
19282 (funcall
19283 (cl-case (or type org-latex-create-formula-image-program)
19284 (dvipng
19285 (org-check-external-command
19286 "dvipng" "needed to convert LaTeX fragments to images")
19287 #'org-create-formula-image-with-dvipng)
19288 (imagemagick
19289 (org-check-external-command
19290 "convert" "you need to install imagemagick")
19291 #'org-create-formula-image-with-imagemagick)
19292 (t (error
19293 "Invalid value of `org-latex-create-formula-image-program'")))
19294 string tofile options buffer))
19296 (declare-function org-export-get-backend "ox" (name))
19297 (declare-function org-export--get-global-options "ox" (&optional backend))
19298 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19299 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19300 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19301 (defun org-create-formula--latex-header ()
19302 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19303 (let ((info (org-combine-plists (org-export--get-global-options
19304 (org-export-get-backend 'latex))
19305 (org-export--get-inbuffer-options
19306 (org-export-get-backend 'latex)))))
19307 (org-latex-guess-babel-language
19308 (org-latex-guess-inputenc
19309 (org-splice-latex-header
19310 org-format-latex-header
19311 org-latex-default-packages-alist
19312 org-latex-packages-alist t
19313 (plist-get info :latex-header)))
19314 info)))
19316 (defun org--get-display-dpi ()
19317 "Get the DPI of the display.
19319 Assumes that the display has the same pixel width in the
19320 horizontal and vertical directions."
19321 (if (display-graphic-p)
19322 (round (/ (display-pixel-height)
19323 (/ (display-mm-height) 25.4)))
19324 (error "Attempt to calculate the dpi of a non-graphic display")))
19326 ;; This function borrows from Ganesh Swami's latex2png.el
19327 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
19328 "This calls dvipng."
19329 (require 'ox-latex)
19330 (let* ((tmpdir (if (featurep 'xemacs)
19331 (temp-directory)
19332 temporary-file-directory))
19333 (texfilebase (make-temp-name
19334 (expand-file-name "orgtex" tmpdir)))
19335 (texfile (concat texfilebase ".tex"))
19336 (dvifile (concat texfilebase ".dvi"))
19337 (pngfile (concat texfilebase ".png"))
19338 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19339 ;; This assumes that the display has the same pixel width in
19340 ;; the horizontal and vertical directions
19341 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19342 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19343 "Black"))
19344 (bg (or (plist-get options (if buffer :background :html-background))
19345 "Transparent")))
19346 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
19347 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
19348 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
19349 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
19350 (let ((latex-header (org-create-formula--latex-header)))
19351 (with-temp-file texfile
19352 (insert latex-header)
19353 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19354 (let ((dir default-directory))
19355 (ignore-errors
19356 (cd tmpdir)
19357 (call-process "latex" nil nil nil texfile))
19358 (cd dir))
19359 (if (not (file-exists-p dvifile))
19360 (progn (message "Failed to create dvi file from %s" texfile) nil)
19361 (ignore-errors
19362 (if (featurep 'xemacs)
19363 (call-process "dvipng" nil nil nil
19364 "-fg" fg "-bg" bg
19365 "-T" "tight"
19366 "-o" pngfile
19367 dvifile)
19368 (call-process "dvipng" nil nil nil
19369 "-fg" fg "-bg" bg
19370 "-D" dpi
19371 ;;"-x" scale "-y" scale
19372 "-T" "tight"
19373 "-o" pngfile
19374 dvifile)))
19375 (if (not (file-exists-p pngfile))
19376 (if org-format-latex-signal-error
19377 (error "Failed to create png file from %s" texfile)
19378 (message "Failed to create png file from %s" texfile)
19379 nil)
19380 ;; Use the requested file name and clean up
19381 (copy-file pngfile tofile 'replace)
19382 (dolist (e '(".dvi" ".tex" ".aux" ".log" ".png" ".out"))
19383 (when (file-exists-p (concat texfilebase e))
19384 (delete-file (concat texfilebase e))))
19385 pngfile))))
19387 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
19388 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
19389 "This calls convert, which is included into imagemagick."
19390 (require 'ox-latex)
19391 (let* ((tmpdir (if (featurep 'xemacs)
19392 (temp-directory)
19393 temporary-file-directory))
19394 (texfilebase (make-temp-name
19395 (expand-file-name "orgtex" tmpdir)))
19396 (texfile (concat texfilebase ".tex"))
19397 (pdffile (concat texfilebase ".pdf"))
19398 (pngfile (concat texfilebase ".png"))
19399 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19400 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19401 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19402 "black"))
19403 (bg (or (plist-get options (if buffer :background :html-background))
19404 "white")))
19405 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
19406 (setq fg (org-latex-color-format fg)))
19407 (if (eq bg 'default) (setq bg (org-latex-color :background))
19408 (setq bg (org-latex-color-format
19409 (if (string= bg "Transparent") "white" bg))))
19410 (let ((latex-header (org-create-formula--latex-header)))
19411 (with-temp-file texfile
19412 (insert latex-header)
19413 (insert "\n\\begin{document}\n"
19414 "\\definecolor{fg}{rgb}{" fg "}\n"
19415 "\\definecolor{bg}{rgb}{" bg "}\n"
19416 "\n\\pagecolor{bg}\n"
19417 "\n{\\color{fg}\n"
19418 string
19419 "\n}\n"
19420 "\n\\end{document}\n")))
19421 (org-latex-compile texfile t)
19422 (if (not (file-exists-p pdffile))
19423 (progn (message "Failed to create pdf file from %s" texfile) nil)
19424 (ignore-errors
19425 (if (featurep 'xemacs)
19426 (call-process "convert" nil nil nil
19427 "-density" "96"
19428 "-trim"
19429 "-antialias"
19430 pdffile
19431 "-quality" "100"
19432 ;; "-sharpen" "0x1.0"
19433 pngfile)
19434 (call-process "convert" nil nil nil
19435 "-density" dpi
19436 "-trim"
19437 "-antialias"
19438 pdffile
19439 "-quality" "100"
19440 ;; "-sharpen" "0x1.0"
19441 pngfile)))
19442 (if (not (file-exists-p pngfile))
19443 (if org-format-latex-signal-error
19444 (error "Failed to create png file from %s" texfile)
19445 (message "Failed to create png file from %s" texfile)
19446 nil)
19447 ;; Use the requested file name and clean up
19448 (copy-file pngfile tofile 'replace)
19449 (dolist (e '(".pdf" ".tex" ".aux" ".log" ".png"))
19450 (when (file-exists-p (concat texfilebase e))
19451 (delete-file (concat texfilebase e))))
19452 pngfile))))
19454 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19455 "Fill a LaTeX header template TPL.
19456 In the template, the following place holders will be recognized:
19458 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19459 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19460 [PACKAGES] \\usepackage statements for PKG
19461 [NO-PACKAGES] do not include PKG
19462 [EXTRA] the string EXTRA
19463 [NO-EXTRA] do not include EXTRA
19465 For backward compatibility, if both the positive and the negative place
19466 holder is missing, the positive one (without the \"NO-\") will be
19467 assumed to be present at the end of the template.
19468 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19469 EXTRA is a string.
19470 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19471 (let (rpl (end ""))
19472 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19473 (setq rpl (if (or (match-end 1) (not def-pkg))
19474 "" (org-latex-packages-to-string def-pkg snippets-p t))
19475 tpl (replace-match rpl t t tpl))
19476 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19478 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19479 (setq rpl (if (or (match-end 1) (not pkg))
19480 "" (org-latex-packages-to-string pkg snippets-p t))
19481 tpl (replace-match rpl t t tpl))
19482 (when pkg (setq end
19483 (concat end "\n"
19484 (org-latex-packages-to-string pkg snippets-p)))))
19486 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19487 (setq rpl (if (or (match-end 1) (not extra))
19488 "" (concat extra "\n"))
19489 tpl (replace-match rpl t t tpl))
19490 (when (and extra (string-match "\\S-" extra))
19491 (setq end (concat end "\n" extra))))
19493 (if (string-match "\\S-" end)
19494 (concat tpl "\n" end)
19495 tpl)))
19497 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19498 "Turn an alist of packages into a string with the \\usepackage macros."
19499 (setq pkg (mapconcat (lambda(p)
19500 (cond
19501 ((stringp p) p)
19502 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19503 (format "%% Package %s omitted" (cadr p)))
19504 ((equal "" (car p))
19505 (format "\\usepackage{%s}" (cadr p)))
19507 (format "\\usepackage[%s]{%s}"
19508 (car p) (cadr p)))))
19510 "\n"))
19511 (if newline (concat pkg "\n") pkg))
19513 (defun org-dvipng-color (attr)
19514 "Return a RGB color specification for dvipng."
19515 (apply 'format "rgb %s %s %s"
19516 (mapcar 'org-normalize-color
19517 (if (featurep 'xemacs)
19518 (color-rgb-components
19519 (face-property 'default
19520 (cond ((eq attr :foreground) 'foreground)
19521 ((eq attr :background) 'background))))
19522 (color-values (face-attribute 'default attr nil))))))
19524 (defun org-dvipng-color-format (color-name)
19525 "Convert COLOR-NAME to a RGB color value for dvipng."
19526 (apply 'format "rgb %s %s %s"
19527 (mapcar 'org-normalize-color
19528 (color-values color-name))))
19530 (defun org-latex-color (attr)
19531 "Return a RGB color for the LaTeX color package."
19532 (apply 'format "%s,%s,%s"
19533 (mapcar 'org-normalize-color
19534 (if (featurep 'xemacs)
19535 (color-rgb-components
19536 (face-property 'default
19537 (cond ((eq attr :foreground) 'foreground)
19538 ((eq attr :background) 'background))))
19539 (color-values (face-attribute 'default attr nil))))))
19541 (defun org-latex-color-format (color-name)
19542 "Convert COLOR-NAME to a RGB color value."
19543 (apply 'format "%s,%s,%s"
19544 (mapcar 'org-normalize-color
19545 (color-values color-name))))
19547 (defun org-normalize-color (value)
19548 "Return string to be used as color value for an RGB component."
19549 (format "%g" (/ value 65535.0)))
19553 ;; Image display
19555 (defvar-local org-inline-image-overlays nil)
19557 (defun org-toggle-inline-images (&optional include-linked)
19558 "Toggle the display of inline images.
19559 INCLUDE-LINKED is passed to `org-display-inline-images'."
19560 (interactive "P")
19561 (if org-inline-image-overlays
19562 (progn
19563 (org-remove-inline-images)
19564 (when (org-called-interactively-p 'interactive)
19565 (message "Inline image display turned off")))
19566 (org-display-inline-images include-linked)
19567 (when (org-called-interactively-p 'interactive)
19568 (message (if org-inline-image-overlays
19569 (format "%d images displayed inline"
19570 (length org-inline-image-overlays))
19571 "No images to display inline")))))
19573 (defun org-redisplay-inline-images ()
19574 "Refresh the display of inline images."
19575 (interactive)
19576 (if (not org-inline-image-overlays)
19577 (org-toggle-inline-images)
19578 (org-toggle-inline-images)
19579 (org-toggle-inline-images)))
19581 (defun org-display-inline-images (&optional include-linked refresh beg end)
19582 "Display inline images.
19584 An inline image is a link which follows either of these
19585 conventions:
19587 1. Its path is a file with an extension matching return value
19588 from `image-file-name-regexp' and it has no contents.
19590 2. Its description consists in a single link of the previous
19591 type.
19593 When optional argument INCLUDE-LINKED is non-nil, also links with
19594 a text description part will be inlined. This can be nice for
19595 a quick look at those images, but it does not reflect what
19596 exported files will look like.
19598 When optional argument REFRESH is non-nil, refresh existing
19599 images between BEG and END. This will create new image displays
19600 only if necessary. BEG and END default to the buffer
19601 boundaries."
19602 (interactive "P")
19603 (when (display-graphic-p)
19604 (unless refresh
19605 (org-remove-inline-images)
19606 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19607 (org-with-wide-buffer
19608 (goto-char (or beg (point-min)))
19609 (let ((case-fold-search t)
19610 (file-extension-re (image-file-name-regexp)))
19611 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19612 (let ((link (save-match-data (org-element-context))))
19613 ;; Check if we're at an inline image.
19614 (when (and (equal (org-element-property :type link) "file")
19615 (or include-linked
19616 (not (org-element-property :contents-begin link)))
19617 (let ((parent (org-element-property :parent link)))
19618 (or (not (eq (org-element-type parent) 'link))
19619 (not (cdr (org-element-contents parent)))))
19620 (org-string-match-p file-extension-re
19621 (org-element-property :path link)))
19622 (let ((file (expand-file-name
19623 (org-link-unescape
19624 (org-element-property :path link)))))
19625 (when (file-exists-p file)
19626 (let ((width
19627 ;; Apply `org-image-actual-width' specifications.
19628 (cond
19629 ((not (image-type-available-p 'imagemagick)) nil)
19630 ((eq org-image-actual-width t) nil)
19631 ((listp org-image-actual-width)
19633 ;; First try to find a width among
19634 ;; attributes associated to the paragraph
19635 ;; containing link.
19636 (let ((paragraph
19637 (let ((e link))
19638 (while (and (setq e (org-element-property
19639 :parent e))
19640 (not (eq (org-element-type e)
19641 'paragraph))))
19642 e)))
19643 (when paragraph
19644 (save-excursion
19645 (goto-char (org-element-property :begin paragraph))
19646 (when
19647 (re-search-forward
19648 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19649 (org-element-property
19650 :post-affiliated paragraph)
19652 (string-to-number (match-string 1))))))
19653 ;; Otherwise, fall-back to provided number.
19654 (car org-image-actual-width)))
19655 ((numberp org-image-actual-width)
19656 org-image-actual-width)))
19657 (old (get-char-property-and-overlay
19658 (org-element-property :begin link)
19659 'org-image-overlay)))
19660 (if (and (car-safe old) refresh)
19661 (image-refresh (overlay-get (cdr old) 'display))
19662 (let ((image (create-image file
19663 (and width 'imagemagick)
19665 :width width)))
19666 (when image
19667 (let* ((link
19668 ;; If inline image is the description
19669 ;; of another link, be sure to
19670 ;; consider the latter as the one to
19671 ;; apply the overlay on.
19672 (let ((parent
19673 (org-element-property :parent link)))
19674 (if (eq (org-element-type parent) 'link)
19675 parent
19676 link)))
19677 (ov (make-overlay
19678 (org-element-property :begin link)
19679 (progn
19680 (goto-char
19681 (org-element-property :end link))
19682 (skip-chars-backward " \t")
19683 (point)))))
19684 (overlay-put ov 'display image)
19685 (overlay-put ov 'face 'default)
19686 (overlay-put ov 'org-image-overlay t)
19687 (overlay-put
19688 ov 'modification-hooks
19689 (list 'org-display-inline-remove-overlay))
19690 (push ov org-inline-image-overlays)))))))))))))))
19692 (define-obsolete-function-alias
19693 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19695 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19696 "Remove inline-display overlay if a corresponding region is modified."
19697 (let ((inhibit-modification-hooks t))
19698 (when (and ov after)
19699 (delete ov org-inline-image-overlays)
19700 (delete-overlay ov))))
19702 (defun org-remove-inline-images ()
19703 "Remove inline display of images."
19704 (interactive)
19705 (mapc #'delete-overlay org-inline-image-overlays)
19706 (setq org-inline-image-overlays nil))
19708 ;;;; Key bindings
19710 ;; Outline functions from `outline-mode-prefix-map'
19711 ;; that can be remapped in Org:
19712 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19713 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19714 (define-key org-mode-map [remap outline-forward-same-level]
19715 'org-forward-heading-same-level)
19716 (define-key org-mode-map [remap outline-backward-same-level]
19717 'org-backward-heading-same-level)
19718 (define-key org-mode-map [remap outline-show-branches]
19719 'org-kill-note-or-show-branches)
19720 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19721 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19722 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19723 (define-key org-mode-map [remap outline-next-visible-heading]
19724 'org-next-visible-heading)
19725 (define-key org-mode-map [remap outline-previous-visible-heading]
19726 'org-previous-visible-heading)
19727 (define-key org-mode-map [remap show-children] 'org-show-children)
19729 ;; Outline functions from `outline-mode-prefix-map' that can not
19730 ;; be remapped in Org:
19732 ;; - the column "key binding" shows whether the Outline function is still
19733 ;; available in Org mode on the same key that it has been bound to in
19734 ;; Outline mode:
19735 ;; - "overridden": key used for a different functionality in Org mode
19736 ;; - else: key still bound to the same Outline function in Org mode
19738 ;; | Outline function | key binding | Org replacement |
19739 ;; |------------------------------------+-------------+--------------------------|
19740 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19741 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19742 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19743 ;; | `show-entry' | overridden | no replacement |
19744 ;; | `show-branches' | `C-c C-k' | still same function |
19745 ;; | `show-subtree' | overridden | visibility cycling |
19746 ;; | `show-all' | overridden | no replacement |
19747 ;; | `hide-subtree' | overridden | visibility cycling |
19748 ;; | `hide-body' | overridden | no replacement |
19749 ;; | `hide-entry' | overridden | visibility cycling |
19750 ;; | `hide-leaves' | overridden | no replacement |
19751 ;; | `hide-sublevels' | overridden | no replacement |
19752 ;; | `hide-other' | overridden | no replacement |
19754 ;; Make `C-c C-x' a prefix key
19755 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19757 ;; TAB key with modifiers
19758 (org-defkey org-mode-map "\C-i" 'org-cycle)
19759 (org-defkey org-mode-map [(tab)] 'org-cycle)
19760 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19761 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19762 ;; The following line is necessary under Suse GNU/Linux
19763 (unless (featurep 'xemacs)
19764 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19765 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19766 (define-key org-mode-map [backtab] 'org-shifttab)
19768 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19769 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19770 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19772 ;; Cursor keys with modifiers
19773 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19774 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19775 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19776 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19778 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19779 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19780 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19781 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19782 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19783 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19785 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19786 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19787 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19788 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19790 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19791 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19792 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19793 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19795 ;; Babel keys
19796 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19797 (dolist (pair org-babel-key-bindings)
19798 (define-key org-babel-map (car pair) (cdr pair)))
19800 ;;; Extra keys for tty access.
19801 ;; We only set them when really needed because otherwise the
19802 ;; menus don't show the simple keys
19804 (when (or org-use-extra-keys
19805 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19806 (not window-system))
19807 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19808 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19809 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19810 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19811 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19812 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19813 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19814 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19815 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19816 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19817 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19818 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19819 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19820 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19821 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19822 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19823 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19824 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19825 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19826 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19827 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19828 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19829 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19830 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19831 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19832 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19833 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19834 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19836 ;; All the other keys
19838 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19839 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19840 (if (boundp 'narrow-map)
19841 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19842 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19843 (if (boundp 'narrow-map)
19844 (org-defkey narrow-map "b" 'org-narrow-to-block)
19845 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19846 (if (boundp 'narrow-map)
19847 (org-defkey narrow-map "e" 'org-narrow-to-element)
19848 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19849 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19850 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19851 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19852 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19853 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19854 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19855 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19856 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19857 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19858 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19859 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19860 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19861 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19862 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19863 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19864 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19865 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19866 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19867 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19868 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19869 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19870 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19871 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19872 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19873 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19874 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19875 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19876 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19877 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19878 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19879 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19880 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19881 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19882 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19883 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19884 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19885 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19886 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19887 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19888 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19889 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19890 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19891 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19892 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19893 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19894 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19895 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19896 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19897 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19898 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19899 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19900 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19901 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19902 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19903 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19904 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19905 (org-defkey org-mode-map "\C-c^" 'org-sort)
19906 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19907 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19908 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19909 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19910 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19911 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19912 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19913 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19914 (org-defkey org-mode-map "\C-m" 'org-return)
19915 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19916 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19917 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19918 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19919 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19920 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19921 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19922 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19923 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19924 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19925 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19926 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19927 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19928 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19929 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19930 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19931 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19932 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19933 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19934 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19935 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19936 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19937 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19938 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19939 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19941 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19942 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19943 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19945 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19946 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19947 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19948 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19949 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19950 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19951 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19952 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19953 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19954 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19955 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19956 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19957 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19958 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19959 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19960 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19961 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19962 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19963 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19964 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19965 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19966 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19968 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19969 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19970 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19971 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19972 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19974 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19976 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19978 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19979 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19981 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19984 (when (featurep 'xemacs)
19985 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19988 (defconst org-speed-commands-default
19990 ("Outline Navigation")
19991 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19992 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19993 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19994 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19995 ("F" . org-next-block)
19996 ("B" . org-previous-block)
19997 ("u" . (org-speed-move-safe 'outline-up-heading))
19998 ("j" . org-goto)
19999 ("g" . (org-refile t))
20000 ("Outline Visibility")
20001 ("c" . org-cycle)
20002 ("C" . org-shifttab)
20003 (" " . org-display-outline-path)
20004 ("s" . org-narrow-to-subtree)
20005 ("=" . org-columns)
20006 ("Outline Structure Editing")
20007 ("U" . org-metaup)
20008 ("D" . org-metadown)
20009 ("r" . org-metaright)
20010 ("l" . org-metaleft)
20011 ("R" . org-shiftmetaright)
20012 ("L" . org-shiftmetaleft)
20013 ("i" . (progn (forward-char 1) (call-interactively
20014 'org-insert-heading-respect-content)))
20015 ("^" . org-sort)
20016 ("w" . org-refile)
20017 ("a" . org-archive-subtree-default-with-confirmation)
20018 ("@" . org-mark-subtree)
20019 ("#" . org-toggle-comment)
20020 ("Clock Commands")
20021 ("I" . org-clock-in)
20022 ("O" . org-clock-out)
20023 ("Meta Data Editing")
20024 ("t" . org-todo)
20025 ("," . (org-priority))
20026 ("0" . (org-priority ?\ ))
20027 ("1" . (org-priority ?A))
20028 ("2" . (org-priority ?B))
20029 ("3" . (org-priority ?C))
20030 (":" . org-set-tags-command)
20031 ("e" . org-set-effort)
20032 ("E" . org-inc-effort)
20033 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20034 (org-entry-put (point) "APPT_WARNTIME" m)))
20035 ("Agenda Views etc")
20036 ("v" . org-agenda)
20037 ("/" . org-sparse-tree)
20038 ("Misc")
20039 ("o" . org-open-at-point)
20040 ("?" . org-speed-command-help)
20041 ("<" . (org-agenda-set-restriction-lock 'subtree))
20042 (">" . (org-agenda-remove-restriction-lock))
20044 "The default speed commands.")
20046 (defun org-print-speed-command (e)
20047 (if (> (length (car e)) 1)
20048 (progn
20049 (princ "\n")
20050 (princ (car e))
20051 (princ "\n")
20052 (princ (make-string (length (car e)) ?-))
20053 (princ "\n"))
20054 (princ (car e))
20055 (princ " ")
20056 (if (symbolp (cdr e))
20057 (princ (symbol-name (cdr e)))
20058 (prin1 (cdr e)))
20059 (princ "\n")))
20061 (defun org-speed-command-help ()
20062 "Show the available speed commands."
20063 (interactive)
20064 (if (not org-use-speed-commands)
20065 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20066 (with-output-to-temp-buffer "*Help*"
20067 (princ "User-defined Speed commands\n===========================\n")
20068 (mapc #'org-print-speed-command org-speed-commands-user)
20069 (princ "\n")
20070 (princ "Built-in Speed commands\n=======================\n")
20071 (mapc #'org-print-speed-command org-speed-commands-default))
20072 (with-current-buffer "*Help*"
20073 (setq truncate-lines t))))
20075 (defun org-speed-move-safe (cmd)
20076 "Execute CMD, but make sure that the cursor always ends up in a headline.
20077 If not, return to the original position and throw an error."
20078 (interactive)
20079 (let ((pos (point)))
20080 (call-interactively cmd)
20081 (unless (and (bolp) (org-at-heading-p))
20082 (goto-char pos)
20083 (error "Boundary reached while executing %s" cmd))))
20085 (defvar org-self-insert-command-undo-counter 0)
20087 (defvar org-table-auto-blank-field) ; defined in org-table.el
20088 (defvar org-speed-command nil)
20090 (define-obsolete-function-alias
20091 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
20093 (defun org-speed-command-activate (keys)
20094 "Hook for activating single-letter speed commands.
20095 `org-speed-commands-default' specifies a minimal command set.
20096 Use `org-speed-commands-user' for further customization."
20097 (when (or (and (bolp) (looking-at org-outline-regexp))
20098 (and (functionp org-use-speed-commands)
20099 (funcall org-use-speed-commands)))
20100 (cdr (assoc keys (append org-speed-commands-user
20101 org-speed-commands-default)))))
20103 (define-obsolete-function-alias
20104 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
20106 (defun org-babel-speed-command-activate (keys)
20107 "Hook for activating single-letter code block commands."
20108 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20109 (cdr (assoc keys org-babel-key-bindings))))
20111 (defcustom org-speed-command-hook
20112 '(org-speed-command-default-hook org-babel-speed-command-hook)
20113 "Hook for activating speed commands at strategic locations.
20114 Hook functions are called in sequence until a valid handler is
20115 found.
20117 Each hook takes a single argument, a user-pressed command key
20118 which is also a `self-insert-command' from the global map.
20120 Within the hook, examine the cursor position and the command key
20121 and return nil or a valid handler as appropriate. Handler could
20122 be one of an interactive command, a function, or a form.
20124 Set `org-use-speed-commands' to non-nil value to enable this
20125 hook. The default setting is `org-speed-command-activate'."
20126 :group 'org-structure
20127 :version "24.1"
20128 :type 'hook)
20130 (defun org-self-insert-command (N)
20131 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20132 If the cursor is in a table looking at whitespace, the whitespace is
20133 overwritten, and the table is not marked as requiring realignment."
20134 (interactive "p")
20135 (org-check-before-invisible-edit 'insert)
20136 (cond
20137 ((and org-use-speed-commands
20138 (let ((kv (this-command-keys-vector)))
20139 (setq org-speed-command
20140 (run-hook-with-args-until-success
20141 'org-speed-command-hook
20142 (make-string 1 (aref kv (1- (length kv))))))))
20143 (cond
20144 ((commandp org-speed-command)
20145 (setq this-command org-speed-command)
20146 (call-interactively org-speed-command))
20147 ((functionp org-speed-command)
20148 (funcall org-speed-command))
20149 ((and org-speed-command (listp org-speed-command))
20150 (eval org-speed-command))
20151 (t (let (org-use-speed-commands)
20152 (call-interactively 'org-self-insert-command)))))
20153 ((and
20154 (org-at-table-p)
20155 (progn
20156 ;; Check if we blank the field, and if that triggers align.
20157 (and (featurep 'org-table) org-table-auto-blank-field
20158 (memq last-command
20159 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20160 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20161 ;; Got extra space, this field does not determine
20162 ;; column width.
20163 (let (org-table-may-need-update) (org-table-blank-field))
20164 ;; No extra space, this field may determine column
20165 ;; width.
20166 (org-table-blank-field)))
20168 (eq N 1)
20169 (looking-at "[^|\n]* \\( \\)|"))
20170 ;; There is room for insertion without re-aligning the table.
20171 (delete-region (match-beginning 1) (match-end 1))
20172 (self-insert-command N))
20174 (setq org-table-may-need-update t)
20175 (self-insert-command N)
20176 (org-fix-tags-on-the-fly)
20177 (when org-self-insert-cluster-for-undo
20178 (if (not (eq last-command 'org-self-insert-command))
20179 (setq org-self-insert-command-undo-counter 1)
20180 (if (>= org-self-insert-command-undo-counter 20)
20181 (setq org-self-insert-command-undo-counter 1)
20182 (and (> org-self-insert-command-undo-counter 0)
20183 buffer-undo-list (listp buffer-undo-list)
20184 (not (cadr buffer-undo-list)) ; remove nil entry
20185 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20186 (setq org-self-insert-command-undo-counter
20187 (1+ org-self-insert-command-undo-counter))))))))
20189 (defun org-check-before-invisible-edit (kind)
20190 "Check is editing if kind KIND would be dangerous with invisible text around.
20191 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20192 ;; First, try to get out of here as quickly as possible, to reduce overhead
20193 (when (and org-catch-invisible-edits
20194 (or (not (boundp 'visible-mode)) (not visible-mode))
20195 (or (get-char-property (point) 'invisible)
20196 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20197 ;; OK, we need to take a closer look
20198 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20199 (invisible-before-point (unless (bobp) (get-char-property
20200 (1- (point)) 'invisible)))
20201 (border-and-ok-direction
20203 ;; Check if we are acting predictably before invisible text
20204 (and invisible-at-point (not invisible-before-point)
20205 (memq kind '(insert delete-backward)))
20206 ;; Check if we are acting predictably after invisible text
20207 ;; This works not well, and I have turned it off. It seems
20208 ;; better to always show and stop after invisible text.
20209 ;; (and (not invisible-at-point) invisible-before-point
20210 ;; (memq kind '(insert delete)))
20212 (when (or (memq invisible-at-point '(outline org-hide-block t))
20213 (memq invisible-before-point '(outline org-hide-block t)))
20214 (when (eq org-catch-invisible-edits 'error)
20215 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20216 (if (and org-custom-properties-overlays
20217 (y-or-n-p "Display invisible properties in this buffer? "))
20218 (org-toggle-custom-properties-visibility)
20219 ;; Make the area visible
20220 (save-excursion
20221 (when invisible-before-point
20222 (goto-char (previous-single-char-property-change
20223 (point) 'invisible)))
20224 (outline-show-subtree))
20225 (cond
20226 ((eq org-catch-invisible-edits 'show)
20227 ;; That's it, we do the edit after showing
20228 (message
20229 "Unfolding invisible region around point before editing")
20230 (sit-for 1))
20231 ((and (eq org-catch-invisible-edits 'smart)
20232 border-and-ok-direction)
20233 (message "Unfolding invisible region around point before editing"))
20235 ;; Don't do the edit, make the user repeat it in full visibility
20236 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20238 (defun org-fix-tags-on-the-fly ()
20239 (when (and (equal (char-after (point-at-bol)) ?*)
20240 (org-at-heading-p))
20241 (org-align-tags-here org-tags-column)))
20243 (defun org-delete-backward-char (N)
20244 "Like `delete-backward-char', insert whitespace at field end in tables.
20245 When deleting backwards, in tables this function will insert whitespace in
20246 front of the next \"|\" separator, to keep the table aligned. The table will
20247 still be marked for re-alignment if the field did fill the entire column,
20248 because, in this case the deletion might narrow the column."
20249 (interactive "p")
20250 (save-match-data
20251 (org-check-before-invisible-edit 'delete-backward)
20252 (if (and (org-at-table-p)
20253 (eq N 1)
20254 (string-match "|" (buffer-substring (point-at-bol) (point)))
20255 (looking-at ".*?|"))
20256 (let ((pos (point))
20257 (noalign (looking-at "[^|\n\r]* |"))
20258 (c org-table-may-need-update))
20259 (backward-delete-char N)
20260 (unless overwrite-mode
20261 (skip-chars-forward "^|")
20262 (insert " ")
20263 (goto-char (1- pos)))
20264 ;; noalign: if there were two spaces at the end, this field
20265 ;; does not determine the width of the column.
20266 (when noalign (setq org-table-may-need-update c)))
20267 (backward-delete-char N)
20268 (org-fix-tags-on-the-fly))))
20270 (defun org-delete-char (N)
20271 "Like `delete-char', but insert whitespace at field end in tables.
20272 When deleting characters, in tables this function will insert whitespace in
20273 front of the next \"|\" separator, to keep the table aligned. The table will
20274 still be marked for re-alignment if the field did fill the entire column,
20275 because, in this case the deletion might narrow the column."
20276 (interactive "p")
20277 (save-match-data
20278 (org-check-before-invisible-edit 'delete)
20279 (if (and (org-at-table-p)
20280 (not (bolp))
20281 (not (= (char-after) ?|))
20282 (eq N 1))
20283 (if (looking-at ".*?|")
20284 (let ((pos (point))
20285 (noalign (looking-at "[^|\n\r]* |"))
20286 (c org-table-may-need-update))
20287 (replace-match
20288 (concat (substring (match-string 0) 1 -1) " |") nil t)
20289 (goto-char pos)
20290 ;; noalign: if there were two spaces at the end, this field
20291 ;; does not determine the width of the column.
20292 (when noalign (setq org-table-may-need-update c)))
20293 (delete-char N))
20294 (delete-char N)
20295 (org-fix-tags-on-the-fly))))
20297 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20298 (put 'org-self-insert-command 'delete-selection
20299 (lambda ()
20300 (not (run-hook-with-args-until-success
20301 'self-insert-uses-region-functions))))
20302 (put 'orgtbl-self-insert-command 'delete-selection
20303 (lambda ()
20304 (not (run-hook-with-args-until-success
20305 'self-insert-uses-region-functions))))
20306 (put 'org-delete-char 'delete-selection 'supersede)
20307 (put 'org-delete-backward-char 'delete-selection 'supersede)
20308 (put 'org-yank 'delete-selection 'yank)
20310 ;; Make `flyspell-mode' delay after some commands
20311 (put 'org-self-insert-command 'flyspell-delayed t)
20312 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20313 (put 'org-delete-char 'flyspell-delayed t)
20314 (put 'org-delete-backward-char 'flyspell-delayed t)
20316 ;; Make pabbrev-mode expand after org-mode commands
20317 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20318 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20320 (defun org-remap (map &rest commands)
20321 "In MAP, remap the functions given in COMMANDS.
20322 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20323 (let (new old)
20324 (while commands
20325 (setq old (pop commands) new (pop commands))
20326 (if (fboundp 'command-remapping)
20327 (org-defkey map (vector 'remap old) new)
20328 (substitute-key-definition old new map global-map)))))
20330 (defun org-transpose-words ()
20331 "Transpose words for Org.
20332 This uses the `org-mode-transpose-word-syntax-table' syntax
20333 table, which interprets characters in `org-emphasis-alist' as
20334 word constituents."
20335 (interactive)
20336 (with-syntax-table org-mode-transpose-word-syntax-table
20337 (call-interactively 'transpose-words)))
20338 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20340 (when (eq org-enable-table-editor 'optimized)
20341 ;; If the user wants maximum table support, we need to hijack
20342 ;; some standard editing functions
20343 (org-remap org-mode-map
20344 'self-insert-command 'org-self-insert-command
20345 'delete-char 'org-delete-char
20346 'delete-backward-char 'org-delete-backward-char)
20347 (org-defkey org-mode-map "|" 'org-force-self-insert))
20349 (defvar org-ctrl-c-ctrl-c-hook nil
20350 "Hook for functions attaching themselves to `C-c C-c'.
20352 This can be used to add additional functionality to the C-c C-c
20353 key which executes context-dependent commands. This hook is run
20354 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20355 run after the last test.
20357 Each function will be called with no arguments. The function
20358 must check if the context is appropriate for it to act. If yes,
20359 it should do its thing and then return a non-nil value. If the
20360 context is wrong, just do nothing and return nil.")
20362 (defvar org-ctrl-c-ctrl-c-final-hook nil
20363 "Hook for functions attaching themselves to `C-c C-c'.
20365 This can be used to add additional functionality to the C-c C-c
20366 key which executes context-dependent commands. This hook is run
20367 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20368 before the first test.
20370 Each function will be called with no arguments. The function
20371 must check if the context is appropriate for it to act. If yes,
20372 it should do its thing and then return a non-nil value. If the
20373 context is wrong, just do nothing and return nil.")
20375 (defvar org-tab-first-hook nil
20376 "Hook for functions to attach themselves to TAB.
20377 See `org-ctrl-c-ctrl-c-hook' for more information.
20378 This hook runs as the first action when TAB is pressed, even before
20379 `org-cycle' messes around with the `outline-regexp' to cater for
20380 inline tasks and plain list item folding.
20381 If any function in this hook returns t, any other actions that
20382 would have been caused by TAB (such as table field motion or visibility
20383 cycling) will not occur.")
20385 (defvar org-tab-after-check-for-table-hook nil
20386 "Hook for functions to attach themselves to TAB.
20387 See `org-ctrl-c-ctrl-c-hook' for more information.
20388 This hook runs after it has been established that the cursor is not in a
20389 table, but before checking if the cursor is in a headline or if global cycling
20390 should be done.
20391 If any function in this hook returns t, not other actions like visibility
20392 cycling will be done.")
20394 (defvar org-tab-after-check-for-cycling-hook nil
20395 "Hook for functions to attach themselves to TAB.
20396 See `org-ctrl-c-ctrl-c-hook' for more information.
20397 This hook runs after it has been established that not table field motion and
20398 not visibility should be done because of current context. This is probably
20399 the place where a package like yasnippets can hook in.")
20401 (defvar org-tab-before-tab-emulation-hook nil
20402 "Hook for functions to attach themselves to TAB.
20403 See `org-ctrl-c-ctrl-c-hook' for more information.
20404 This hook runs after every other options for TAB have been exhausted, but
20405 before indentation and \t insertion takes place.")
20407 (defvar org-metaleft-hook nil
20408 "Hook for functions attaching themselves to `M-left'.
20409 See `org-ctrl-c-ctrl-c-hook' for more information.")
20410 (defvar org-metaright-hook nil
20411 "Hook for functions attaching themselves to `M-right'.
20412 See `org-ctrl-c-ctrl-c-hook' for more information.")
20413 (defvar org-metaup-hook nil
20414 "Hook for functions attaching themselves to `M-up'.
20415 See `org-ctrl-c-ctrl-c-hook' for more information.")
20416 (defvar org-metadown-hook nil
20417 "Hook for functions attaching themselves to `M-down'.
20418 See `org-ctrl-c-ctrl-c-hook' for more information.")
20419 (defvar org-shiftmetaleft-hook nil
20420 "Hook for functions attaching themselves to `M-S-left'.
20421 See `org-ctrl-c-ctrl-c-hook' for more information.")
20422 (defvar org-shiftmetaright-hook nil
20423 "Hook for functions attaching themselves to `M-S-right'.
20424 See `org-ctrl-c-ctrl-c-hook' for more information.")
20425 (defvar org-shiftmetaup-hook nil
20426 "Hook for functions attaching themselves to `M-S-up'.
20427 See `org-ctrl-c-ctrl-c-hook' for more information.")
20428 (defvar org-shiftmetadown-hook nil
20429 "Hook for functions attaching themselves to `M-S-down'.
20430 See `org-ctrl-c-ctrl-c-hook' for more information.")
20431 (defvar org-metareturn-hook nil
20432 "Hook for functions attaching themselves to `M-RET'.
20433 See `org-ctrl-c-ctrl-c-hook' for more information.")
20434 (defvar org-shiftup-hook nil
20435 "Hook for functions attaching themselves to `S-up'.
20436 See `org-ctrl-c-ctrl-c-hook' for more information.")
20437 (defvar org-shiftup-final-hook nil
20438 "Hook for functions attaching themselves to `S-up'.
20439 This one runs after all other options except shift-select have been excluded.
20440 See `org-ctrl-c-ctrl-c-hook' for more information.")
20441 (defvar org-shiftdown-hook nil
20442 "Hook for functions attaching themselves to `S-down'.
20443 See `org-ctrl-c-ctrl-c-hook' for more information.")
20444 (defvar org-shiftdown-final-hook nil
20445 "Hook for functions attaching themselves to `S-down'.
20446 This one runs after all other options except shift-select have been excluded.
20447 See `org-ctrl-c-ctrl-c-hook' for more information.")
20448 (defvar org-shiftleft-hook nil
20449 "Hook for functions attaching themselves to `S-left'.
20450 See `org-ctrl-c-ctrl-c-hook' for more information.")
20451 (defvar org-shiftleft-final-hook nil
20452 "Hook for functions attaching themselves to `S-left'.
20453 This one runs after all other options except shift-select have been excluded.
20454 See `org-ctrl-c-ctrl-c-hook' for more information.")
20455 (defvar org-shiftright-hook nil
20456 "Hook for functions attaching themselves to `S-right'.
20457 See `org-ctrl-c-ctrl-c-hook' for more information.")
20458 (defvar org-shiftright-final-hook nil
20459 "Hook for functions attaching themselves to `S-right'.
20460 This one runs after all other options except shift-select have been excluded.
20461 See `org-ctrl-c-ctrl-c-hook' for more information.")
20463 (defun org-modifier-cursor-error ()
20464 "Throw an error, a modified cursor command was applied in wrong context."
20465 (user-error "This command is active in special context like tables, headlines or items"))
20467 (defun org-shiftselect-error ()
20468 "Throw an error because Shift-Cursor command was applied in wrong context."
20469 (if (and (boundp 'shift-select-mode) shift-select-mode)
20470 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20471 (user-error "This command works only in special context like headlines or timestamps")))
20473 (defun org-call-for-shift-select (cmd)
20474 (let ((this-command-keys-shift-translated t))
20475 (call-interactively cmd)))
20477 (defun org-shifttab (&optional arg)
20478 "Global visibility cycling or move to previous table field.
20479 Call `org-table-previous-field' within a table.
20480 When ARG is nil, cycle globally through visibility states.
20481 When ARG is a numeric prefix, show contents of this level."
20482 (interactive "P")
20483 (cond
20484 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20485 ((integerp arg)
20486 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20487 (message "Content view to level: %d" arg)
20488 (org-content (prefix-numeric-value arg2))
20489 (org-cycle-show-empty-lines t)
20490 (setq org-cycle-global-status 'overview)))
20491 (t (call-interactively 'org-global-cycle))))
20493 (defun org-shiftmetaleft ()
20494 "Promote subtree or delete table column.
20495 Calls `org-promote-subtree', `org-outdent-item-tree', or
20496 `org-table-delete-column', depending on context. See the
20497 individual commands for more information."
20498 (interactive)
20499 (cond
20500 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20501 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20502 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20503 ((if (not (org-region-active-p)) (org-at-item-p)
20504 (save-excursion (goto-char (region-beginning))
20505 (org-at-item-p)))
20506 (call-interactively 'org-outdent-item-tree))
20507 (t (org-modifier-cursor-error))))
20509 (defun org-shiftmetaright ()
20510 "Demote subtree or insert table column.
20511 Calls `org-demote-subtree', `org-indent-item-tree', or
20512 `org-table-insert-column', depending on context. See the
20513 individual commands for more information."
20514 (interactive)
20515 (cond
20516 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20517 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20518 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20519 ((if (not (org-region-active-p)) (org-at-item-p)
20520 (save-excursion (goto-char (region-beginning))
20521 (org-at-item-p)))
20522 (call-interactively 'org-indent-item-tree))
20523 (t (org-modifier-cursor-error))))
20525 (defun org-shiftmetaup (&optional _arg)
20526 "Drag the line at point up.
20527 In a table, kill the current row.
20528 On a clock timestamp, update the value of the timestamp like `S-<up>'
20529 but also adjust the previous clocked item in the clock history.
20530 Everywhere else, drag the line at point up."
20531 (interactive "P")
20532 (cond
20533 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20534 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20535 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20536 (call-interactively 'org-timestamp-up)))
20537 (t (call-interactively 'org-drag-line-backward))))
20539 (defun org-shiftmetadown (&optional _arg)
20540 "Drag the line at point down.
20541 In a table, insert an empty row at the current line.
20542 On a clock timestamp, update the value of the timestamp like `S-<down>'
20543 but also adjust the previous clocked item in the clock history.
20544 Everywhere else, drag the line at point down."
20545 (interactive "P")
20546 (cond
20547 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20548 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20549 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20550 (call-interactively 'org-timestamp-down)))
20551 (t (call-interactively 'org-drag-line-forward))))
20553 (defsubst org-hidden-tree-error ()
20554 (user-error
20555 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20557 (defun org-metaleft (&optional _arg)
20558 "Promote heading, list item at point or move table column left.
20560 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20561 depending on context. With no specific context, calls the Emacs
20562 default `backward-word'. See the individual commands for more
20563 information.
20565 This function runs the hook `org-metaleft-hook' as a first step,
20566 and returns at first non-nil value."
20567 (interactive "P")
20568 (cond
20569 ((run-hook-with-args-until-success 'org-metaleft-hook))
20570 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20571 ((org-with-limited-levels
20572 (or (org-at-heading-p)
20573 (and (org-region-active-p)
20574 (save-excursion
20575 (goto-char (region-beginning))
20576 (org-at-heading-p)))))
20577 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20578 (call-interactively 'org-do-promote))
20579 ;; At an inline task.
20580 ((org-at-heading-p)
20581 (call-interactively 'org-inlinetask-promote))
20582 ((or (org-at-item-p)
20583 (and (org-region-active-p)
20584 (save-excursion
20585 (goto-char (region-beginning))
20586 (org-at-item-p))))
20587 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20588 (call-interactively 'org-outdent-item))
20589 (t (call-interactively 'backward-word))))
20591 (defun org-metaright (&optional _arg)
20592 "Demote heading, list item at point or move table column right.
20594 In front of a drawer or a block keyword, indent it correctly.
20596 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20597 `org-indnet-drawer' or `org-indent-block' depending on context.
20598 With no specific context, calls the Emacs default `forward-word'.
20599 See the individual commands for more information.
20601 This function runs the hook `org-metaright-hook' as a first step,
20602 and returns at first non-nil value."
20603 (interactive "P")
20604 (cond
20605 ((run-hook-with-args-until-success 'org-metaright-hook))
20606 ((org-at-table-p) (call-interactively 'org-table-move-column))
20607 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20608 ((org-at-block-p) (call-interactively 'org-indent-block))
20609 ((org-with-limited-levels
20610 (or (org-at-heading-p)
20611 (and (org-region-active-p)
20612 (save-excursion
20613 (goto-char (region-beginning))
20614 (org-at-heading-p)))))
20615 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20616 (call-interactively 'org-do-demote))
20617 ;; At an inline task.
20618 ((org-at-heading-p)
20619 (call-interactively 'org-inlinetask-demote))
20620 ((or (org-at-item-p)
20621 (and (org-region-active-p)
20622 (save-excursion
20623 (goto-char (region-beginning))
20624 (org-at-item-p))))
20625 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20626 (call-interactively 'org-indent-item))
20627 (t (call-interactively 'forward-word))))
20629 (defun org-check-for-hidden (what)
20630 "Check if there are hidden headlines/items in the current visual line.
20631 WHAT can be either `headlines' or `items'. If the current line is
20632 an outline or item heading and it has a folded subtree below it,
20633 this function returns t, nil otherwise."
20634 (let ((re (cond
20635 ((eq what 'headlines) org-outline-regexp-bol)
20636 ((eq what 'items) (org-item-beginning-re))
20637 (t (error "This should not happen"))))
20638 beg end)
20639 (save-excursion
20640 (catch 'exit
20641 (unless (org-region-active-p)
20642 (setq beg (point-at-bol))
20643 (beginning-of-line 2)
20644 (while (and (not (eobp)) ;; this is like `next-line'
20645 (get-char-property (1- (point)) 'invisible))
20646 (beginning-of-line 2))
20647 (setq end (point))
20648 (goto-char beg)
20649 (goto-char (point-at-eol))
20650 (setq end (max end (point)))
20651 (while (re-search-forward re end t)
20652 (when (get-char-property (match-beginning 0) 'invisible)
20653 (throw 'exit t))))
20654 nil))))
20656 (defun org-metaup (&optional _arg)
20657 "Move subtree up or move table row up.
20658 Calls `org-move-subtree-up' or `org-table-move-row' or
20659 `org-move-item-up', depending on context. See the individual commands
20660 for more information."
20661 (interactive "P")
20662 (cond
20663 ((run-hook-with-args-until-success 'org-metaup-hook))
20664 ((org-region-active-p)
20665 (let* ((a (min (region-beginning) (region-end)))
20666 (b (1- (max (region-beginning) (region-end))))
20667 (c (save-excursion (goto-char a)
20668 (move-beginning-of-line 0)))
20669 (d (save-excursion (goto-char a)
20670 (move-end-of-line 0) (point))))
20671 (transpose-regions a b c d)
20672 (goto-char c)))
20673 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20674 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20675 ((org-at-item-p) (call-interactively 'org-move-item-up))
20676 (t (org-drag-element-backward))))
20678 (defun org-metadown (&optional _arg)
20679 "Move subtree down or move table row down.
20680 Calls `org-move-subtree-down' or `org-table-move-row' or
20681 `org-move-item-down', depending on context. See the individual
20682 commands for more information."
20683 (interactive "P")
20684 (cond
20685 ((run-hook-with-args-until-success 'org-metadown-hook))
20686 ((org-region-active-p)
20687 (let* ((a (min (region-beginning) (region-end)))
20688 (b (max (region-beginning) (region-end)))
20689 (c (save-excursion (goto-char b)
20690 (move-beginning-of-line 1)))
20691 (d (save-excursion (goto-char b)
20692 (move-end-of-line 1) (1+ (point)))))
20693 (transpose-regions a b c d)
20694 (goto-char d)))
20695 ((org-at-table-p) (call-interactively 'org-table-move-row))
20696 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20697 ((org-at-item-p) (call-interactively 'org-move-item-down))
20698 (t (org-drag-element-forward))))
20700 (defun org-shiftup (&optional arg)
20701 "Increase item in timestamp or increase priority of current headline.
20702 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20703 depending on context. See the individual commands for more information."
20704 (interactive "P")
20705 (cond
20706 ((run-hook-with-args-until-success 'org-shiftup-hook))
20707 ((and org-support-shift-select (org-region-active-p))
20708 (org-call-for-shift-select 'previous-line))
20709 ((org-at-timestamp-p t)
20710 (call-interactively (if org-edit-timestamp-down-means-later
20711 'org-timestamp-down 'org-timestamp-up)))
20712 ((and (not (eq org-support-shift-select 'always))
20713 org-enable-priority-commands
20714 (org-at-heading-p))
20715 (call-interactively 'org-priority-up))
20716 ((and (not org-support-shift-select) (org-at-item-p))
20717 (call-interactively 'org-previous-item))
20718 ((org-clocktable-try-shift 'up arg))
20719 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20720 (org-support-shift-select
20721 (org-call-for-shift-select 'previous-line))
20722 (t (org-shiftselect-error))))
20724 (defun org-shiftdown (&optional arg)
20725 "Decrease item in timestamp or decrease priority of current headline.
20726 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20727 depending on context. See the individual commands for more information."
20728 (interactive "P")
20729 (cond
20730 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20731 ((and org-support-shift-select (org-region-active-p))
20732 (org-call-for-shift-select 'next-line))
20733 ((org-at-timestamp-p t)
20734 (call-interactively (if org-edit-timestamp-down-means-later
20735 'org-timestamp-up 'org-timestamp-down)))
20736 ((and (not (eq org-support-shift-select 'always))
20737 org-enable-priority-commands
20738 (org-at-heading-p))
20739 (call-interactively 'org-priority-down))
20740 ((and (not org-support-shift-select) (org-at-item-p))
20741 (call-interactively 'org-next-item))
20742 ((org-clocktable-try-shift 'down arg))
20743 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20744 (org-support-shift-select
20745 (org-call-for-shift-select 'next-line))
20746 (t (org-shiftselect-error))))
20748 (defun org-shiftright (&optional arg)
20749 "Cycle the thing at point or in the current line, depending on context.
20750 Depending on context, this does one of the following:
20752 - switch a timestamp at point one day into the future
20753 - on a headline, switch to the next TODO keyword.
20754 - on an item, switch entire list to the next bullet type
20755 - on a property line, switch to the next allowed value
20756 - on a clocktable definition line, move time block into the future"
20757 (interactive "P")
20758 (cond
20759 ((run-hook-with-args-until-success 'org-shiftright-hook))
20760 ((and org-support-shift-select (org-region-active-p))
20761 (org-call-for-shift-select 'forward-char))
20762 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20763 ((and (not (eq org-support-shift-select 'always))
20764 (org-at-heading-p))
20765 (let ((org-inhibit-logging
20766 (not org-treat-S-cursor-todo-selection-as-state-change))
20767 (org-inhibit-blocking
20768 (not org-treat-S-cursor-todo-selection-as-state-change)))
20769 (org-call-with-arg 'org-todo 'right)))
20770 ((or (and org-support-shift-select
20771 (not (eq org-support-shift-select 'always))
20772 (org-at-item-bullet-p))
20773 (and (not org-support-shift-select) (org-at-item-p)))
20774 (org-call-with-arg 'org-cycle-list-bullet nil))
20775 ((and (not (eq org-support-shift-select 'always))
20776 (org-at-property-p))
20777 (call-interactively 'org-property-next-allowed-value))
20778 ((org-clocktable-try-shift 'right arg))
20779 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20780 (org-support-shift-select
20781 (org-call-for-shift-select 'forward-char))
20782 (t (org-shiftselect-error))))
20784 (defun org-shiftleft (&optional arg)
20785 "Cycle the thing at point or in the current line, depending on context.
20786 Depending on context, this does one of the following:
20788 - switch a timestamp at point one day into the past
20789 - on a headline, switch to the previous TODO keyword.
20790 - on an item, switch entire list to the previous bullet type
20791 - on a property line, switch to the previous allowed value
20792 - on a clocktable definition line, move time block into the past"
20793 (interactive "P")
20794 (cond
20795 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20796 ((and org-support-shift-select (org-region-active-p))
20797 (org-call-for-shift-select 'backward-char))
20798 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20799 ((and (not (eq org-support-shift-select 'always))
20800 (org-at-heading-p))
20801 (let ((org-inhibit-logging
20802 (not org-treat-S-cursor-todo-selection-as-state-change))
20803 (org-inhibit-blocking
20804 (not org-treat-S-cursor-todo-selection-as-state-change)))
20805 (org-call-with-arg 'org-todo 'left)))
20806 ((or (and org-support-shift-select
20807 (not (eq org-support-shift-select 'always))
20808 (org-at-item-bullet-p))
20809 (and (not org-support-shift-select) (org-at-item-p)))
20810 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20811 ((and (not (eq org-support-shift-select 'always))
20812 (org-at-property-p))
20813 (call-interactively 'org-property-previous-allowed-value))
20814 ((org-clocktable-try-shift 'left arg))
20815 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20816 (org-support-shift-select
20817 (org-call-for-shift-select 'backward-char))
20818 (t (org-shiftselect-error))))
20820 (defun org-shiftcontrolright ()
20821 "Switch to next TODO set."
20822 (interactive)
20823 (cond
20824 ((and org-support-shift-select (org-region-active-p))
20825 (org-call-for-shift-select 'forward-word))
20826 ((and (not (eq org-support-shift-select 'always))
20827 (org-at-heading-p))
20828 (org-call-with-arg 'org-todo 'nextset))
20829 (org-support-shift-select
20830 (org-call-for-shift-select 'forward-word))
20831 (t (org-shiftselect-error))))
20833 (defun org-shiftcontrolleft ()
20834 "Switch to previous TODO set."
20835 (interactive)
20836 (cond
20837 ((and org-support-shift-select (org-region-active-p))
20838 (org-call-for-shift-select 'backward-word))
20839 ((and (not (eq org-support-shift-select 'always))
20840 (org-at-heading-p))
20841 (org-call-with-arg 'org-todo 'previousset))
20842 (org-support-shift-select
20843 (org-call-for-shift-select 'backward-word))
20844 (t (org-shiftselect-error))))
20846 (defun org-shiftcontrolup (&optional n)
20847 "Change timestamps synchronously up in CLOCK log lines.
20848 Optional argument N tells to change by that many units."
20849 (interactive "P")
20850 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20851 (let (org-support-shift-select)
20852 (org-clock-timestamps-up n))
20853 (user-error "Not at a clock log")))
20855 (defun org-shiftcontroldown (&optional n)
20856 "Change timestamps synchronously down in CLOCK log lines.
20857 Optional argument N tells to change by that many units."
20858 (interactive "P")
20859 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20860 (let (org-support-shift-select)
20861 (org-clock-timestamps-down n))
20862 (user-error "Not at a clock log")))
20864 (defun org-increase-number-at-point (&optional inc)
20865 "Increment the number at point.
20866 With an optional prefix numeric argument INC, increment using
20867 this numeric value."
20868 (interactive "p")
20869 (if (not (number-at-point))
20870 (user-error "Not on a number")
20871 (unless inc (setq inc 1))
20872 (let ((pos (point))
20873 (beg (skip-chars-backward "-+^/*0-9eE."))
20874 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20875 (setq nap (buffer-substring-no-properties
20876 (+ pos beg) (+ pos beg end)))
20877 (delete-region (+ pos beg) (+ pos beg end))
20878 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20879 (when (org-at-table-p)
20880 (org-table-align)
20881 (org-table-end-of-field 1))))
20883 (defun org-decrease-number-at-point (&optional inc)
20884 "Decrement the number at point.
20885 With an optional prefix numeric argument INC, decrement using
20886 this numeric value."
20887 (interactive "p")
20888 (org-increase-number-at-point (- (or inc 1))))
20890 (defun org-ctrl-c-ret ()
20891 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20892 (interactive)
20893 (cond
20894 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20895 (t (call-interactively 'org-insert-heading))))
20897 (defun org-find-visible ()
20898 (let ((s (point)))
20899 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20900 (get-char-property s 'invisible)))
20902 (defun org-find-invisible ()
20903 (let ((s (point)))
20904 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20905 (not (get-char-property s 'invisible))))
20908 (defun org-copy-visible (beg end)
20909 "Copy the visible parts of the region."
20910 (interactive "r")
20911 (let (snippets s)
20912 (save-excursion
20913 (save-restriction
20914 (narrow-to-region beg end)
20915 (setq s (goto-char (point-min)))
20916 (while (not (= (point) (point-max)))
20917 (goto-char (org-find-invisible))
20918 (push (buffer-substring s (point)) snippets)
20919 (setq s (goto-char (org-find-visible))))))
20920 (kill-new (apply 'concat (nreverse snippets)))))
20922 (defun org-copy-special ()
20923 "Copy region in table or copy current subtree.
20924 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20925 See the individual commands for more information."
20926 (interactive)
20927 (call-interactively
20928 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20930 (defun org-cut-special ()
20931 "Cut region in table or cut current subtree.
20932 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20933 See the individual commands for more information."
20934 (interactive)
20935 (call-interactively
20936 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20938 (defun org-paste-special (arg)
20939 "Paste rectangular region into table, or past subtree relative to level.
20940 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20941 See the individual commands for more information."
20942 (interactive "P")
20943 (if (org-at-table-p)
20944 (org-table-paste-rectangle)
20945 (org-paste-subtree arg)))
20947 (defsubst org-in-fixed-width-region-p ()
20948 "Is point in a fixed-width region?"
20949 (save-match-data
20950 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20952 (defun org-edit-special (&optional arg)
20953 "Call a special editor for the element at point.
20954 When at a table, call the formula editor with `org-table-edit-formulas'.
20955 When in a source code block, call `org-edit-src-code'.
20956 When in a fixed-width region, call `org-edit-fixed-width-region'.
20957 When in an export block, call `org-edit-export-block'.
20958 When at an #+INCLUDE keyword, visit the included file.
20959 When at a footnote reference, call `org-edit-footnote-reference'
20960 On a link, call `ffap' to visit the link at point.
20961 Otherwise, return a user error."
20962 (interactive "P")
20963 (let ((element (org-element-at-point)))
20964 (cl-assert (not buffer-read-only) nil
20965 "Buffer is read-only: %s" (buffer-name))
20966 (pcase (org-element-type element)
20967 (`src-block
20968 (if (not arg) (org-edit-src-code)
20969 (let* ((info (org-babel-get-src-block-info))
20970 (lang (nth 0 info))
20971 (params (nth 2 info))
20972 (session (cdr (assq :session params))))
20973 (if (not session) (org-edit-src-code)
20974 ;; At a src-block with a session and function called with
20975 ;; an ARG: switch to the buffer related to the inferior
20976 ;; process.
20977 (switch-to-buffer
20978 (funcall (intern (concat "org-babel-prep-session:" lang))
20979 session params))))))
20980 (`keyword
20981 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20982 (org-open-link-from-string
20983 (format "[[%s]]"
20984 (expand-file-name
20985 (let ((value (org-element-property :value element)))
20986 (cond ((not (org-string-nw-p value))
20987 (user-error "No file to edit"))
20988 ((string-match "\\`\"\\(.*?\\)\"" value)
20989 (match-string 1 value))
20990 ((string-match "\\`[^ \t\"]\\S-*" value)
20991 (match-string 0 value))
20992 (t (user-error "No valid file specified")))))))
20993 (user-error "No special environment to edit here")))
20994 (`table
20995 (if (eq (org-element-property :type element) 'table.el)
20996 (org-edit-table.el)
20997 (call-interactively 'org-table-edit-formulas)))
20998 ;; Only Org tables contain `table-row' type elements.
20999 (`table-row (call-interactively 'org-table-edit-formulas))
21000 (`example-block (org-edit-src-code))
21001 (`export-block (org-edit-export-block))
21002 (`fixed-width (org-edit-fixed-width-region))
21004 ;; No notable element at point. Though, we may be at a link or
21005 ;; a footnote reference, which are objects. Thus, scan deeper.
21006 (let ((context (org-element-context element)))
21007 (pcase (org-element-type context)
21008 (`footnote-reference (org-edit-footnote-reference))
21009 (`inline-src-block (org-edit-inline-src-code))
21010 (`link (call-interactively #'ffap))
21011 (_ (user-error "No special environment to edit here"))))))))
21013 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21014 (defun org-ctrl-c-ctrl-c (&optional arg)
21015 "Set tags in headline, or update according to changed information at point.
21017 This command does many different things, depending on context:
21019 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21020 this is what we do.
21022 - If the cursor is on a statistics cookie, update it.
21024 - If the cursor is in a headline, prompt for tags and insert them
21025 into the current line, aligned to `org-tags-column'. When called
21026 with prefix arg, realign all tags in the current buffer.
21028 - If the cursor is in one of the special #+KEYWORD lines, this
21029 triggers scanning the buffer for these lines and updating the
21030 information.
21032 - If the cursor is inside a table, realign the table. This command
21033 works even if the automatic table editor has been turned off.
21035 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21036 the entire table.
21038 - If the cursor is at a footnote reference or definition, jump to
21039 the corresponding definition or references, respectively.
21041 - If the cursor is a the beginning of a dynamic block, update it.
21043 - If the current buffer is a capture buffer, close note and file it.
21045 - If the cursor is on a <<<target>>>, update radio targets and
21046 corresponding links in this buffer.
21048 - If the cursor is on a numbered item in a plain list, renumber the
21049 ordered list.
21051 - If the cursor is on a checkbox, toggle it.
21053 - If the cursor is on a code block, evaluate it. The variable
21054 `org-confirm-babel-evaluate' can be used to control prompting
21055 before code block evaluation, by default every code block
21056 evaluation requires confirmation. Code block evaluation can be
21057 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21058 (interactive "P")
21059 (cond
21060 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21061 org-occur-highlights)
21062 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21063 (org-remove-occur-highlights)
21064 (message "Temporary highlights/overlays removed from current buffer"))
21065 ((and (local-variable-p 'org-finish-function (current-buffer))
21066 (fboundp org-finish-function))
21067 (funcall org-finish-function))
21068 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21070 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21071 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21072 (user-error "C-c C-c can do nothing useful at this location"))
21073 (let* ((context (org-element-context))
21074 (type (org-element-type context)))
21075 (cl-case type
21076 ;; When at a link, act according to the parent instead.
21077 (link (setq context (org-element-property :parent context))
21078 (setq type (org-element-type context)))
21079 ;; Unsupported object types: refer to the first supported
21080 ;; element or object containing it.
21081 ((bold code entity export-snippet inline-babel-call inline-src-block
21082 italic latex-fragment line-break macro strike-through subscript
21083 superscript underline verbatim)
21084 (setq context
21085 (org-element-lineage
21086 context '(radio-target paragraph verse-block table-cell)))))
21087 ;; For convenience: at the first line of a paragraph on the
21088 ;; same line as an item, apply function on that item instead.
21089 (when (eq type 'paragraph)
21090 (let ((parent (org-element-property :parent context)))
21091 (when (and (eq (org-element-type parent) 'item)
21092 (= (line-beginning-position)
21093 (org-element-property :begin parent)))
21094 (setq context parent type 'item))))
21095 ;; Act according to type of element or object at point.
21096 (cl-case type
21097 (clock (org-clock-update-time-maybe))
21098 (dynamic-block
21099 (save-excursion
21100 (goto-char (org-element-property :post-affiliated context))
21101 (org-update-dblock)))
21102 (footnote-definition
21103 (goto-char (org-element-property :post-affiliated context))
21104 (call-interactively 'org-footnote-action))
21105 (footnote-reference (call-interactively 'org-footnote-action))
21106 ((headline inlinetask)
21107 (save-excursion (goto-char (org-element-property :begin context))
21108 (call-interactively 'org-set-tags)))
21109 (item
21110 ;; At an item: a double C-u set checkbox to "[-]"
21111 ;; unconditionally, whereas a single one will toggle its
21112 ;; presence. Without a universal argument, if the item
21113 ;; has a checkbox, toggle it. Otherwise repair the list.
21114 (let* ((box (org-element-property :checkbox context))
21115 (struct (org-element-property :structure context))
21116 (old-struct (copy-tree struct))
21117 (parents (org-list-parents-alist struct))
21118 (prevs (org-list-prevs-alist struct))
21119 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21120 (org-list-set-checkbox
21121 (org-element-property :begin context) struct
21122 (cond ((equal arg '(16)) "[-]")
21123 ((and (not box) (equal arg '(4))) "[ ]")
21124 ((or (not box) (equal arg '(4))) nil)
21125 ((eq box 'on) "[ ]")
21126 (t "[X]")))
21127 ;; Mimic `org-list-write-struct' but with grabbing
21128 ;; a return value from `org-list-struct-fix-box'.
21129 (org-list-struct-fix-ind struct parents 2)
21130 (org-list-struct-fix-item-end struct)
21131 (org-list-struct-fix-bul struct prevs)
21132 (org-list-struct-fix-ind struct parents)
21133 (let ((block-item
21134 (org-list-struct-fix-box struct parents prevs orderedp)))
21135 (if (and box (equal struct old-struct))
21136 (if (equal arg '(16))
21137 (message "Checkboxes already reset")
21138 (user-error "Cannot toggle this checkbox: %s"
21139 (if (eq box 'on)
21140 "all subitems checked"
21141 "unchecked subitems")))
21142 (org-list-struct-apply-struct struct old-struct)
21143 (org-update-checkbox-count-maybe))
21144 (when block-item
21145 (message "Checkboxes were removed due to empty box at line %d"
21146 (org-current-line block-item))))))
21147 (keyword
21148 (let ((org-inhibit-startup-visibility-stuff t)
21149 (org-startup-align-all-tables nil))
21150 (when (boundp 'org-table-coordinate-overlays)
21151 (mapc #'delete-overlay org-table-coordinate-overlays)
21152 (setq org-table-coordinate-overlays nil))
21153 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21154 (message "Local setup has been refreshed"))
21155 (plain-list
21156 ;; At a plain list, with a double C-u argument, set
21157 ;; checkboxes of each item to "[-]", whereas a single one
21158 ;; will toggle their presence according to the state of the
21159 ;; first item in the list. Without an argument, repair the
21160 ;; list.
21161 (let* ((begin (org-element-property :contents-begin context))
21162 (beginm (move-marker (make-marker) begin))
21163 (struct (org-element-property :structure context))
21164 (old-struct (copy-tree struct))
21165 (first-box (save-excursion
21166 (goto-char begin)
21167 (looking-at org-list-full-item-re)
21168 (match-string-no-properties 3)))
21169 (new-box (cond ((equal arg '(16)) "[-]")
21170 ((equal arg '(4)) (unless first-box "[ ]"))
21171 ((equal first-box "[X]") "[ ]")
21172 (t "[X]"))))
21173 (cond
21174 (arg
21175 (dolist (pos
21176 (org-list-get-all-items
21177 begin struct (org-list-prevs-alist struct)))
21178 (org-list-set-checkbox pos struct new-box)))
21179 ((and first-box (eq (point) begin))
21180 ;; For convenience, when point is at bol on the first
21181 ;; item of the list and no argument is provided, simply
21182 ;; toggle checkbox of that item, if any.
21183 (org-list-set-checkbox begin struct new-box)))
21184 (org-list-write-struct
21185 struct (org-list-parents-alist struct) old-struct)
21186 (org-update-checkbox-count-maybe)
21187 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21188 ((property-drawer node-property)
21189 (call-interactively 'org-property-action))
21190 ((radio-target target)
21191 (call-interactively 'org-update-radio-target-regexp))
21192 (statistics-cookie
21193 (call-interactively 'org-update-statistics-cookies))
21194 ((table table-cell table-row)
21195 ;; At a table, recalculate every field and align it. Also
21196 ;; send the table if necessary. If the table has
21197 ;; a `table.el' type, just give up. At a table row or
21198 ;; cell, maybe recalculate line but always align table.
21199 (if (eq (org-element-property :type context) 'table.el)
21200 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21201 Use \\[org-edit-special] to edit table.el tables"))
21202 (let ((org-enable-table-editor t))
21203 (if (or (eq type 'table)
21204 ;; Check if point is at a TBLFM line.
21205 (and (eq type 'table-row)
21206 (= (point) (org-element-property :end context))))
21207 (save-excursion
21208 (if (org-at-TBLFM-p)
21209 (progn (require 'org-table)
21210 (org-table-calc-current-TBLFM))
21211 (goto-char (org-element-property :contents-begin context))
21212 (org-call-with-arg 'org-table-recalculate (or arg t))
21213 (orgtbl-send-table 'maybe)))
21214 (org-table-maybe-eval-formula)
21215 (cond (arg (call-interactively 'org-table-recalculate))
21216 ((org-table-maybe-recalculate-line))
21217 (t (org-table-align)))))))
21218 (timestamp (org-timestamp-change 0 'day))
21219 (otherwise
21220 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21221 (user-error
21222 "C-c C-c can do nothing useful at this location")))))))))
21224 (defun org-mode-restart ()
21225 (interactive)
21226 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
21227 (funcall major-mode)
21228 (hack-local-variables)
21229 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
21230 (org-indent-mode -1)))
21231 (message "%s restarted" major-mode))
21233 (defun org-kill-note-or-show-branches ()
21234 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21235 (interactive)
21236 (if (not org-finish-function)
21237 (progn
21238 (outline-hide-subtree)
21239 (call-interactively 'outline-show-branches))
21240 (let ((org-note-abort t))
21241 (funcall org-finish-function))))
21243 (defun org-delete-indentation (&optional ARG)
21244 "Join current line to previous and fix whitespace at join.
21246 If previous line is a headline add to headline title. Otherwise
21247 the function calls `delete-indentation'.
21249 With argument, join this line to following line."
21250 (interactive "*P")
21251 (if (save-excursion
21252 (if ARG (beginning-of-line)
21253 (forward-line -1))
21254 (looking-at org-complex-heading-regexp))
21255 ;; At headline.
21256 (let ((tags-column (when (match-beginning 5)
21257 (save-excursion (goto-char (match-beginning 5))
21258 (current-column))))
21259 (string (concat " " (progn (when ARG (forward-line 1))
21260 (org-trim (delete-and-extract-region
21261 (line-beginning-position)
21262 (line-end-position)))))))
21263 (unless (bobp) (delete-region (point) (1- (point))))
21264 (goto-char (or (match-end 4)
21265 (match-beginning 5)
21266 (match-end 0)))
21267 (skip-chars-backward " \t")
21268 (save-excursion (insert string))
21269 ;; Adjust alignment of tags.
21270 (when tags-column
21271 (org-align-tags-here (if org-auto-align-tags
21272 org-tags-column
21273 tags-column))))
21274 (delete-indentation ARG)))
21276 (defun org-open-line (n)
21277 "Insert a new row in tables, call `open-line' elsewhere.
21278 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21279 (interactive "*p")
21280 (cond
21281 ((not org-special-ctrl-o)
21282 (open-line n))
21283 ((org-at-table-p)
21284 (org-table-insert-row))
21286 (open-line n))))
21288 (defun org-return (&optional indent)
21289 "Goto next table row or insert a newline.
21291 Calls `org-table-next-row' or `newline', depending on context.
21293 When optional INDENT argument is non-nil, call
21294 `newline-and-indent' instead of `newline'.
21296 When `org-return-follows-link' is non-nil and point is on
21297 a timestamp or a link, call `org-open-at-point'. However, it
21298 will not happen if point is in a table or on a \"dead\"
21299 object (e.g., within a comment). In these case, you need to use
21300 `org-open-at-point' directly."
21301 (interactive)
21302 (let ((context (if org-return-follows-link (org-element-context)
21303 (org-element-at-point))))
21304 (cond
21305 ;; In a table, call `org-table-next-row'.
21306 ((or (and (eq (org-element-type context) 'table)
21307 (>= (point) (org-element-property :contents-begin context))
21308 (< (point) (org-element-property :contents-end context)))
21309 (org-element-lineage context '(table-row table-cell) t))
21310 (org-table-justify-field-maybe)
21311 (call-interactively #'org-table-next-row))
21312 ;; On a link or a timestamp, call `org-open-at-point' if
21313 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21314 ;; locations, e.g., in a comment, as `org-open-at-point'.
21315 ((and org-return-follows-link
21316 (or (org-in-regexp org-ts-regexp-both nil t)
21317 (org-in-regexp org-tsr-regexp-both nil t)
21318 (org-in-regexp org-any-link-re nil t)))
21319 (call-interactively #'org-open-at-point))
21320 ;; Insert newline in heading, but preserve tags.
21321 ((and (not (bolp))
21322 (save-excursion (beginning-of-line)
21323 (looking-at org-complex-heading-regexp)))
21324 ;; At headline. Split line. However, if point is on keyword,
21325 ;; priority cookie or tags, do not break any of them: add
21326 ;; a newline after the headline instead.
21327 (let ((tags-column (and (match-beginning 5)
21328 (save-excursion (goto-char (match-beginning 5))
21329 (current-column))))
21330 (string
21331 (when (and (match-end 4)
21332 (>= (point)
21333 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21334 (<= (point) (match-end 4)))
21335 (delete-and-extract-region (point) (match-end 4)))))
21336 (when (and tags-column string) ; Adjust tag alignment.
21337 (org-align-tags-here
21338 (if org-auto-align-tags org-tags-column tags-column)))
21339 (end-of-line)
21340 (org-show-entry)
21341 (if indent (newline-and-indent) (newline))
21342 (when string (save-excursion (insert (org-trim string))))))
21343 ;; In a list, make sure indenting keeps trailing text within.
21344 ((and indent
21345 (not (eolp))
21346 (org-element-lineage context '(item)))
21347 (let ((trailing-data
21348 (delete-and-extract-region (point) (line-end-position))))
21349 (newline-and-indent)
21350 (save-excursion (insert trailing-data))))
21351 (t (if indent (newline-and-indent) (newline))))))
21353 (defun org-return-indent ()
21354 "Goto next table row or insert a newline and indent.
21355 Calls `org-table-next-row' or `newline-and-indent', depending on
21356 context. See the individual commands for more information."
21357 (interactive)
21358 (org-return t))
21360 (defun org-ctrl-c-star ()
21361 "Compute table, or change heading status of lines.
21362 Calls `org-table-recalculate' or `org-toggle-heading',
21363 depending on context."
21364 (interactive)
21365 (cond
21366 ((org-at-table-p)
21367 (call-interactively 'org-table-recalculate))
21369 ;; Convert all lines in region to list items
21370 (call-interactively 'org-toggle-heading))))
21372 (defun org-ctrl-c-minus ()
21373 "Insert separator line in table or modify bullet status of line.
21374 Also turns a plain line or a region of lines into list items.
21375 Calls `org-table-insert-hline', `org-toggle-item', or
21376 `org-cycle-list-bullet', depending on context."
21377 (interactive)
21378 (cond
21379 ((org-at-table-p)
21380 (call-interactively 'org-table-insert-hline))
21381 ((org-region-active-p)
21382 (call-interactively 'org-toggle-item))
21383 ((org-in-item-p)
21384 (call-interactively 'org-cycle-list-bullet))
21386 (call-interactively 'org-toggle-item))))
21388 (defun org-toggle-item (arg)
21389 "Convert headings or normal lines to items, items to normal lines.
21390 If there is no active region, only the current line is considered.
21392 If the first non blank line in the region is a headline, convert
21393 all headlines to items, shifting text accordingly.
21395 If it is an item, convert all items to normal lines.
21397 If it is normal text, change region into a list of items.
21398 With a prefix argument ARG, change the region in a single item."
21399 (interactive "P")
21400 (let ((shift-text
21401 (function
21402 ;; Shift text in current section to IND, from point to END.
21403 ;; The function leaves point to END line.
21404 (lambda (ind end)
21405 (let ((min-i 1000) (end (copy-marker end)))
21406 ;; First determine the minimum indentation (MIN-I) of
21407 ;; the text.
21408 (save-excursion
21409 (catch 'exit
21410 (while (< (point) end)
21411 (let ((i (org-get-indentation)))
21412 (cond
21413 ;; Skip blank lines and inline tasks.
21414 ((looking-at "^[ \t]*$"))
21415 ((looking-at org-outline-regexp-bol))
21416 ;; We can't find less than 0 indentation.
21417 ((zerop i) (throw 'exit (setq min-i 0)))
21418 ((< i min-i) (setq min-i i))))
21419 (forward-line))))
21420 ;; Then indent each line so that a line indented to
21421 ;; MIN-I becomes indented to IND. Ignore blank lines
21422 ;; and inline tasks in the process.
21423 (let ((delta (- ind min-i)))
21424 (while (< (point) end)
21425 (unless (or (looking-at "^[ \t]*$")
21426 (looking-at org-outline-regexp-bol))
21427 (org-indent-line-to (+ (org-get-indentation) delta)))
21428 (forward-line)))))))
21429 (skip-blanks
21430 (function
21431 ;; Return beginning of first non-blank line, starting from
21432 ;; line at POS.
21433 (lambda (pos)
21434 (save-excursion
21435 (goto-char pos)
21436 (skip-chars-forward " \r\t\n")
21437 (point-at-bol)))))
21438 beg end)
21439 ;; Determine boundaries of changes.
21440 (if (org-region-active-p)
21441 (setq beg (funcall skip-blanks (region-beginning))
21442 end (copy-marker (region-end)))
21443 (setq beg (funcall skip-blanks (point-at-bol))
21444 end (copy-marker (point-at-eol))))
21445 ;; Depending on the starting line, choose an action on the text
21446 ;; between BEG and END.
21447 (org-with-limited-levels
21448 (save-excursion
21449 (goto-char beg)
21450 (cond
21451 ;; Case 1. Start at an item: de-itemize. Note that it only
21452 ;; happens when a region is active: `org-ctrl-c-minus'
21453 ;; would call `org-cycle-list-bullet' otherwise.
21454 ((org-at-item-p)
21455 (while (< (point) end)
21456 (when (org-at-item-p)
21457 (skip-chars-forward " \t")
21458 (delete-region (point) (match-end 0)))
21459 (forward-line)))
21460 ;; Case 2. Start at an heading: convert to items.
21461 ((org-at-heading-p)
21462 (let* ((bul (org-list-bullet-string "-"))
21463 (bul-len (length bul))
21464 (done (org-entry-is-done-p))
21465 (todo (org-entry-is-todo-p))
21466 ;; Indentation of the first heading. It should be
21467 ;; relative to the indentation of its parent, if any.
21468 (start-ind (save-excursion
21469 (cond
21470 ((not org-adapt-indentation) 0)
21471 ((not (outline-previous-heading)) 0)
21472 (t (length (match-string 0))))))
21473 ;; Level of first heading. Further headings will be
21474 ;; compared to it to determine hierarchy in the list.
21475 (ref-level (org-reduced-level (org-outline-level))))
21476 (when (or done todo) (org-todo ""))
21477 (while (< (point) end)
21478 (let* ((level (org-reduced-level (org-outline-level)))
21479 (delta (max 0 (- level ref-level))))
21480 ;; If current headline is less indented than the first
21481 ;; one, set it as reference, in order to preserve
21482 ;; subtrees.
21483 (when (< level ref-level) (setq ref-level level))
21484 (replace-match bul t t)
21485 (org-indent-line-to (+ start-ind (* delta bul-len)))
21486 (when (or done todo)
21487 (let* ((struct (org-list-struct))
21488 (old (copy-tree struct)))
21489 (org-list-set-checkbox (line-beginning-position)
21490 struct
21491 (if done "[X]" "[ ]"))
21492 (org-list-write-struct struct
21493 (org-list-parents-alist struct)
21494 old)))
21495 ;; Ensure all text down to END (or SECTION-END) belongs
21496 ;; to the newly created item.
21497 (let ((section-end (save-excursion
21498 (or (outline-next-heading) (point)))))
21499 (forward-line)
21500 (funcall shift-text
21501 (+ start-ind (* (1+ delta) bul-len))
21502 (min end section-end)))))))
21503 ;; Case 3. Normal line with ARG: make the first line of region
21504 ;; an item, and shift indentation of others lines to
21505 ;; set them as item's body.
21506 (arg (let* ((bul (org-list-bullet-string "-"))
21507 (bul-len (length bul))
21508 (ref-ind (org-get-indentation)))
21509 (skip-chars-forward " \t")
21510 (insert bul)
21511 (forward-line)
21512 (while (< (point) end)
21513 ;; Ensure that lines less indented than first one
21514 ;; still get included in item body.
21515 (funcall shift-text
21516 (+ ref-ind bul-len)
21517 (min end (save-excursion (or (outline-next-heading)
21518 (point)))))
21519 (forward-line))))
21520 ;; Case 4. Normal line without ARG: turn each non-item line
21521 ;; into an item.
21523 (while (< (point) end)
21524 (unless (or (org-at-heading-p) (org-at-item-p))
21525 (when (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21526 (replace-match
21527 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21528 (forward-line))))))))
21530 (defun org-toggle-heading (&optional nstars)
21531 "Convert headings to normal text, or items or text to headings.
21532 If there is no active region, only convert the current line.
21534 With a \\[universal-argument] prefix, convert the whole list at
21535 point into heading.
21537 In a region:
21539 - If the first non blank line is a headline, remove the stars
21540 from all headlines in the region.
21542 - If it is a normal line, turn each and every normal line (i.e.,
21543 not an heading or an item) in the region into headings. If you
21544 want to convert only the first line of this region, use one
21545 universal prefix argument.
21547 - If it is a plain list item, turn all plain list items into headings.
21549 When converting a line into a heading, the number of stars is chosen
21550 such that the lines become children of the current entry. However,
21551 when a numeric prefix argument is given, its value determines the
21552 number of stars to add."
21553 (interactive "P")
21554 (let ((skip-blanks
21555 (function
21556 ;; Return beginning of first non-blank line, starting from
21557 ;; line at POS.
21558 (lambda (pos)
21559 (save-excursion
21560 (goto-char pos)
21561 (while (org-at-comment-p) (forward-line))
21562 (skip-chars-forward " \r\t\n")
21563 (point-at-bol)))))
21564 beg end toggled)
21565 ;; Determine boundaries of changes. If a universal prefix has
21566 ;; been given, put the list in a region. If region ends at a bol,
21567 ;; do not consider the last line to be in the region.
21569 (when (and current-prefix-arg (org-at-item-p))
21570 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21571 (org-mark-element))
21573 (if (org-region-active-p)
21574 (setq beg (funcall skip-blanks (region-beginning))
21575 end (copy-marker (save-excursion
21576 (goto-char (region-end))
21577 (if (bolp) (point) (point-at-eol)))))
21578 (setq beg (funcall skip-blanks (point-at-bol))
21579 end (copy-marker (point-at-eol))))
21580 ;; Ensure inline tasks don't count as headings.
21581 (org-with-limited-levels
21582 (save-excursion
21583 (goto-char beg)
21584 (cond
21585 ;; Case 1. Started at an heading: de-star headings.
21586 ((org-at-heading-p)
21587 (while (< (point) end)
21588 (when (org-at-heading-p t)
21589 (looking-at org-outline-regexp) (replace-match "")
21590 (setq toggled t))
21591 (forward-line)))
21592 ;; Case 2. Started at an item: change items into headlines.
21593 ;; One star will be added by `org-list-to-subtree'.
21594 ((org-at-item-p)
21595 (while (< (point) end)
21596 (when (org-at-item-p)
21597 ;; Pay attention to cases when region ends before list.
21598 (let* ((struct (org-list-struct))
21599 (list-end
21600 (min (org-list-get-bottom-point struct) (1+ end))))
21601 (save-restriction
21602 (narrow-to-region (point) list-end)
21603 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21604 (setq toggled t))
21605 (forward-line)))
21606 ;; Case 3. Started at normal text: make every line an heading,
21607 ;; skipping headlines and items.
21608 (t (let* ((stars
21609 (make-string
21610 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21611 (add-stars
21612 (cond (nstars "") ; stars from prefix only
21613 ((equal stars "") "*") ; before first heading
21614 (org-odd-levels-only "**") ; inside heading, odd
21615 (t "*"))) ; inside heading, oddeven
21616 (rpl (concat stars add-stars " "))
21617 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21618 (while (< (point) (if (equal nstars '(4)) lend end))
21619 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21620 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21621 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21622 (forward-line)))))))
21623 (unless toggled (message "Cannot toggle heading from here"))))
21625 (defun org-meta-return (&optional _arg)
21626 "Insert a new heading or wrap a region in a table.
21627 Calls `org-insert-heading' or `org-table-wrap-region', depending
21628 on context. See the individual commands for more information."
21629 (interactive)
21630 (org-check-before-invisible-edit 'insert)
21631 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21632 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21633 #'org-insert-heading))))
21635 ;;; Menu entries
21637 (defsubst org-in-subtree-not-table-p ()
21638 "Are we in a subtree and not in a table?"
21639 (and (not (org-before-first-heading-p))
21640 (not (org-at-table-p))))
21642 ;; Define the Org-mode menus
21643 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21644 '("Tbl"
21645 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21646 ["Next Field" org-cycle (org-at-table-p)]
21647 ["Previous Field" org-shifttab (org-at-table-p)]
21648 ["Next Row" org-return (org-at-table-p)]
21649 "--"
21650 ["Blank Field" org-table-blank-field (org-at-table-p)]
21651 ["Edit Field" org-table-edit-field (org-at-table-p)]
21652 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21653 "--"
21654 ("Column"
21655 ["Move Column Left" org-metaleft (org-at-table-p)]
21656 ["Move Column Right" org-metaright (org-at-table-p)]
21657 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21658 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21659 ("Row"
21660 ["Move Row Up" org-metaup (org-at-table-p)]
21661 ["Move Row Down" org-metadown (org-at-table-p)]
21662 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21663 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21664 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21665 "--"
21666 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21667 ("Rectangle"
21668 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21669 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21670 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21671 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21672 "--"
21673 ("Calculate"
21674 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21675 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21676 ["Edit Formulas" org-edit-special (org-at-table-p)]
21677 "--"
21678 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21679 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21680 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21681 "--"
21682 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21683 "--"
21684 ["Sum Column/Rectangle" org-table-sum
21685 (or (org-at-table-p) (org-region-active-p))]
21686 ["Which Column?" org-table-current-column (org-at-table-p)])
21687 ["Debug Formulas"
21688 org-table-toggle-formula-debugger
21689 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21690 ["Show Col/Row Numbers"
21691 org-table-toggle-coordinate-overlays
21692 :style toggle
21693 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21694 "--"
21695 ["Create" org-table-create (and (not (org-at-table-p))
21696 org-enable-table-editor)]
21697 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21698 ["Import from File" org-table-import (not (org-at-table-p))]
21699 ["Export to File" org-table-export (org-at-table-p)]
21700 "--"
21701 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21702 "--"
21703 ("Plot"
21704 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21705 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21707 (easy-menu-define org-org-menu org-mode-map "Org menu"
21708 '("Org"
21709 ("Show/Hide"
21710 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21711 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21712 ["Sparse Tree..." org-sparse-tree t]
21713 ["Reveal Context" org-reveal t]
21714 ["Show All" outline-show-all t]
21715 "--"
21716 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21717 "--"
21718 ["New Heading" org-insert-heading t]
21719 ("Navigate Headings"
21720 ["Up" outline-up-heading t]
21721 ["Next" outline-next-visible-heading t]
21722 ["Previous" outline-previous-visible-heading t]
21723 ["Next Same Level" outline-forward-same-level t]
21724 ["Previous Same Level" outline-backward-same-level t]
21725 "--"
21726 ["Jump" org-goto t])
21727 ("Edit Structure"
21728 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21729 "--"
21730 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21731 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21732 "--"
21733 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21734 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21735 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21736 "--"
21737 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21738 "--"
21739 ["Copy visible text" org-copy-visible t]
21740 "--"
21741 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21742 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21743 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21744 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21745 "--"
21746 ["Sort Region/Children" org-sort t]
21747 "--"
21748 ["Convert to odd levels" org-convert-to-odd-levels t]
21749 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21750 ("Editing"
21751 ["Emphasis..." org-emphasize t]
21752 ["Edit Source Example" org-edit-special t]
21753 "--"
21754 ["Footnote new/jump" org-footnote-action t]
21755 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21756 ("Archive"
21757 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21758 "--"
21759 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21760 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21761 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21763 "--"
21764 ("Hyperlinks"
21765 ["Store Link (Global)" org-store-link t]
21766 ["Find existing link to here" org-occur-link-in-agenda-files t]
21767 ["Insert Link" org-insert-link t]
21768 ["Follow Link" org-open-at-point t]
21769 "--"
21770 ["Next link" org-next-link t]
21771 ["Previous link" org-previous-link t]
21772 "--"
21773 ["Descriptive Links"
21774 org-toggle-link-display
21775 :style radio
21776 :selected org-descriptive-links
21778 ["Literal Links"
21779 org-toggle-link-display
21780 :style radio
21781 :selected (not org-descriptive-links)])
21782 "--"
21783 ("TODO Lists"
21784 ["TODO/DONE/-" org-todo t]
21785 ("Select keyword"
21786 ["Next keyword" org-shiftright (org-at-heading-p)]
21787 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21788 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21789 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21790 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21791 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21792 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21793 "--"
21794 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21795 :selected org-enforce-todo-dependencies :style toggle :active t]
21796 "Settings for tree at point"
21797 ["Do Children sequentially" org-toggle-ordered-property :style radio
21798 :selected (org-entry-get nil "ORDERED")
21799 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21800 ["Do Children parallel" org-toggle-ordered-property :style radio
21801 :selected (not (org-entry-get nil "ORDERED"))
21802 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21803 "--"
21804 ["Set Priority" org-priority t]
21805 ["Priority Up" org-shiftup t]
21806 ["Priority Down" org-shiftdown t]
21807 "--"
21808 ["Get news from all feeds" org-feed-update-all t]
21809 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21810 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21811 ("TAGS and Properties"
21812 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21813 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21814 "--"
21815 ["Set property" org-set-property (not (org-before-first-heading-p))]
21816 ["Column view of properties" org-columns t]
21817 ["Insert Column View DBlock" org-insert-columns-dblock t])
21818 ("Dates and Scheduling"
21819 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21820 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21821 ("Change Date"
21822 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21823 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21824 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21825 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21826 ["Compute Time Range" org-evaluate-time-range t]
21827 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21828 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21829 "--"
21830 ["Custom time format" org-toggle-time-stamp-overlays
21831 :style radio :selected org-display-custom-times]
21832 "--"
21833 ["Goto Calendar" org-goto-calendar t]
21834 ["Date from Calendar" org-date-from-calendar t]
21835 "--"
21836 ["Start/Restart Timer" org-timer-start t]
21837 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21838 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21839 ["Insert Timer String" org-timer t]
21840 ["Insert Timer Item" org-timer-item t])
21841 ("Logging work"
21842 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21843 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21844 ["Clock out" org-clock-out t]
21845 ["Clock cancel" org-clock-cancel t]
21846 "--"
21847 ["Mark as default task" org-clock-mark-default-task t]
21848 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21849 ["Goto running clock" org-clock-goto t]
21850 "--"
21851 ["Display times" org-clock-display t]
21852 ["Create clock table" org-clock-report t]
21853 "--"
21854 ["Record DONE time"
21855 (progn (setq org-log-done (not org-log-done))
21856 (message "Switching to %s will %s record a timestamp"
21857 (car org-done-keywords)
21858 (if org-log-done "automatically" "not")))
21859 :style toggle :selected org-log-done])
21860 "--"
21861 ["Agenda Command..." org-agenda t]
21862 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21863 ("File List for Agenda")
21864 ("Special views current file"
21865 ["TODO Tree" org-show-todo-tree t]
21866 ["Check Deadlines" org-check-deadlines t]
21867 ["Timeline" org-timeline t]
21868 ["Tags/Property tree" org-match-sparse-tree t])
21869 "--"
21870 ["Export/Publish..." org-export-dispatch t]
21871 ("LaTeX"
21872 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21873 :selected org-cdlatex-mode]
21874 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21875 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21876 ["Modify math symbol" org-cdlatex-math-modify
21877 (org-inside-LaTeX-fragment-p)]
21878 ["Insert citation" org-reftex-citation t]
21879 "--"
21880 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21881 "--"
21882 ("MobileOrg"
21883 ["Push Files and Views" org-mobile-push t]
21884 ["Get Captured and Flagged" org-mobile-pull t]
21885 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21886 "--"
21887 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21888 "--"
21889 ("Documentation"
21890 ["Show Version" org-version t]
21891 ["Info Documentation" org-info t])
21892 ("Customize"
21893 ["Browse Org Group" org-customize t]
21894 "--"
21895 ["Expand This Menu" org-create-customize-menu
21896 (fboundp 'customize-menu-create)])
21897 ["Send bug report" org-submit-bug-report t]
21898 "--"
21899 ("Refresh/Reload"
21900 ["Refresh setup current buffer" org-mode-restart t]
21901 ["Reload Org (after update)" org-reload t]
21902 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21905 (defun org-info (&optional node)
21906 "Read documentation for Org-mode in the info system.
21907 With optional NODE, go directly to that node."
21908 (interactive)
21909 (info (format "(org)%s" (or node ""))))
21911 ;;;###autoload
21912 (defun org-submit-bug-report ()
21913 "Submit a bug report on Org-mode via mail.
21915 Don't hesitate to report any problems or inaccurate documentation.
21917 If you don't have setup sending mail from (X)Emacs, please copy the
21918 output buffer into your mail program, as it gives us important
21919 information about your Org-mode version and configuration."
21920 (interactive)
21921 (require 'reporter)
21922 (defvar reporter-prompt-for-summary-p)
21923 (org-load-modules-maybe)
21924 (org-require-autoloaded-modules)
21925 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21926 (reporter-submit-bug-report
21927 "emacs-orgmode@gnu.org"
21928 (org-version nil 'full)
21929 (let (list)
21930 (save-window-excursion
21931 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21932 (delete-other-windows)
21933 (erase-buffer)
21934 (insert "You are about to submit a bug report to the Org-mode mailing list.
21936 We would like to add your full Org-mode and Outline configuration to the
21937 bug report. This greatly simplifies the work of the maintainer and
21938 other experts on the mailing list.
21940 HOWEVER, some variables you have customized may contain private
21941 information. The names of customers, colleagues, or friends, might
21942 appear in the form of file names, tags, todo states, or search strings.
21943 If you answer yes to the prompt, you might want to check and remove
21944 such private information before sending the email.")
21945 (add-text-properties (point-min) (point-max) '(face org-warning))
21946 (when (yes-or-no-p "Include your Org-mode configuration ")
21947 (mapatoms
21948 (lambda (v)
21949 (and (boundp v)
21950 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21951 (or (and (symbol-value v)
21952 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21953 (and
21954 (get v 'custom-type) (get v 'standard-value)
21955 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21956 (push v list)))))
21957 (kill-buffer (get-buffer "*Warn about privacy*"))
21958 list))
21959 nil nil
21960 "Remember to cover the basics, that is, what you expected to happen and
21961 what in fact did happen. You don't know how to make a good report? See
21963 http://orgmode.org/manual/Feedback.html#Feedback
21965 Your bug report will be posted to the Org-mode mailing list.
21966 ------------------------------------------------------------------------")
21967 (save-excursion
21968 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21969 (replace-match "\\1Bug: \\3 [\\2]")))))
21972 (defun org-install-agenda-files-menu ()
21973 (let ((bl (buffer-list)))
21974 (save-excursion
21975 (while bl
21976 (set-buffer (pop bl))
21977 (when (derived-mode-p 'org-mode) (setq bl nil)))
21978 (when (derived-mode-p 'org-mode)
21979 (easy-menu-change
21980 '("Org") "File List for Agenda"
21981 (append
21982 (list
21983 ["Edit File List" (org-edit-agenda-file-list) t]
21984 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21985 ["Remove Current File from List" org-remove-file t]
21986 ["Cycle through agenda files" org-cycle-agenda-files t]
21987 ["Occur in all agenda files" org-occur-in-agenda-files t]
21988 "--")
21989 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21991 ;;;; Documentation
21993 (defun org-require-autoloaded-modules ()
21994 (interactive)
21995 (mapc #'require
21996 '(org-agenda org-archive org-attach org-clock org-colview org-id
21997 org-table org-timer)))
21999 ;;;###autoload
22000 (defun org-reload (&optional uncompiled)
22001 "Reload all org lisp files.
22002 With prefix arg UNCOMPILED, load the uncompiled versions."
22003 (interactive "P")
22004 (require 'loadhist)
22005 (let* ((org-dir (org-find-library-dir "org"))
22006 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
22007 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
22008 (remove-re (mapconcat 'identity
22009 (mapcar (lambda (f) (concat "^" f "$"))
22010 (list (if (featurep 'xemacs)
22011 "org-colview"
22012 "org-colview-xemacs")
22013 "org" "org-loaddefs" "org-version"))
22014 "\\|"))
22015 (feats (delete-dups
22016 (mapcar 'file-name-sans-extension
22017 (mapcar 'file-name-nondirectory
22018 (delq nil
22019 (mapcar 'feature-file
22020 features))))))
22021 (lfeat (append
22022 (sort
22023 (setq feats
22024 (delq nil (mapcar
22025 (lambda (f)
22026 (if (and (string-match feature-re f)
22027 (not (string-match remove-re f)))
22028 f nil))
22029 feats)))
22030 'string-lessp)
22031 (list "org-version" "org")))
22032 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
22033 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
22034 load-uncore load-misses)
22035 (setq load-misses
22036 (delq 't
22037 (mapcar (lambda (f)
22038 (or (org-load-noerror-mustsuffix (concat org-dir f))
22039 (and (string= org-dir contrib-dir)
22040 (org-load-noerror-mustsuffix (concat contrib-dir f)))
22041 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
22042 (add-to-list 'load-uncore f 'append)
22045 lfeat)))
22046 (when load-uncore
22047 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
22048 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
22049 (if load-misses
22050 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
22051 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
22052 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
22054 ;;;###autoload
22055 (defun org-customize ()
22056 "Call the customize function with org as argument."
22057 (interactive)
22058 (org-load-modules-maybe)
22059 (org-require-autoloaded-modules)
22060 (customize-browse 'org))
22062 (defun org-create-customize-menu ()
22063 "Create a full customization menu for Org-mode, insert it into the menu."
22064 (interactive)
22065 (org-load-modules-maybe)
22066 (org-require-autoloaded-modules)
22067 (if (fboundp 'customize-menu-create)
22068 (progn
22069 (easy-menu-change
22070 '("Org") "Customize"
22071 `(["Browse Org group" org-customize t]
22072 "--"
22073 ,(customize-menu-create 'org)
22074 ["Set" Custom-set t]
22075 ["Save" Custom-save t]
22076 ["Reset to Current" Custom-reset-current t]
22077 ["Reset to Saved" Custom-reset-saved t]
22078 ["Reset to Standard Settings" Custom-reset-standard t]))
22079 (message "\"Org\"-menu now contains full customization menu"))
22080 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22082 ;;;; Miscellaneous stuff
22084 ;;; Generally useful functions
22086 (defun org-get-at-eol (property n)
22087 "Get text property PROPERTY at the end of line less N characters."
22088 (get-text-property (- (point-at-eol) n) property))
22090 (defun org-find-text-property-in-string (prop s)
22091 "Return the first non-nil value of property PROP in string S."
22092 (or (get-text-property 0 prop s)
22093 (get-text-property (or (next-single-property-change 0 prop s) 0)
22094 prop s)))
22096 (defun org-display-warning (message) ;; Copied from Emacs-Muse
22097 "Display the given MESSAGE as a warning."
22098 (if (fboundp 'display-warning)
22099 (display-warning 'org message
22100 (if (featurep 'xemacs) 'warning :warning))
22101 (let ((buf (get-buffer-create "*Org warnings*")))
22102 (with-current-buffer buf
22103 (goto-char (point-max))
22104 (insert "Warning (Org): " message)
22105 (unless (bolp)
22106 (newline)))
22107 (display-buffer buf)
22108 (sit-for 0))))
22110 (defun org-eval (form)
22111 "Eval FORM and return result."
22112 (condition-case error
22113 (eval form)
22114 (error (format "%%![Error: %s]" error))))
22116 (defun org-in-clocktable-p ()
22117 "Check if the cursor is in a clocktable."
22118 (let ((pos (point)) start)
22119 (save-excursion
22120 (end-of-line 1)
22121 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22122 (setq start (match-beginning 0))
22123 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22124 (>= (match-end 0) pos)
22125 start))))
22127 (defun org-in-verbatim-emphasis ()
22128 (save-match-data
22129 (and (org-in-regexp org-emph-re 2)
22130 (>= (point) (match-beginning 3))
22131 (<= (point) (match-end 4))
22132 (member (match-string 3) '("=" "~")))))
22134 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22135 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22136 (if (and marker (marker-buffer marker)
22137 (buffer-live-p (marker-buffer marker)))
22138 (progn
22139 (org-pop-to-buffer-same-window (marker-buffer marker))
22140 (when (or (> marker (point-max)) (< marker (point-min)))
22141 (widen))
22142 (goto-char marker)
22143 (org-show-context 'org-goto))
22144 (if bookmark
22145 (bookmark-jump bookmark)
22146 (error "Cannot find location"))))
22148 (defun org-quote-csv-field (s)
22149 "Quote field for inclusion in CSV material."
22150 (if (string-match "[\",]" s)
22151 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22154 (defun org-force-self-insert (N)
22155 "Needed to enforce self-insert under remapping."
22156 (interactive "p")
22157 (self-insert-command N))
22159 (defun org-string-width (s)
22160 "Compute width of string, ignoring invisible characters.
22161 This ignores character with invisibility property `org-link', and also
22162 characters with property `org-cwidth', because these will become invisible
22163 upon the next fontification round."
22164 (let (b l)
22165 (when (or (eq t buffer-invisibility-spec)
22166 (assq 'org-link buffer-invisibility-spec))
22167 (while (setq b (text-property-any 0 (length s)
22168 'invisible 'org-link s))
22169 (setq s (concat (substring s 0 b)
22170 (substring s (or (next-single-property-change
22171 b 'invisible s)
22172 (length s)))))))
22173 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22174 (setq s (concat (substring s 0 b)
22175 (substring s (or (next-single-property-change
22176 b 'org-cwidth s)
22177 (length s))))))
22178 (setq l (string-width s) b -1)
22179 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22180 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22183 (defun org-shorten-string (s maxlength)
22184 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22185 If the string is shorter or has length MAXLENGTH, just return the
22186 original string. If it is longer, the functions finds a space in the
22187 string, breaks this string off at that locations and adds three dots
22188 as ellipsis. Including the ellipsis, the string will not be longer
22189 than MAXLENGTH. If finding a good breaking point in the string does
22190 not work, the string is just chopped off in the middle of a word
22191 if necessary."
22192 (if (<= (length s) maxlength)
22194 (let* ((n (max (- maxlength 4) 1))
22195 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22196 (if (string-match re s)
22197 (concat (match-string 1 s) "...")
22198 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22200 (defun org-get-indentation (&optional line)
22201 "Get the indentation of the current line, interpreting tabs.
22202 When LINE is given, assume it represents a line and compute its indentation."
22203 (if line
22204 (when (string-match "^ *" (org-remove-tabs line))
22205 (match-end 0))
22206 (save-excursion
22207 (beginning-of-line 1)
22208 (skip-chars-forward " \t")
22209 (current-column))))
22211 (defun org-get-string-indentation (s)
22212 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22213 (let ((n -1) (i 0) (w tab-width) c)
22214 (catch 'exit
22215 (while (< (setq n (1+ n)) (length s))
22216 (setq c (aref s n))
22217 (cond ((= c ?\ ) (setq i (1+ i)))
22218 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22219 (t (throw 'exit t)))))
22222 (defun org-remove-tabs (s &optional width)
22223 "Replace tabulators in S with spaces.
22224 Assumes that s is a single line, starting in column 0."
22225 (setq width (or width tab-width))
22226 (while (string-match "\t" s)
22227 (setq s (replace-match
22228 (make-string
22229 (- (* width (/ (+ (match-beginning 0) width) width))
22230 (match-beginning 0)) ?\ )
22231 t t s)))
22234 (defun org-fix-indentation (line ind)
22235 "Fix indentation in LINE.
22236 IND is a cons cell with target and minimum indentation.
22237 If the current indentation in LINE is smaller than the minimum,
22238 leave it alone. If it is larger than ind, set it to the target."
22239 (let* ((l (org-remove-tabs line))
22240 (i (org-get-indentation l))
22241 (i1 (car ind)) (i2 (cdr ind)))
22242 (when (>= i i2) (setq l (substring line i2)))
22243 (if (> i1 0)
22244 (concat (make-string i1 ?\ ) l)
22245 l)))
22247 (defun org-remove-indentation (code &optional n)
22248 "Remove maximum common indentation in string CODE and return it.
22249 N may optionally be the number of columns to remove. Return CODE
22250 as-is if removal failed."
22251 (with-temp-buffer
22252 (insert code)
22253 (if (org-do-remove-indentation n) (buffer-string) code)))
22255 (defun org-do-remove-indentation (&optional n)
22256 "Remove the maximum common indentation from the buffer.
22257 When optional argument N is a positive integer, remove exactly
22258 that much characters from indentation, if possible. Return nil
22259 if it fails."
22260 (catch :exit
22261 (goto-char (point-min))
22262 ;; Find maximum common indentation, if not specified.
22263 (let ((n (or n
22264 (let ((min-ind (point-max)))
22265 (save-excursion
22266 (while (re-search-forward "^[ \t]*\\S-" nil t)
22267 (let ((ind (1- (current-column))))
22268 (if (zerop ind) (throw :exit nil)
22269 (setq min-ind (min min-ind ind))))))
22270 min-ind))))
22271 (if (zerop n) (throw :exit nil)
22272 ;; Remove exactly N indentation, but give up if not possible.
22273 (while (not (eobp))
22274 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22275 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22276 ((< ind n) (throw :exit nil))
22277 (t (org-indent-line-to (- ind n))))
22278 (forward-line)))
22279 ;; Signal success.
22280 t))))
22282 (defun org-fill-template (template alist)
22283 "Find each %key of ALIST in TEMPLATE and replace it."
22284 (let ((case-fold-search nil))
22285 (dolist (entry (sort (copy-sequence alist)
22286 (lambda (a b) (< (length (car a)) (length (car b))))))
22287 (setq template
22288 (replace-regexp-in-string
22289 (concat "%" (regexp-quote (car entry)))
22290 (or (cdr entry) "") template t t)))
22291 template))
22293 (defun org-base-buffer (buffer)
22294 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22295 (if (not buffer)
22296 buffer
22297 (or (buffer-base-buffer buffer)
22298 buffer)))
22300 (defun org-wrap (string &optional width lines)
22301 "Wrap string to either a number of lines, or a width in characters.
22302 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22303 that costs. If there is a word longer than WIDTH, the text is actually
22304 wrapped to the length of that word.
22305 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22306 many lines, whatever width that takes.
22307 The return value is a list of lines, without newlines at the end."
22308 (let* ((words (org-split-string string "[ \t\n]+"))
22309 (maxword (apply 'max (mapcar 'org-string-width words)))
22310 w ll)
22311 (cond (width
22312 (org-do-wrap words (max maxword width)))
22313 (lines
22314 (setq w maxword)
22315 (setq ll (org-do-wrap words maxword))
22316 (if (<= (length ll) lines)
22318 (setq ll words)
22319 (while (> (length ll) lines)
22320 (setq w (1+ w))
22321 (setq ll (org-do-wrap words w)))
22322 ll))
22323 (t (error "Cannot wrap this")))))
22325 (defun org-do-wrap (words width)
22326 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22327 (let (lines line)
22328 (while words
22329 (setq line (pop words))
22330 (while (and words (< (+ (length line) (length (car words))) width))
22331 (setq line (concat line " " (pop words))))
22332 (setq lines (push line lines)))
22333 (nreverse lines)))
22335 (defun org-split-string (string &optional separators)
22336 "Splits STRING into substrings at SEPARATORS.
22337 SEPARATORS is a regular expression.
22338 No empty strings are returned if there are matches at the beginning
22339 and end of string."
22340 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22341 (let ((start 0) notfirst list)
22342 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22343 (if (and notfirst
22344 (= start (match-beginning 0))
22345 (< start (length string)))
22346 (1+ start) start))
22347 (< (match-beginning 0) (length string)))
22348 (setq notfirst t)
22349 (or (eq (match-beginning 0) 0)
22350 (and (eq (match-beginning 0) (match-end 0))
22351 (eq (match-beginning 0) start))
22352 (push (substring string start (match-beginning 0)) list))
22353 (setq start (match-end 0)))
22354 (or (eq start (length string))
22355 (push (substring string start) list))
22356 (nreverse list)))
22358 (defun org-quote-vert (s)
22359 "Replace \"|\" with \"\\vert\"."
22360 (while (string-match "|" s)
22361 (setq s (replace-match "\\vert" t t s)))
22364 (defun org-uuidgen-p (s)
22365 "Is S an ID created by UUIDGEN?"
22366 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22368 (defun org-in-src-block-p (&optional inside)
22369 "Whether point is in a code source block.
22370 When INSIDE is non-nil, don't consider we are within a src block
22371 when point is at #+BEGIN_SRC or #+END_SRC."
22372 (let ((case-fold-search t))
22373 (or (and (eq (get-char-property (point) 'src-block) t))
22374 (and (not inside)
22375 (save-match-data
22376 (save-excursion
22377 (beginning-of-line)
22378 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22380 (defun org-context ()
22381 "Return a list of contexts of the current cursor position.
22382 If several contexts apply, all are returned.
22383 Each context entry is a list with a symbol naming the context, and
22384 two positions indicating start and end of the context. Possible
22385 contexts are:
22387 :headline anywhere in a headline
22388 :headline-stars on the leading stars in a headline
22389 :todo-keyword on a TODO keyword (including DONE) in a headline
22390 :tags on the TAGS in a headline
22391 :priority on the priority cookie in a headline
22392 :item on the first line of a plain list item
22393 :item-bullet on the bullet/number of a plain list item
22394 :checkbox on the checkbox in a plain list item
22395 :table in an org-mode table
22396 :table-special on a special filed in a table
22397 :table-table in a table.el table
22398 :clocktable in a clocktable
22399 :src-block in a source block
22400 :link on a hyperlink
22401 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22402 :target on a <<target>>
22403 :radio-target on a <<<radio-target>>>
22404 :latex-fragment on a LaTeX fragment
22405 :latex-preview on a LaTeX fragment with overlaid preview image
22407 This function expects the position to be visible because it uses font-lock
22408 faces as a help to recognize the following contexts: :table-special, :link,
22409 and :keyword."
22410 (let* ((f (get-text-property (point) 'face))
22411 (faces (if (listp f) f (list f)))
22412 (case-fold-search t)
22413 (p (point)) clist o)
22414 ;; First the large context
22415 (cond
22416 ((org-at-heading-p t)
22417 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22418 (when (progn
22419 (beginning-of-line 1)
22420 (looking-at org-todo-line-tags-regexp))
22421 (push (org-point-in-group p 1 :headline-stars) clist)
22422 (push (org-point-in-group p 2 :todo-keyword) clist)
22423 (push (org-point-in-group p 4 :tags) clist))
22424 (goto-char p)
22425 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22426 (when (looking-at "\\[#[A-Z0-9]\\]")
22427 (push (org-point-in-group p 0 :priority) clist)))
22429 ((org-at-item-p)
22430 (push (org-point-in-group p 2 :item-bullet) clist)
22431 (push (list :item (point-at-bol)
22432 (save-excursion (org-end-of-item) (point)))
22433 clist)
22434 (and (org-at-item-checkbox-p)
22435 (push (org-point-in-group p 0 :checkbox) clist)))
22437 ((org-at-table-p)
22438 (push (list :table (org-table-begin) (org-table-end)) clist)
22439 (when (memq 'org-formula faces)
22440 (push (list :table-special
22441 (previous-single-property-change p 'face)
22442 (next-single-property-change p 'face)) clist)))
22443 ((org-at-table-p 'any)
22444 (push (list :table-table) clist)))
22445 (goto-char p)
22447 (let ((case-fold-search t))
22448 ;; New the "medium" contexts: clocktables, source blocks
22449 (cond ((org-in-clocktable-p)
22450 (push (list :clocktable
22451 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22452 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22453 (match-beginning 1))
22454 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22455 (match-end 0))) clist))
22456 ((org-in-src-block-p)
22457 (push (list :src-block
22458 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22459 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22460 (match-beginning 1))
22461 (and (search-forward "#+END_SRC" nil t)
22462 (match-beginning 0))) clist))))
22463 (goto-char p)
22465 ;; Now the small context
22466 (cond
22467 ((org-at-timestamp-p)
22468 (push (org-point-in-group p 0 :timestamp) clist))
22469 ((memq 'org-link faces)
22470 (push (list :link
22471 (previous-single-property-change p 'face)
22472 (next-single-property-change p 'face)) clist))
22473 ((memq 'org-special-keyword faces)
22474 (push (list :keyword
22475 (previous-single-property-change p 'face)
22476 (next-single-property-change p 'face)) clist))
22477 ((org-at-target-p)
22478 (push (org-point-in-group p 0 :target) clist)
22479 (goto-char (1- (match-beginning 0)))
22480 (when (looking-at org-radio-target-regexp)
22481 (push (org-point-in-group p 0 :radio-target) clist))
22482 (goto-char p))
22483 ((setq o (car (delq nil
22484 (mapcar
22485 (lambda (x)
22486 (when (memq x org-latex-fragment-image-overlays) x))
22487 (overlays-at (point))))))
22488 (push (list :latex-fragment
22489 (overlay-start o) (overlay-end o)) clist)
22490 (push (list :latex-preview
22491 (overlay-start o) (overlay-end o)) clist))
22492 ((org-inside-LaTeX-fragment-p)
22493 ;; FIXME: positions wrong.
22494 (push (list :latex-fragment (point) (point)) clist)))
22496 (setq clist (nreverse (delq nil clist)))
22497 clist))
22499 (defun org-in-regexp (regexp &optional nlines visually)
22500 "Check if point is inside a match of REGEXP.
22502 Normally only the current line is checked, but you can include
22503 NLINES extra lines around point into the search. If VISUALLY is
22504 set, require that the cursor is not after the match but really
22505 on, so that the block visually is on the match.
22507 Return nil or a cons cell (BEG . END) where BEG and END are,
22508 respectively, the positions at the beginning and the end of the
22509 match."
22510 (catch :exit
22511 (let ((pos (point))
22512 (eol (line-end-position (if nlines (1+ nlines) 1))))
22513 (save-excursion
22514 (beginning-of-line (- 1 (or nlines 0)))
22515 (while (and (re-search-forward regexp eol t)
22516 (<= (match-beginning 0) pos))
22517 (let ((end (match-end 0)))
22518 (when (or (> end pos) (and (= end pos) (not visually)))
22519 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22520 (define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp
22521 "Org mode 8.3")
22523 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22524 "Non-nil when point is between matches of START-RE and END-RE.
22526 Also return a non-nil value when point is on one of the matches.
22528 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22529 buffer positions. Default values are the positions of headlines
22530 surrounding the point.
22532 The functions returns a cons cell whose car (resp. cdr) is the
22533 position before START-RE (resp. after END-RE)."
22534 (save-match-data
22535 (let ((pos (point))
22536 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22537 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22538 beg end)
22539 (save-excursion
22540 ;; Point is on a block when on START-RE or if START-RE can be
22541 ;; found before it...
22542 (and (or (org-in-regexp start-re)
22543 (re-search-backward start-re limit-up t))
22544 (setq beg (match-beginning 0))
22545 ;; ... and END-RE after it...
22546 (goto-char (match-end 0))
22547 (re-search-forward end-re limit-down t)
22548 (> (setq end (match-end 0)) pos)
22549 ;; ... without another START-RE in-between.
22550 (goto-char (match-beginning 0))
22551 (not (re-search-backward start-re (1+ beg) t))
22552 ;; Return value.
22553 (cons beg end))))))
22555 (defun org-in-block-p (names)
22556 "Non-nil when point belongs to a block whose name belongs to NAMES.
22558 NAMES is a list of strings containing names of blocks.
22560 Return first block name matched, or nil. Beware that in case of
22561 nested blocks, the returned name may not belong to the closest
22562 block from point."
22563 (save-match-data
22564 (catch 'exit
22565 (let ((case-fold-search t)
22566 (lim-up (save-excursion (outline-previous-heading)))
22567 (lim-down (save-excursion (outline-next-heading))))
22568 (dolist (name names)
22569 (let ((n (regexp-quote name)))
22570 (when (org-between-regexps-p
22571 (concat "^[ \t]*#\\+begin_" n)
22572 (concat "^[ \t]*#\\+end_" n)
22573 lim-up lim-down)
22574 (throw 'exit n)))))
22575 nil)))
22577 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22578 "Call `multi-occur' with buffers for all agenda files."
22579 (interactive "sOrg-files matching: ")
22580 (let* ((files (org-agenda-files))
22581 (tnames (mapcar #'file-truename files))
22582 (extra org-agenda-text-search-extra-files))
22583 (when (eq (car extra) 'agenda-archives)
22584 (setq extra (cdr extra))
22585 (setq files (org-add-archive-files files)))
22586 (dolist (f extra)
22587 (unless (member (file-truename f) tnames)
22588 (unless (member f files) (setq files (append files (list f))))
22589 (setq tnames (append tnames (list (file-truename f))))))
22590 (multi-occur
22591 (mapcar (lambda (x)
22592 (with-current-buffer
22593 ;; FIXME: Why not just (find-file-noselect x)?
22594 ;; Is it to avoid the "revert buffer" prompt?
22595 (or (get-file-buffer x) (find-file-noselect x))
22596 (widen)
22597 (current-buffer)))
22598 files)
22599 regexp)))
22601 (if (boundp 'occur-mode-find-occurrence-hook)
22602 ;; Emacs 23
22603 (add-hook 'occur-mode-find-occurrence-hook
22604 (lambda ()
22605 (when (derived-mode-p 'org-mode)
22606 (org-reveal))))
22607 ;; Emacs 22
22608 (defadvice occur-mode-goto-occurrence
22609 (after org-occur-reveal activate)
22610 (and (derived-mode-p 'org-mode) (org-reveal)))
22611 (defadvice occur-mode-goto-occurrence-other-window
22612 (after org-occur-reveal activate)
22613 (and (derived-mode-p 'org-mode) (org-reveal)))
22614 (defadvice occur-mode-display-occurrence
22615 (after org-occur-reveal activate)
22616 (when (derived-mode-p 'org-mode)
22617 (let ((pos (occur-mode-find-occurrence)))
22618 (with-current-buffer (marker-buffer pos)
22619 (save-excursion
22620 (goto-char pos)
22621 (org-reveal)))))))
22623 (defun org-occur-link-in-agenda-files ()
22624 "Create a link and search for it in the agendas.
22625 The link is not stored in `org-stored-links', it is just created
22626 for the search purpose."
22627 (interactive)
22628 (let ((link (condition-case nil
22629 (org-store-link nil)
22630 (error "Unable to create a link to here"))))
22631 (org-occur-in-agenda-files (regexp-quote link))))
22633 (defun org-reverse-string (string)
22634 "Return the reverse of STRING."
22635 (apply 'string (reverse (string-to-list string))))
22637 ;; defsubst org-uniquify must be defined before first use
22639 (defun org-uniquify-alist (alist)
22640 "Merge elements of ALIST with the same key.
22642 For example, in this alist:
22644 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22645 => \\='((a 1 3) (b 2))
22647 merge (a 1) and (a 3) into (a 1 3).
22649 The function returns the new ALIST."
22650 (let (rtn)
22651 (dolist (e alist rtn)
22652 (let (n)
22653 (if (not (assoc (car e) rtn))
22654 (push e rtn)
22655 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22656 (setq rtn (assq-delete-all (car e) rtn))
22657 (push n rtn))))))
22659 (defun org-delete-all (elts list)
22660 "Remove all elements in ELTS from LIST."
22661 (while elts
22662 (setq list (delete (pop elts) list)))
22663 list)
22665 (defun org-back-over-empty-lines ()
22666 "Move backwards over whitespace, to the beginning of the first empty line.
22667 Returns the number of empty lines passed."
22668 (let ((pos (point)))
22669 (if (cdr (assoc 'heading org-blank-before-new-entry))
22670 (skip-chars-backward " \t\n\r")
22671 (unless (eobp)
22672 (forward-line -1)))
22673 (beginning-of-line 2)
22674 (goto-char (min (point) pos))
22675 (count-lines (point) pos)))
22677 (defun org-skip-whitespace ()
22678 (skip-chars-forward " \t\n\r"))
22680 (defun org-point-in-group (point group &optional context)
22681 "Check if POINT is in match-group GROUP.
22682 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22683 match. If the match group does not exist or point is not inside it,
22684 return nil."
22685 (and (match-beginning group)
22686 (>= point (match-beginning group))
22687 (<= point (match-end group))
22688 (if context
22689 (list context (match-beginning group) (match-end group))
22690 t)))
22692 (defun org-switch-to-buffer-other-window (&rest args)
22693 "Switch to buffer in a second window on the current frame.
22694 In particular, do not allow pop-up frames.
22695 Returns the newly created buffer."
22696 (org-no-popups
22697 (apply 'switch-to-buffer-other-window args)))
22699 (defun org-combine-plists (&rest plists)
22700 "Create a single property list from all plists in PLISTS.
22701 The process starts by copying the first list, and then setting properties
22702 from the other lists. Settings in the last list are the most significant
22703 ones and overrule settings in the other lists."
22704 (let ((rtn (copy-sequence (pop plists)))
22705 p v ls)
22706 (while plists
22707 (setq ls (pop plists))
22708 (while ls
22709 (setq p (pop ls) v (pop ls))
22710 (setq rtn (plist-put rtn p v))))
22711 rtn))
22713 (defun org-replace-escapes (string table)
22714 "Replace %-escapes in STRING with values in TABLE.
22715 TABLE is an association list with keys like \"%a\" and string values.
22716 The sequences in STRING may contain normal field width and padding information,
22717 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22718 so values can contain further %-escapes if they are define later in TABLE."
22719 (let ((tbl (copy-alist table))
22720 (case-fold-search nil)
22721 (pchg 0)
22722 re rpl)
22723 (dolist (e tbl)
22724 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22725 (when (and (cdr e) (string-match re (cdr e)))
22726 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22727 (safe "SREF"))
22728 (add-text-properties 0 3 (list 'sref sref) safe)
22729 (setcdr e (replace-match safe t t (cdr e)))))
22730 (while (string-match re string)
22731 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22732 (cdr e)))
22733 (setq string (replace-match rpl t t string))))
22734 (while (setq pchg (next-property-change pchg string))
22735 (let ((sref (get-text-property pchg 'sref string)))
22736 (when (and sref (string-match "SREF" string pchg))
22737 (setq string (replace-match sref t t string)))))
22738 string))
22740 (defun org-sublist (list start end)
22741 "Return a section of LIST, from START to END.
22743 Counting starts at 1."
22744 (cl-subseq list (1- start) end))
22745 (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
22747 (defun org-find-base-buffer-visiting (file)
22748 "Like `find-buffer-visiting' but always return the base buffer and
22749 not an indirect buffer."
22750 (let ((buf (or (get-file-buffer file)
22751 (find-buffer-visiting file))))
22752 (if buf
22753 (or (buffer-base-buffer buf) buf)
22754 nil)))
22756 (define-obsolete-function-alias 'org-image-file-name-regexp 'image-file-name-regexp
22757 "Org 9.0")
22759 ;;; TODO: Only called once, from ox-odt which should probably use
22760 ;;; org-export-inline-image-p or something.
22761 (defun org-file-image-p (file)
22762 "Return non-nil if FILE is an image."
22763 (save-match-data
22764 (string-match (image-file-name-regexp) file)))
22766 (defun org-get-cursor-date (&optional with-time)
22767 "Return the date at cursor in as a time.
22768 This works in the calendar and in the agenda, anywhere else it just
22769 returns the current time.
22770 If WITH-TIME is non-nil, returns the time of the event at point (in
22771 the agenda) or the current time of the day."
22772 (let (date day defd tp hod mod)
22773 (when with-time
22774 (setq tp (get-text-property (point) 'time))
22775 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22776 (setq hod (string-to-number (match-string 1 tp))
22777 mod (string-to-number (match-string 2 tp))))
22778 (or tp (let ((now (decode-time)))
22779 (setq hod (nth 2 now)
22780 mod (nth 1 now)))))
22781 (cond
22782 ((eq major-mode 'calendar-mode)
22783 (setq date (calendar-cursor-to-date)
22784 defd (encode-time 0 (or mod 0) (or hod 0)
22785 (nth 1 date) (nth 0 date) (nth 2 date))))
22786 ((eq major-mode 'org-agenda-mode)
22787 (setq day (get-text-property (point) 'day))
22788 (when day
22789 (setq date (calendar-gregorian-from-absolute day)
22790 defd (encode-time 0 (or mod 0) (or hod 0)
22791 (nth 1 date) (nth 0 date) (nth 2 date))))))
22792 (or defd (current-time))))
22794 (defun org-mark-subtree (&optional up)
22795 "Mark the current subtree.
22796 This puts point at the start of the current subtree, and mark at
22797 the end. If a numeric prefix UP is given, move up into the
22798 hierarchy of headlines by UP levels before marking the subtree."
22799 (interactive "P")
22800 (org-with-limited-levels
22801 (cond ((org-at-heading-p) (beginning-of-line))
22802 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22803 (t (outline-previous-visible-heading 1))))
22804 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22805 (if (org-called-interactively-p 'any)
22806 (call-interactively 'org-mark-element)
22807 (org-mark-element)))
22810 ;;; Indentation
22812 (defun org--get-expected-indentation (element contentsp)
22813 "Expected indentation column for current line, according to ELEMENT.
22814 ELEMENT is an element containing point. CONTENTSP is non-nil
22815 when indentation is to be computed according to contents of
22816 ELEMENT."
22817 (let ((type (org-element-type element))
22818 (start (org-element-property :begin element))
22819 (post-affiliated (org-element-property :post-affiliated element)))
22820 (org-with-wide-buffer
22821 (cond
22822 (contentsp
22823 (cl-case type
22824 ((diary-sexp footnote-definition) 0)
22825 ((headline inlinetask nil)
22826 (if (not org-adapt-indentation) 0
22827 (let ((level (org-current-level)))
22828 (if level (1+ level) 0))))
22829 ((item plain-list) (org-list-item-body-column post-affiliated))
22831 (goto-char start)
22832 (org-get-indentation))))
22833 ((memq type '(headline inlinetask nil))
22834 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22835 (org--get-expected-indentation element t)
22837 ((memq type '(diary-sexp footnote-definition)) 0)
22838 ;; First paragraph of a footnote definition or an item.
22839 ;; Indent like parent.
22840 ((< (line-beginning-position) start)
22841 (org--get-expected-indentation
22842 (org-element-property :parent element) t))
22843 ;; At first line: indent according to previous sibling, if any,
22844 ;; ignoring footnote definitions and inline tasks, or parent's
22845 ;; contents.
22846 ((= (line-beginning-position) start)
22847 (catch 'exit
22848 (while t
22849 (if (= (point-min) start) (throw 'exit 0)
22850 (goto-char (1- start))
22851 (let* ((previous (org-element-at-point))
22852 (parent previous))
22853 (while (and parent (<= (org-element-property :end parent) start))
22854 (setq previous parent
22855 parent (org-element-property :parent parent)))
22856 (cond
22857 ((not previous) (throw 'exit 0))
22858 ((> (org-element-property :end previous) start)
22859 (throw 'exit (org--get-expected-indentation previous t)))
22860 ((memq (org-element-type previous)
22861 '(footnote-definition inlinetask))
22862 (setq start (org-element-property :begin previous)))
22863 (t (goto-char (org-element-property :begin previous))
22864 (throw 'exit
22865 (if (bolp) (org-get-indentation)
22866 ;; At first paragraph in an item or
22867 ;; a footnote definition.
22868 (org--get-expected-indentation
22869 (org-element-property :parent previous) t))))))))))
22870 ;; Otherwise, move to the first non-blank line above.
22872 (beginning-of-line)
22873 (let ((pos (point)))
22874 (skip-chars-backward " \r\t\n")
22875 (cond
22876 ;; Two blank lines end a footnote definition or a plain
22877 ;; list. When we indent an empty line after them, the
22878 ;; containing list or footnote definition is over, so it
22879 ;; qualifies as a previous sibling. Therefore, we indent
22880 ;; like its first line.
22881 ((and (memq type '(footnote-definition plain-list))
22882 (> (count-lines (point) pos) 2))
22883 (goto-char start)
22884 (org-get-indentation))
22885 ;; Line above is the first one of a paragraph at the
22886 ;; beginning of an item or a footnote definition. Indent
22887 ;; like parent.
22888 ((< (line-beginning-position) start)
22889 (org--get-expected-indentation
22890 (org-element-property :parent element) t))
22891 ;; Line above is the beginning of an element, i.e., point
22892 ;; was originally on the blank lines between element's start
22893 ;; and contents.
22894 ((= (line-beginning-position) post-affiliated)
22895 (org--get-expected-indentation element t))
22896 ;; POS is after contents in a greater element. Indent like
22897 ;; the beginning of the element.
22899 ;; As a special case, if point is at the end of a footnote
22900 ;; definition or an item, indent like the very last element
22901 ;; within.
22902 ((and (not (eq type 'paragraph))
22903 (let ((cend (org-element-property :contents-end element)))
22904 (and cend (<= cend pos))))
22905 (if (memq type '(footnote-definition item plain-list))
22906 (let ((last (org-element-at-point)))
22907 (org--get-expected-indentation
22908 last
22909 (memq (org-element-type last)
22910 '(footnote-definition item plain-list))))
22911 (goto-char start)
22912 (org-get-indentation)))
22913 ;; In any other case, indent like the current line.
22914 (t (org-get-indentation)))))))))
22916 (defun org--align-node-property ()
22917 "Align node property at point.
22918 Alignment is done according to `org-property-format', which see."
22919 (when (save-excursion
22920 (beginning-of-line)
22921 (looking-at org-property-re))
22922 (replace-match
22923 (concat (match-string 4)
22924 (org-trim
22925 (format org-property-format (match-string 1) (match-string 3))))
22926 t t)))
22928 (defun org-indent-line ()
22929 "Indent line depending on context.
22931 Indentation is done according to the following rules:
22933 - Footnote definitions, diary sexps, headlines and inline tasks
22934 have to start at column 0.
22936 - On the very first line of an element, consider, in order, the
22937 next rules until one matches:
22939 1. If there's a sibling element before, ignoring footnote
22940 definitions and inline tasks, indent like its first line.
22942 2. If element has a parent, indent like its contents. More
22943 precisely, if parent is an item, indent after the
22944 description part, if any, or the bullet (see
22945 `org-list-description-max-indent'). Else, indent like
22946 parent's first line.
22948 3. Otherwise, indent relatively to current level, if
22949 `org-adapt-indentation' is non-nil, or to left margin.
22951 - On a blank line at the end of an element, indent according to
22952 the type of the element. More precisely
22954 1. If element is a plain list, an item, or a footnote
22955 definition, indent like the very last element within.
22957 2. If element is a paragraph, indent like its last non blank
22958 line.
22960 3. Otherwise, indent like its very first line.
22962 - In the code part of a source block, use language major mode
22963 to indent current line if `org-src-tab-acts-natively' is
22964 non-nil. If it is nil, do nothing.
22966 - Otherwise, indent like the first non-blank line above.
22968 The function doesn't indent an item as it could break the whole
22969 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22970 \\[org-shiftmetaright].
22972 Also align node properties according to `org-property-format'."
22973 (interactive)
22974 (cond
22975 (orgstruct-is-++
22976 (let ((indent-line-function
22977 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22978 (indent-according-to-mode)))
22979 ((org-at-heading-p) 'noindent)
22981 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22982 (type (org-element-type element)))
22983 (cond ((and (memq type '(plain-list item))
22984 (= (line-beginning-position)
22985 (org-element-property :post-affiliated element)))
22986 'noindent)
22987 ((and (eq type 'src-block)
22988 org-src-tab-acts-natively
22989 (> (line-beginning-position)
22990 (org-element-property :post-affiliated element))
22991 (< (line-beginning-position)
22992 (org-with-wide-buffer
22993 (goto-char (org-element-property :end element))
22994 (skip-chars-backward " \r\t\n")
22995 (line-beginning-position))))
22996 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22998 (let ((column (org--get-expected-indentation element nil)))
22999 ;; Preserve current column.
23000 (if (<= (current-column) (current-indentation))
23001 (org-indent-line-to column)
23002 (save-excursion (org-indent-line-to column))))
23003 ;; Align node property. Also preserve current column.
23004 (when (eq type 'node-property)
23005 (let ((column (current-column)))
23006 (org--align-node-property)
23007 (org-move-to-column column)))))))))
23009 (defun org-indent-region (start end)
23010 "Indent each non-blank line in the region.
23011 Called from a program, START and END specify the region to
23012 indent. The function will not indent contents of example blocks,
23013 verse blocks and export blocks as leading white spaces are
23014 assumed to be significant there."
23015 (interactive "r")
23016 (save-excursion
23017 (goto-char start)
23018 (skip-chars-forward " \r\t\n")
23019 (unless (eobp) (beginning-of-line))
23020 (let ((indent-to
23021 (lambda (ind pos)
23022 ;; Set IND as indentation for all lines between point and
23023 ;; POS. Blank lines are ignored. Leave point after POS
23024 ;; once done.
23025 (let ((limit (copy-marker pos)))
23026 (while (< (point) limit)
23027 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
23028 (forward-line))
23029 (set-marker limit nil))))
23030 (end (copy-marker end)))
23031 (while (< (point) end)
23032 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23033 (let* ((element (org-element-at-point))
23034 (type (org-element-type element))
23035 (element-end (copy-marker (org-element-property :end element)))
23036 (ind (org--get-expected-indentation element nil)))
23037 (cond
23038 ((or (memq type '(paragraph table table-row))
23039 (not (or (org-element-property :contents-begin element)
23040 (memq type
23041 '(example-block export-block src-block)))))
23042 ;; Elements here are indented as a single block. Also
23043 ;; align node properties.
23044 (when (eq type 'node-property)
23045 (org--align-node-property)
23046 (beginning-of-line))
23047 (funcall indent-to ind (min element-end end)))
23049 ;; Elements in this category consist of three parts:
23050 ;; before the contents, the contents, and after the
23051 ;; contents. The contents are treated specially,
23052 ;; according to the element type, or not indented at
23053 ;; all. Other parts are indented as a single block.
23054 (let* ((post (copy-marker
23055 (org-element-property :post-affiliated element)))
23056 (cbeg
23057 (copy-marker
23058 (cond
23059 ((not (org-element-property :contents-begin element))
23060 ;; Fake contents for source blocks.
23061 (org-with-wide-buffer
23062 (goto-char post)
23063 (forward-line)
23064 (point)))
23065 ((memq type '(footnote-definition item plain-list))
23066 ;; Contents in these elements could start on
23067 ;; the same line as the beginning of the
23068 ;; element. Make sure we start indenting
23069 ;; from the second line.
23070 (org-with-wide-buffer
23071 (goto-char post)
23072 (end-of-line)
23073 (skip-chars-forward " \r\t\n")
23074 (if (eobp) (point) (line-beginning-position))))
23075 (t (org-element-property :contents-begin element)))))
23076 (cend (copy-marker
23077 (or (org-element-property :contents-end element)
23078 ;; Fake contents for source blocks.
23079 (org-with-wide-buffer
23080 (goto-char element-end)
23081 (skip-chars-backward " \r\t\n")
23082 (line-beginning-position)))
23083 t)))
23084 ;; Do not change items indentation individually as it
23085 ;; might break the list as a whole. On the other
23086 ;; hand, when at a plain list, indent it as a whole.
23087 (cond ((eq type 'plain-list)
23088 (let ((offset (- ind (org-get-indentation))))
23089 (unless (zerop offset)
23090 (indent-rigidly (org-element-property :begin element)
23091 (org-element-property :end element)
23092 offset))
23093 (goto-char cbeg)))
23094 ((eq type 'item) (goto-char cbeg))
23095 (t (funcall indent-to ind (min cbeg end))))
23096 (when (< (point) end)
23097 (cl-case type
23098 ((example-block export-block verse-block))
23099 (src-block
23100 ;; In a source block, indent source code
23101 ;; according to language major mode, but only if
23102 ;; `org-src-tab-acts-natively' is non-nil.
23103 (when (and (< (point) end) org-src-tab-acts-natively)
23104 (ignore-errors
23105 (org-babel-do-in-edit-buffer
23106 (indent-region (point-min) (point-max))))))
23107 (t (org-indent-region (point) (min cend end))))
23108 (goto-char (min cend end))
23109 (when (< (point) end)
23110 (funcall indent-to ind (min element-end end))))
23111 (set-marker post nil)
23112 (set-marker cbeg nil)
23113 (set-marker cend nil))))
23114 (set-marker element-end nil))))
23115 (set-marker end nil))))
23117 (defun org-indent-drawer ()
23118 "Indent the drawer at point."
23119 (interactive)
23120 (unless (save-excursion
23121 (beginning-of-line)
23122 (org-looking-at-p org-drawer-regexp))
23123 (user-error "Not at a drawer"))
23124 (let ((element (org-element-at-point)))
23125 (unless (memq (org-element-type element) '(drawer property-drawer))
23126 (user-error "Not at a drawer"))
23127 (org-with-wide-buffer
23128 (org-indent-region (org-element-property :begin element)
23129 (org-element-property :end element))))
23130 (message "Drawer at point indented"))
23132 (defun org-indent-block ()
23133 "Indent the block at point."
23134 (interactive)
23135 (unless (save-excursion
23136 (beginning-of-line)
23137 (let ((case-fold-search t))
23138 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23139 (user-error "Not at a block"))
23140 (let ((element (org-element-at-point)))
23141 (unless (memq (org-element-type element)
23142 '(comment-block center-block dynamic-block example-block
23143 export-block quote-block special-block
23144 src-block verse-block))
23145 (user-error "Not at a block"))
23146 (org-with-wide-buffer
23147 (org-indent-region (org-element-property :begin element)
23148 (org-element-property :end element))))
23149 (message "Block at point indented"))
23152 ;;; Filling
23154 ;; We use our own fill-paragraph and auto-fill functions.
23156 ;; `org-fill-paragraph' relies on adaptive filling and context
23157 ;; checking. Appropriate `fill-prefix' is computed with
23158 ;; `org-adaptive-fill-function'.
23160 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23161 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23162 ;; `org-adaptive-fill-function' value. Internally,
23163 ;; `org-comment-line-break-function' breaks the line.
23165 ;; `org-setup-filling' installs filling and auto-filling related
23166 ;; variables during `org-mode' initialization.
23168 (defvar org-element-paragraph-separate) ; org-element.el
23169 (defun org-setup-filling ()
23170 (require 'org-element)
23171 ;; Prevent auto-fill from inserting unwanted new items.
23172 (when (boundp 'fill-nobreak-predicate)
23173 (setq-local
23174 fill-nobreak-predicate
23175 (org-uniquify
23176 (append fill-nobreak-predicate
23177 '(org-fill-line-break-nobreak-p
23178 org-fill-paragraph-with-timestamp-nobreak-p)))))
23179 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23180 (setq-local paragraph-start paragraph-ending)
23181 (setq-local paragraph-separate paragraph-ending))
23182 (setq-local fill-paragraph-function 'org-fill-paragraph)
23183 (setq-local auto-fill-inhibit-regexp nil)
23184 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23185 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23186 (setq-local comment-line-break-function 'org-comment-line-break-function))
23188 (defun org-fill-line-break-nobreak-p ()
23189 "Non-nil when a new line at point would create an Org line break."
23190 (save-excursion
23191 (skip-chars-backward "[ \t]")
23192 (skip-chars-backward "\\\\")
23193 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23195 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23196 "Non-nil when a new line at point would split a timestamp."
23197 (and (org-at-timestamp-p t)
23198 (not (looking-at org-ts-regexp-both))))
23200 (declare-function message-in-body-p "message" ())
23201 (defvar orgtbl-line-start-regexp) ; From org-table.el
23202 (defun org-adaptive-fill-function ()
23203 "Compute a fill prefix for the current line.
23204 Return fill prefix, as a string, or nil if current line isn't
23205 meant to be filled. For convenience, if `adaptive-fill-regexp'
23206 matches in paragraphs or comments, use it."
23207 (catch 'exit
23208 (when (derived-mode-p 'message-mode)
23209 (save-excursion
23210 (beginning-of-line)
23211 (cond ((not (message-in-body-p)) (throw 'exit nil))
23212 ((org-looking-at-p org-table-line-regexp) (throw 'exit nil))
23213 ((looking-at message-cite-prefix-regexp)
23214 (throw 'exit (match-string-no-properties 0)))
23215 ((looking-at org-outline-regexp)
23216 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23217 (org-with-wide-buffer
23218 (unless (org-at-heading-p)
23219 (let* ((p (line-beginning-position))
23220 (element (save-excursion
23221 (beginning-of-line)
23222 (org-element-at-point)))
23223 (type (org-element-type element))
23224 (post-affiliated (org-element-property :post-affiliated element)))
23225 (unless (< p post-affiliated)
23226 (cl-case type
23227 (comment
23228 (save-excursion
23229 (beginning-of-line)
23230 (looking-at "[ \t]*")
23231 (concat (match-string 0) "# ")))
23232 (footnote-definition "")
23233 ((item plain-list)
23234 (make-string (org-list-item-body-column post-affiliated) ?\s))
23235 (paragraph
23236 ;; Fill prefix is usually the same as the current line,
23237 ;; unless the paragraph is at the beginning of an item.
23238 (let ((parent (org-element-property :parent element)))
23239 (save-excursion
23240 (beginning-of-line)
23241 (cond ((eq (org-element-type parent) 'item)
23242 (make-string (org-list-item-body-column
23243 (org-element-property :begin parent))
23244 ?\s))
23245 ((and adaptive-fill-regexp
23246 ;; Locally disable
23247 ;; `adaptive-fill-function' to let
23248 ;; `fill-context-prefix' handle
23249 ;; `adaptive-fill-regexp' variable.
23250 (let (adaptive-fill-function)
23251 (fill-context-prefix
23252 post-affiliated
23253 (org-element-property :end element)))))
23254 ((looking-at "[ \t]+") (match-string 0))
23255 (t "")))))
23256 (comment-block
23257 ;; Only fill contents if P is within block boundaries.
23258 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23259 (forward-line)
23260 (point)))
23261 (cend (save-excursion
23262 (goto-char (org-element-property :end element))
23263 (skip-chars-backward " \r\t\n")
23264 (line-beginning-position))))
23265 (when (and (>= p cbeg) (< p cend))
23266 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23267 (match-string 0)
23268 "")))))))))))
23270 (declare-function message-goto-body "message" ())
23271 (defvar message-cite-prefix-regexp) ; From message.el
23272 (defun org-fill-paragraph (&optional justify)
23273 "Fill element at point, when applicable.
23275 This function only applies to comment blocks, comments, example
23276 blocks and paragraphs. Also, as a special case, re-align table
23277 when point is at one.
23279 If JUSTIFY is non-nil (interactively, with prefix argument),
23280 justify as well. If `sentence-end-double-space' is non-nil, then
23281 period followed by one space does not end a sentence, so don't
23282 break a line there. The variable `fill-column' controls the
23283 width for filling.
23285 For convenience, when point is at a plain list, an item or
23286 a footnote definition, try to fill the first paragraph within."
23287 (interactive)
23288 (if (and (derived-mode-p 'message-mode)
23289 (or (not (message-in-body-p))
23290 (save-excursion (move-beginning-of-line 1)
23291 (looking-at message-cite-prefix-regexp))))
23292 ;; First ensure filling is correct in message-mode.
23293 (let ((fill-paragraph-function
23294 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23295 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23296 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23297 (paragraph-separate
23298 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23299 (fill-paragraph nil))
23300 (with-syntax-table org-mode-transpose-word-syntax-table
23301 ;; Move to end of line in order to get the first paragraph
23302 ;; within a plain list or a footnote definition.
23303 (let ((element (save-excursion
23304 (end-of-line)
23305 (or (ignore-errors (org-element-at-point))
23306 (user-error "An element cannot be parsed line %d"
23307 (line-number-at-pos (point)))))))
23308 ;; First check if point is in a blank line at the beginning of
23309 ;; the buffer. In that case, ignore filling.
23310 (cl-case (org-element-type element)
23311 ;; Use major mode filling function is src blocks.
23312 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23313 ;; Align Org tables, leave table.el tables as-is.
23314 (table-row (org-table-align) t)
23315 (table
23316 (when (eq (org-element-property :type element) 'org)
23317 (save-excursion
23318 (goto-char (org-element-property :post-affiliated element))
23319 (org-table-align)))
23321 (paragraph
23322 ;; Paragraphs may contain `line-break' type objects.
23323 (let ((beg (max (point-min)
23324 (org-element-property :contents-begin element)))
23325 (end (min (point-max)
23326 (org-element-property :contents-end element))))
23327 ;; Do nothing if point is at an affiliated keyword.
23328 (if (< (line-end-position) beg) t
23329 (when (derived-mode-p 'message-mode)
23330 ;; In `message-mode', do not fill following citation
23331 ;; in current paragraph nor text before message body.
23332 (let ((body-start (save-excursion (message-goto-body))))
23333 (when body-start (setq beg (max body-start beg))))
23334 (when (save-excursion
23335 (re-search-forward
23336 (concat "^" message-cite-prefix-regexp) end t))
23337 (setq end (match-beginning 0))))
23338 ;; Fill paragraph, taking line breaks into account.
23339 (save-excursion
23340 (goto-char beg)
23341 (let ((cuts (list beg)))
23342 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23343 (when (eq 'line-break
23344 (org-element-type
23345 (save-excursion (backward-char)
23346 (org-element-context))))
23347 (push (point) cuts)))
23348 (dolist (c (delq end cuts))
23349 (fill-region-as-paragraph c end justify)
23350 (setq end c))))
23351 t)))
23352 ;; Contents of `comment-block' type elements should be
23353 ;; filled as plain text, but only if point is within block
23354 ;; markers.
23355 (comment-block
23356 (let* ((case-fold-search t)
23357 (beg (save-excursion
23358 (goto-char (org-element-property :begin element))
23359 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23360 (forward-line)
23361 (point)))
23362 (end (save-excursion
23363 (goto-char (org-element-property :end element))
23364 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23365 (line-beginning-position))))
23366 (if (or (< (point) beg) (> (point) end)) t
23367 (fill-region-as-paragraph
23368 (save-excursion (end-of-line)
23369 (re-search-backward "^[ \t]*$" beg 'move)
23370 (line-beginning-position))
23371 (save-excursion (beginning-of-line)
23372 (re-search-forward "^[ \t]*$" end 'move)
23373 (line-beginning-position))
23374 justify))))
23375 ;; Fill comments.
23376 (comment
23377 (let ((begin (org-element-property :post-affiliated element))
23378 (end (org-element-property :end element)))
23379 (when (and (>= (point) begin) (<= (point) end))
23380 (let ((begin (save-excursion
23381 (end-of-line)
23382 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23383 (progn (forward-line) (point))
23384 begin)))
23385 (end (save-excursion
23386 (end-of-line)
23387 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23388 (1- (line-beginning-position))
23389 (skip-chars-backward " \r\t\n")
23390 (line-end-position)))))
23391 ;; Do not fill comments when at a blank line.
23392 (when (> end begin)
23393 (let ((fill-prefix
23394 (save-excursion
23395 (beginning-of-line)
23396 (looking-at "[ \t]*#")
23397 (let ((comment-prefix (match-string 0)))
23398 (goto-char (match-end 0))
23399 (if (looking-at adaptive-fill-regexp)
23400 (concat comment-prefix (match-string 0))
23401 (concat comment-prefix " "))))))
23402 (save-excursion
23403 (fill-region-as-paragraph begin end justify))))))
23405 ;; Ignore every other element.
23406 (otherwise t))))))
23408 (defun org-auto-fill-function ()
23409 "Auto-fill function."
23410 ;; Check if auto-filling is meaningful.
23411 (let ((fc (current-fill-column)))
23412 (when (and fc (> (current-column) fc))
23413 (let* ((fill-prefix (org-adaptive-fill-function))
23414 ;; Enforce empty fill prefix, if required. Otherwise, it
23415 ;; will be computed again.
23416 (adaptive-fill-mode (not (equal fill-prefix ""))))
23417 (when fill-prefix (do-auto-fill))))))
23419 (defun org-comment-line-break-function (&optional soft)
23420 "Break line at point and indent, continuing comment if within one.
23421 The inserted newline is marked hard if variable
23422 `use-hard-newlines' is true, unless optional argument SOFT is
23423 non-nil."
23424 (if soft (insert-and-inherit ?\n) (newline 1))
23425 (save-excursion (forward-char -1) (delete-horizontal-space))
23426 (delete-horizontal-space)
23427 (indent-to-left-margin)
23428 (insert-before-markers-and-inherit fill-prefix))
23431 ;;; Fixed Width Areas
23433 (defun org-toggle-fixed-width ()
23434 "Toggle fixed-width markup.
23436 Add or remove fixed-width markup on current line, whenever it
23437 makes sense. Return an error otherwise.
23439 If a region is active and if it contains only fixed-width areas
23440 or blank lines, remove all fixed-width markup in it. If the
23441 region contains anything else, convert all non-fixed-width lines
23442 to fixed-width ones.
23444 Blank lines at the end of the region are ignored unless the
23445 region only contains such lines."
23446 (interactive)
23447 (if (not (org-region-active-p))
23448 ;; No region:
23450 ;; Remove fixed width marker only in a fixed-with element.
23452 ;; Add fixed width maker in paragraphs, in blank lines after
23453 ;; elements or at the beginning of a headline or an inlinetask,
23454 ;; and before any one-line elements (e.g., a clock).
23455 (progn
23456 (beginning-of-line)
23457 (let* ((element (org-element-at-point))
23458 (type (org-element-type element)))
23459 (cond
23460 ((and (eq type 'fixed-width)
23461 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23462 (replace-match
23463 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23464 ((and (memq type '(babel-call clock comment diary-sexp headline
23465 horizontal-rule keyword paragraph
23466 planning))
23467 (<= (org-element-property :post-affiliated element) (point)))
23468 (skip-chars-forward " \t")
23469 (insert ": "))
23470 ((and (org-looking-at-p "[ \t]*$")
23471 (or (eq type 'inlinetask)
23472 (save-excursion
23473 (skip-chars-forward " \r\t\n")
23474 (<= (org-element-property :end element) (point)))))
23475 (delete-region (point) (line-end-position))
23476 (org-indent-line)
23477 (insert ": "))
23478 (t (user-error "Cannot insert a fixed-width line here")))))
23479 ;; Region active.
23480 (let* ((begin (save-excursion
23481 (goto-char (region-beginning))
23482 (line-beginning-position)))
23483 (end (copy-marker
23484 (save-excursion
23485 (goto-char (region-end))
23486 (unless (eolp) (beginning-of-line))
23487 (if (save-excursion (re-search-backward "\\S-" begin t))
23488 (progn (skip-chars-backward " \r\t\n") (point))
23489 (point)))))
23490 (all-fixed-width-p
23491 (catch 'not-all-p
23492 (save-excursion
23493 (goto-char begin)
23494 (skip-chars-forward " \r\t\n")
23495 (when (eobp) (throw 'not-all-p nil))
23496 (while (< (point) end)
23497 (let ((element (org-element-at-point)))
23498 (if (eq (org-element-type element) 'fixed-width)
23499 (goto-char (org-element-property :end element))
23500 (throw 'not-all-p nil))))
23501 t))))
23502 (if all-fixed-width-p
23503 (save-excursion
23504 (goto-char begin)
23505 (while (< (point) end)
23506 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23507 (replace-match
23508 "" nil nil nil
23509 (if (= (line-end-position) (match-end 0)) 0 1)))
23510 (forward-line)))
23511 (let ((min-ind (point-max)))
23512 ;; Find minimum indentation across all lines.
23513 (save-excursion
23514 (goto-char begin)
23515 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23516 (setq min-ind 0)
23517 (catch 'zerop
23518 (while (< (point) end)
23519 (unless (org-looking-at-p "[ \t]*$")
23520 (let ((ind (org-get-indentation)))
23521 (setq min-ind (min min-ind ind))
23522 (when (zerop ind) (throw 'zerop t))))
23523 (forward-line)))))
23524 ;; Loop over all lines and add fixed-width markup everywhere
23525 ;; but in fixed-width lines.
23526 (save-excursion
23527 (goto-char begin)
23528 (while (< (point) end)
23529 (cond
23530 ((org-at-heading-p)
23531 (insert ": ")
23532 (forward-line)
23533 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23534 (insert ":")
23535 (forward-line)))
23536 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23537 (let* ((element (org-element-at-point))
23538 (element-end (org-element-property :end element)))
23539 (if (eq (org-element-type element) 'fixed-width)
23540 (progn (goto-char element-end)
23541 (skip-chars-backward " \r\t\n")
23542 (forward-line))
23543 (let ((limit (min end element-end)))
23544 (while (< (point) limit)
23545 (org-move-to-column min-ind t)
23546 (insert ": ")
23547 (forward-line))))))
23549 (org-move-to-column min-ind t)
23550 (insert ": ")
23551 (forward-line)))))))
23552 (set-marker end nil))))
23555 ;;; Comments
23557 ;; Org comments syntax is quite complex. It requires the entire line
23558 ;; to be just a comment. Also, even with the right syntax at the
23559 ;; beginning of line, some some elements (i.e. verse-block or
23560 ;; example-block) don't accept comments. Usual Emacs comment commands
23561 ;; cannot cope with those requirements. Therefore, Org replaces them.
23563 ;; Org still relies on `comment-dwim', but cannot trust
23564 ;; `comment-only-p'. So, `comment-region-function' and
23565 ;; `uncomment-region-function' both point
23566 ;; to`org-comment-or-uncomment-region'. Eventually,
23567 ;; `org-insert-comment' takes care of insertion of comments at the
23568 ;; beginning of line.
23570 ;; `org-setup-comments-handling' install comments related variables
23571 ;; during `org-mode' initialization.
23573 (defun org-setup-comments-handling ()
23574 (interactive)
23575 (setq-local comment-use-syntax nil)
23576 (setq-local comment-start "# ")
23577 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23578 (setq-local comment-insert-comment-function 'org-insert-comment)
23579 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23580 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23582 (defun org-insert-comment ()
23583 "Insert an empty comment above current line.
23584 If the line is empty, insert comment at its beginning. When
23585 point is within a source block, comment according to the related
23586 major mode."
23587 (if (let ((element (org-element-at-point)))
23588 (and (eq (org-element-type element) 'src-block)
23589 (< (save-excursion
23590 (goto-char (org-element-property :post-affiliated element))
23591 (line-end-position))
23592 (point))
23593 (> (save-excursion
23594 (goto-char (org-element-property :end element))
23595 (skip-chars-backward " \r\t\n")
23596 (line-beginning-position))
23597 (point))))
23598 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23599 (beginning-of-line)
23600 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23601 (open-line 1))
23602 (org-indent-line)
23603 (insert "# ")))
23605 (defvar comment-empty-lines) ; From newcomment.el.
23606 (defun org-comment-or-uncomment-region (beg end &rest _)
23607 "Comment or uncomment each non-blank line in the region.
23608 Uncomment each non-blank line between BEG and END if it only
23609 contains commented lines. Otherwise, comment them. If region is
23610 strictly within a source block, use appropriate comment syntax."
23611 (if (let ((element (org-element-at-point)))
23612 (and (eq (org-element-type element) 'src-block)
23613 (< (save-excursion
23614 (goto-char (org-element-property :post-affiliated element))
23615 (line-end-position))
23616 beg)
23617 (>= (save-excursion
23618 (goto-char (org-element-property :end element))
23619 (skip-chars-backward " \r\t\n")
23620 (line-beginning-position))
23621 end)))
23622 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23623 (save-restriction
23624 ;; Restrict region
23625 (narrow-to-region (save-excursion (goto-char beg)
23626 (skip-chars-forward " \r\t\n" end)
23627 (line-beginning-position))
23628 (save-excursion (goto-char end)
23629 (skip-chars-backward " \r\t\n" beg)
23630 (line-end-position)))
23631 (let ((uncommentp
23632 ;; UNCOMMENTP is non-nil when every non blank line between
23633 ;; BEG and END is a comment.
23634 (save-excursion
23635 (goto-char (point-min))
23636 (while (and (not (eobp))
23637 (let ((element (org-element-at-point)))
23638 (and (eq (org-element-type element) 'comment)
23639 (goto-char (min (point-max)
23640 (org-element-property
23641 :end element)))))))
23642 (eobp))))
23643 (if uncommentp
23644 ;; Only blank lines and comments in region: uncomment it.
23645 (save-excursion
23646 (goto-char (point-min))
23647 (while (not (eobp))
23648 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23649 (replace-match "" nil nil nil 1))
23650 (forward-line)))
23651 ;; Comment each line in region.
23652 (let ((min-indent (point-max)))
23653 ;; First find the minimum indentation across all lines.
23654 (save-excursion
23655 (goto-char (point-min))
23656 (while (and (not (eobp)) (not (zerop min-indent)))
23657 (unless (looking-at "[ \t]*$")
23658 (setq min-indent (min min-indent (current-indentation))))
23659 (forward-line)))
23660 ;; Then loop over all lines.
23661 (save-excursion
23662 (goto-char (point-min))
23663 (while (not (eobp))
23664 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23665 ;; Don't get fooled by invisible text (e.g. link path)
23666 ;; when moving to column MIN-INDENT.
23667 (let ((buffer-invisibility-spec nil))
23668 (org-move-to-column min-indent t))
23669 (insert comment-start))
23670 (forward-line)))))))))
23672 (defun org-comment-dwim (_arg)
23673 "Call `comment-dwim' within a source edit buffer if needed."
23674 (interactive "*P")
23675 (if (org-in-src-block-p)
23676 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23677 (call-interactively 'comment-dwim)))
23680 ;;; Timestamps API
23682 ;; This section contains tools to operate on timestamp objects, as
23683 ;; returned by, e.g. `org-element-context'.
23685 (defun org-timestamp--to-internal-time (timestamp &optional end)
23686 "Encode TIMESTAMP object into Emacs internal time.
23687 Use end of date range or time range when END is non-nil."
23688 (apply #'encode-time
23689 (cons 0
23690 (mapcar
23691 (lambda (prop) (or (org-element-property prop timestamp) 0))
23692 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23693 '(:minute-start :hour-start :day-start :month-start
23694 :year-start))))))
23696 (defun org-timestamp-has-time-p (timestamp)
23697 "Non-nil when TIMESTAMP has a time specified."
23698 (org-element-property :hour-start timestamp))
23700 (defun org-timestamp-format (timestamp format &optional end utc)
23701 "Format a TIMESTAMP object into a string.
23703 FORMAT is a format specifier to be passed to
23704 `format-time-string'.
23706 When optional argument END is non-nil, use end of date-range or
23707 time-range, if possible.
23709 When optional argument UTC is non-nil, time will be expressed as
23710 Universal Time."
23711 (format-time-string
23712 format (org-timestamp--to-internal-time timestamp end) utc))
23714 (defun org-timestamp-split-range (timestamp &optional end)
23715 "Extract a TIMESTAMP object from a date or time range.
23717 END, when non-nil, means extract the end of the range.
23718 Otherwise, extract its start.
23720 Return a new timestamp object."
23721 (let ((type (org-element-property :type timestamp)))
23722 (if (memq type '(active inactive diary)) timestamp
23723 (let ((split-ts (org-element-copy timestamp)))
23724 ;; Set new type.
23725 (org-element-put-property
23726 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23727 ;; Copy start properties over end properties if END is
23728 ;; non-nil. Otherwise, copy end properties over `start' ones.
23729 (let ((p-alist '((:minute-start . :minute-end)
23730 (:hour-start . :hour-end)
23731 (:day-start . :day-end)
23732 (:month-start . :month-end)
23733 (:year-start . :year-end))))
23734 (dolist (p-cell p-alist)
23735 (org-element-put-property
23736 split-ts
23737 (funcall (if end #'car #'cdr) p-cell)
23738 (org-element-property
23739 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23740 ;; Eventually refresh `:raw-value'.
23741 (org-element-put-property split-ts :raw-value nil)
23742 (org-element-put-property
23743 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23745 (defun org-timestamp-translate (timestamp &optional boundary)
23746 "Translate TIMESTAMP object to custom format.
23748 Format string is defined in `org-time-stamp-custom-formats',
23749 which see.
23751 When optional argument BOUNDARY is non-nil, it is either the
23752 symbol `start' or `end'. In this case, only translate the
23753 starting or ending part of TIMESTAMP if it is a date or time
23754 range. Otherwise, translate both parts.
23756 Return timestamp as-is if `org-display-custom-times' is nil or if
23757 it has a `diary' type."
23758 (let ((type (org-element-property :type timestamp)))
23759 (if (or (not org-display-custom-times) (eq type 'diary))
23760 (org-element-interpret-data timestamp)
23761 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23762 org-time-stamp-custom-formats)))
23763 (if (and (not boundary) (memq type '(active-range inactive-range)))
23764 (concat (org-timestamp-format timestamp fmt)
23765 "--"
23766 (org-timestamp-format timestamp fmt t))
23767 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23771 ;;; Other stuff.
23773 (defvar reftex-docstruct-symbol)
23774 (defvar reftex-cite-format)
23775 (defvar org--rds)
23777 (defun org-reftex-citation ()
23778 "Use reftex-citation to insert a citation into the buffer.
23779 This looks for a line like
23781 #+BIBLIOGRAPHY: foo plain option:-d
23783 and derives from it that foo.bib is the bibliography file relevant
23784 for this document. It then installs the necessary environment for RefTeX
23785 to work in this buffer and calls `reftex-citation' to insert a citation
23786 into the buffer.
23788 Export of such citations to both LaTeX and HTML is handled by the contributed
23789 package ox-bibtex by Taru Karttunen."
23790 (interactive)
23791 (let ((reftex-docstruct-symbol 'org--rds)
23792 (reftex-cite-format "\\cite{%l}")
23793 org--rds bib)
23794 (save-excursion
23795 (save-restriction
23796 (widen)
23797 (let ((case-fold-search t)
23798 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23799 (if (not (save-excursion
23800 (or (re-search-forward re nil t)
23801 (re-search-backward re nil t))))
23802 (user-error "No bibliography defined in file")
23803 (setq bib (concat (match-string 1) ".bib")
23804 org--rds (list (list 'bib bib)))))))
23805 (call-interactively 'reftex-citation)))
23807 ;;;; Functions extending outline functionality
23809 (defun org-beginning-of-line (&optional arg)
23810 "Go to the beginning of the current line. If that is invisible, continue
23811 to a visible line beginning. This makes the function of C-a more intuitive.
23812 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23813 first attempt, and only move to after the tags when the cursor is already
23814 beyond the end of the headline."
23815 (interactive "P")
23816 (let ((pos (point))
23817 (special (if (consp org-special-ctrl-a/e)
23818 (car org-special-ctrl-a/e)
23819 org-special-ctrl-a/e))
23820 deactivate-mark refpos)
23821 (if (org-bound-and-true-p visual-line-mode)
23822 (beginning-of-visual-line 1)
23823 (beginning-of-line 1))
23824 (if (and arg (fboundp 'move-beginning-of-line))
23825 (call-interactively 'move-beginning-of-line)
23826 (unless (bobp)
23827 (backward-char 1)
23828 (if (org-truely-invisible-p)
23829 (while (and (not (bobp)) (org-truely-invisible-p))
23830 (backward-char 1)
23831 (beginning-of-line 1))
23832 (forward-char 1))))
23833 (when special
23834 (cond
23835 ((and (looking-at org-complex-heading-regexp)
23836 (eq (char-after (match-end 1)) ?\s))
23837 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23838 (point-at-eol)))
23839 (goto-char
23840 (if (eq special t)
23841 (cond ((> pos refpos) refpos)
23842 ((= pos (point)) refpos)
23843 (t (point)))
23844 (cond ((> pos (point)) (point))
23845 ((not (eq last-command this-command)) (point))
23846 (t refpos)))))
23847 ((org-at-item-p)
23848 ;; Being at an item and not looking at an the item means point
23849 ;; was previously moved to beginning of a visual line, which
23850 ;; doesn't contain the item. Therefore, do nothing special,
23851 ;; just stay here.
23852 (when (looking-at org-list-full-item-re)
23853 ;; Set special position at first white space character after
23854 ;; bullet, and check-box, if any.
23855 (let ((after-bullet
23856 (let ((box (match-end 3)))
23857 (if (not box) (match-end 1)
23858 (let ((after (char-after box)))
23859 (if (and after (= after ? )) (1+ box) box))))))
23860 ;; Special case: Move point to special position when
23861 ;; currently after it or at beginning of line.
23862 (if (eq special t)
23863 (when (or (> pos after-bullet) (= (point) pos))
23864 (goto-char after-bullet))
23865 ;; Reversed case: Move point to special position when
23866 ;; point was already at beginning of line and command is
23867 ;; repeated.
23868 (when (and (= (point) pos) (eq last-command this-command))
23869 (goto-char after-bullet))))))))
23870 (org-no-warnings
23871 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23872 (setq disable-point-adjustment
23873 (or (not (invisible-p (point)))
23874 (not (invisible-p (max (point-min) (1- (point))))))))
23876 (defun org-end-of-line (&optional arg)
23877 "Go to the end of the line.
23878 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23879 tags on the first attempt, and only move to after the tags when
23880 the cursor is already beyond the end of the headline."
23881 (interactive "P")
23882 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23883 org-special-ctrl-a/e))
23884 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23885 'end-of-visual-line)
23886 ((fboundp 'move-end-of-line) 'move-end-of-line)
23887 (t 'end-of-line)))
23888 deactivate-mark)
23889 (if (or (not special) arg) (call-interactively move-fun)
23890 (let* ((element (save-excursion (beginning-of-line)
23891 (org-element-at-point)))
23892 (type (org-element-type element)))
23893 (cond
23894 ((memq type '(headline inlinetask))
23895 (let ((pos (point)))
23896 (beginning-of-line 1)
23897 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23898 (if (eq special t)
23899 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23900 (goto-char (match-beginning 1))
23901 (goto-char (match-end 0)))
23902 (if (or (< pos (match-end 0))
23903 (not (eq this-command last-command)))
23904 (goto-char (match-end 0))
23905 (goto-char (match-beginning 1))))
23906 (call-interactively move-fun))))
23907 ((outline-invisible-p (line-end-position))
23908 ;; If element is hidden, `move-end-of-line' would put point
23909 ;; after it. Use `end-of-line' to stay on current line.
23910 (call-interactively 'end-of-line))
23911 (t (call-interactively move-fun)))))
23912 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23913 (setq disable-point-adjustment
23914 (or (not (invisible-p (point)))
23915 (not (invisible-p (max (point-min) (1- (point))))))))
23917 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23918 (define-key org-mode-map "\C-e" 'org-end-of-line)
23920 (defun org-backward-sentence (&optional _arg)
23921 "Go to beginning of sentence, or beginning of table field.
23922 This will call `backward-sentence' or `org-table-beginning-of-field',
23923 depending on context."
23924 (interactive)
23925 (let* ((element (org-element-at-point))
23926 (contents-begin (org-element-property :contents-begin element))
23927 (table (org-element-lineage element '(table) t)))
23928 (if (and table
23929 (> (point) contents-begin)
23930 (<= (point) (org-element-property :contents-end table)))
23931 (call-interactively #'org-table-beginning-of-field)
23932 (save-restriction
23933 (when (and contents-begin
23934 (< (point-min) contents-begin)
23935 (> (point) contents-begin))
23936 (narrow-to-region contents-begin
23937 (org-element-property :contents-end element)))
23938 (call-interactively #'backward-sentence)))))
23940 (defun org-forward-sentence (&optional _arg)
23941 "Go to end of sentence, or end of table field.
23942 This will call `forward-sentence' or `org-table-end-of-field',
23943 depending on context."
23944 (interactive)
23945 (let* ((element (org-element-at-point))
23946 (contents-end (org-element-property :contents-end element))
23947 (table (org-element-lineage element '(table) t)))
23948 (if (and table
23949 (>= (point) (org-element-property :contents-begin table))
23950 (< (point) contents-end))
23951 (call-interactively #'org-table-end-of-field)
23952 (save-restriction
23953 (when (and contents-end
23954 (> (point-max) contents-end)
23955 ;; Skip blank lines between elements.
23956 (< (org-element-property :end element)
23957 (save-excursion (goto-char contents-end)
23958 (skip-chars-forward " \r\t\n"))))
23959 (narrow-to-region (org-element-property :contents-begin element)
23960 contents-end))
23961 (call-interactively #'forward-sentence)))))
23963 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23964 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23966 (defun org-kill-line (&optional _arg)
23967 "Kill line, to tags or end of line."
23968 (interactive)
23969 (cond
23970 ((or (not org-special-ctrl-k)
23971 (bolp)
23972 (not (org-at-heading-p)))
23973 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23974 org-ctrl-k-protect-subtree
23975 (or (eq org-ctrl-k-protect-subtree 'error)
23976 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23977 (user-error "C-k aborted as it would kill a hidden subtree"))
23978 (call-interactively
23979 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23980 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23981 (kill-region (point) (match-beginning 1))
23982 (org-set-tags nil t))
23983 (t (kill-region (point) (point-at-eol)))))
23985 (define-key org-mode-map "\C-k" 'org-kill-line)
23987 (defun org-yank (&optional arg)
23988 "Yank. If the kill is a subtree, treat it specially.
23989 This command will look at the current kill and check if is a single
23990 subtree, or a series of subtrees[1]. If it passes the test, and if the
23991 cursor is at the beginning of a line or after the stars of a currently
23992 empty headline, then the yank is handled specially. How exactly depends
23993 on the value of the following variables, both set by default.
23995 `org-yank-folded-subtrees'
23996 When set, the subtree(s) will be folded after insertion, but only
23997 if doing so would now swallow text after the yanked text.
23999 `org-yank-adjusted-subtrees'
24000 When set, the subtree will be promoted or demoted in order to
24001 fit into the local outline tree structure, which means that the
24002 level will be adjusted so that it becomes the smaller one of the
24003 two *visible* surrounding headings.
24005 Any prefix to this command will cause `yank' to be called directly with
24006 no special treatment. In particular, a simple \\[universal-argument] prefix \
24007 will just
24008 plainly yank the text as it is.
24010 \[1] The test checks if the first non-white line is a heading
24011 and if there are no other headings with fewer stars."
24012 (interactive "P")
24013 (org-yank-generic 'yank arg))
24015 (defun org-yank-generic (command arg)
24016 "Perform some yank-like command.
24018 This function implements the behavior described in the `org-yank'
24019 documentation. However, it has been generalized to work for any
24020 interactive command with similar behavior."
24022 ;; pretend to be command COMMAND
24023 (setq this-command command)
24025 (if arg
24026 (call-interactively command)
24028 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24029 (and (org-kill-is-subtree-p)
24030 (or (bolp)
24031 (and (looking-at "[ \t]*$")
24032 (string-match
24033 "\\`\\*+\\'"
24034 (buffer-substring (point-at-bol) (point)))))))
24035 swallowp)
24036 (cond
24037 ((and subtreep org-yank-folded-subtrees)
24038 (let ((beg (point))
24039 end)
24040 (if (and subtreep org-yank-adjusted-subtrees)
24041 (org-paste-subtree nil nil 'for-yank)
24042 (call-interactively command))
24044 (setq end (point))
24045 (goto-char beg)
24046 (when (and (bolp) subtreep
24047 (not (setq swallowp
24048 (org-yank-folding-would-swallow-text beg end))))
24049 (org-with-limited-levels
24050 (or (looking-at org-outline-regexp)
24051 (re-search-forward org-outline-regexp-bol end t))
24052 (while (and (< (point) end) (looking-at org-outline-regexp))
24053 (outline-hide-subtree)
24054 (org-cycle-show-empty-lines 'folded)
24055 (condition-case nil
24056 (outline-forward-same-level 1)
24057 (error (goto-char end))))))
24058 (when swallowp
24059 (message
24060 "Inserted text not folded because that would swallow text"))
24062 (goto-char end)
24063 (skip-chars-forward " \t\n\r")
24064 (beginning-of-line 1)
24065 (push-mark beg 'nomsg)))
24066 ((and subtreep org-yank-adjusted-subtrees)
24067 (let ((beg (point-at-bol)))
24068 (org-paste-subtree nil nil 'for-yank)
24069 (push-mark beg 'nomsg)))
24071 (call-interactively command))))))
24073 (defun org-yank-folding-would-swallow-text (beg end)
24074 "Would hide-subtree at BEG swallow any text after END?"
24075 (let (level)
24076 (org-with-limited-levels
24077 (save-excursion
24078 (goto-char beg)
24079 (when (or (looking-at org-outline-regexp)
24080 (re-search-forward org-outline-regexp-bol end t))
24081 (setq level (org-outline-level)))
24082 (goto-char end)
24083 (skip-chars-forward " \t\r\n\v\f")
24084 (not (or (eobp)
24085 (and (bolp) (looking-at-p org-outline-regexp)
24086 (<= (org-outline-level) level))))))))
24088 (define-key org-mode-map "\C-y" 'org-yank)
24090 (defun org-truely-invisible-p ()
24091 "Check if point is at a character currently not visible.
24092 This version does not only check the character property, but also
24093 `visible-mode'."
24094 ;; Early versions of noutline don't have `outline-invisible-p'.
24095 (unless (org-bound-and-true-p visible-mode)
24096 (outline-invisible-p)))
24098 (defun org-invisible-p2 ()
24099 "Check if point is at a character currently not visible."
24100 (save-excursion
24101 (when (and (eolp) (not (bobp))) (backward-char 1))
24102 ;; Early versions of noutline don't have `outline-invisible-p'.
24103 (outline-invisible-p)))
24105 (defun org-back-to-heading (&optional invisible-ok)
24106 "Call `outline-back-to-heading', but provide a better error message."
24107 (condition-case nil
24108 (outline-back-to-heading invisible-ok)
24109 (error (error "Before first headline at position %d in buffer %s"
24110 (point) (current-buffer)))))
24112 (defun org-before-first-heading-p ()
24113 "Before first heading?"
24114 (save-excursion
24115 (end-of-line)
24116 (null (re-search-backward org-outline-regexp-bol nil t))))
24118 (defun org-at-heading-p (&optional ignored)
24119 (outline-on-heading-p t))
24120 ;;; Though the function was obsoleted in 7.8.03, the byte-compiler
24121 ;;; warning was only added in Org 9.0, which should be taken into
24122 ;;; account when deciding when to remove the alias.
24123 (define-obsolete-function-alias 'org-on-heading-p 'org-at-heading-p "Org 7.8.03")
24125 (defun org-in-commented-heading-p (&optional no-inheritance)
24126 "Non-nil if point is under a commented heading.
24127 This function also checks ancestors of the current headline,
24128 unless optional argument NO-INHERITANCE is non-nil."
24129 (cond
24130 ((org-before-first-heading-p) nil)
24131 ((let ((headline (nth 4 (org-heading-components))))
24132 (and headline
24133 (let ((case-fold-search nil))
24134 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24135 headline)))))
24136 (no-inheritance nil)
24138 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24140 (defun org-at-comment-p nil
24141 "Is cursor in a commented line?"
24142 (save-excursion
24143 (save-match-data
24144 (beginning-of-line)
24145 (looking-at "^[ \t]*# "))))
24147 (defun org-at-drawer-p nil
24148 "Is cursor at a drawer keyword?"
24149 (save-excursion
24150 (move-beginning-of-line 1)
24151 (looking-at org-drawer-regexp)))
24153 (defun org-at-block-p nil
24154 "Is cursor at a block keyword?"
24155 (save-excursion
24156 (move-beginning-of-line 1)
24157 (looking-at org-block-regexp)))
24159 (defun org-point-at-end-of-empty-headline ()
24160 "If point is at the end of an empty headline, return t, else nil.
24161 If the heading only contains a TODO keyword, it is still still considered
24162 empty."
24163 (and (looking-at "[ \t]*$")
24164 (when org-todo-line-regexp
24165 (save-excursion
24166 (beginning-of-line 1)
24167 (let ((case-fold-search nil))
24168 (looking-at org-todo-line-regexp)
24169 (string= (match-string 3) ""))))))
24171 (defun org-at-heading-or-item-p ()
24172 (or (org-at-heading-p) (org-at-item-p)))
24174 (defun org-at-target-p ()
24175 (or (org-in-regexp org-radio-target-regexp)
24176 (org-in-regexp org-target-regexp)))
24177 ;; Compatibility alias with Org versions < 7.8.03
24178 (defalias 'org-on-target-p 'org-at-target-p)
24180 (defun org-up-heading-all (arg)
24181 "Move to the heading line of which the present line is a subheading.
24182 This function considers both visible and invisible heading lines.
24183 With argument, move up ARG levels."
24184 (if (fboundp 'outline-up-heading-all)
24185 (outline-up-heading-all arg) ; emacs 21 version of outline.el
24186 (outline-up-heading arg t))) ; emacs 22 version of outline.el
24188 (defun org-up-heading-safe ()
24189 "Move to the heading line of which the present line is a subheading.
24190 This version will not throw an error. It will return the level of the
24191 headline found, or nil if no higher level is found.
24193 Also, this function will be a lot faster than `outline-up-heading',
24194 because it relies on stars being the outline starters. This can really
24195 make a significant difference in outlines with very many siblings."
24196 (when (ignore-errors (org-back-to-heading t))
24197 (let ((level-up (1- (funcall outline-level))))
24198 (and (> level-up 0)
24199 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24200 (funcall outline-level)))))
24202 (defun org-first-sibling-p ()
24203 "Is this heading the first child of its parents?"
24204 (interactive)
24205 (let ((re org-outline-regexp-bol)
24206 level l)
24207 (unless (org-at-heading-p t)
24208 (user-error "Not at a heading"))
24209 (setq level (funcall outline-level))
24210 (save-excursion
24211 (if (not (re-search-backward re nil t))
24213 (setq l (funcall outline-level))
24214 (< l level)))))
24216 (defun org-goto-sibling (&optional previous)
24217 "Goto the next sibling, even if it is invisible.
24218 When PREVIOUS is set, go to the previous sibling instead. Returns t
24219 when a sibling was found. When none is found, return nil and don't
24220 move point."
24221 (let ((fun (if previous 're-search-backward 're-search-forward))
24222 (pos (point))
24223 (re org-outline-regexp-bol)
24224 level l)
24225 (when (ignore-errors (org-back-to-heading t))
24226 (setq level (funcall outline-level))
24227 (catch 'exit
24228 (or previous (forward-char 1))
24229 (while (funcall fun re nil t)
24230 (setq l (funcall outline-level))
24231 (when (< l level) (goto-char pos) (throw 'exit nil))
24232 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24233 (goto-char pos)
24234 nil))))
24236 (defun org-show-siblings ()
24237 "Show all siblings of the current headline."
24238 (save-excursion
24239 (while (org-goto-sibling) (org-flag-heading nil)))
24240 (save-excursion
24241 (while (org-goto-sibling 'previous)
24242 (org-flag-heading nil))))
24244 (defun org-goto-first-child ()
24245 "Goto the first child, even if it is invisible.
24246 Return t when a child was found. Otherwise don't move point and
24247 return nil."
24248 (let (level (pos (point)) (re org-outline-regexp-bol))
24249 (when (ignore-errors (org-back-to-heading t))
24250 (setq level (outline-level))
24251 (forward-char 1)
24252 (if (and (re-search-forward re nil t) (> (outline-level) level))
24253 (progn (goto-char (match-beginning 0)) t)
24254 (goto-char pos) nil))))
24256 (defun org-show-hidden-entry ()
24257 "Show an entry where even the heading is hidden."
24258 (save-excursion
24259 (org-show-entry)))
24261 (defun org-flag-heading (flag &optional entry)
24262 "Flag the current heading. FLAG non-nil means make invisible.
24263 When ENTRY is non-nil, show the entire entry."
24264 (save-excursion
24265 (org-back-to-heading t)
24266 ;; Check if we should show the entire entry
24267 (if entry
24268 (progn
24269 (org-show-entry)
24270 (save-excursion
24271 (and (outline-next-heading)
24272 (org-flag-heading nil))))
24273 (outline-flag-region (max (point-min) (1- (point)))
24274 (save-excursion (outline-end-of-heading) (point))
24275 flag))))
24277 (defun org-get-next-sibling ()
24278 "Move to next heading of the same level, and return point.
24279 If there is no such heading, return nil.
24280 This is like outline-next-sibling, but invisible headings are ok."
24281 (let ((level (funcall outline-level)))
24282 (outline-next-heading)
24283 (while (and (not (eobp)) (> (funcall outline-level) level))
24284 (outline-next-heading))
24285 (unless (or (eobp) (< (funcall outline-level) level))
24286 (point))))
24288 (defun org-get-last-sibling ()
24289 "Move to previous heading of the same level, and return point.
24290 If there is no such heading, return nil."
24291 (let ((opoint (point))
24292 (level (funcall outline-level)))
24293 (outline-previous-heading)
24294 (when (and (/= (point) opoint) (outline-on-heading-p t))
24295 (while (and (> (funcall outline-level) level)
24296 (not (bobp)))
24297 (outline-previous-heading))
24298 (unless (< (funcall outline-level) level)
24299 (point)))))
24301 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24302 "Goto to the end of a subtree."
24303 ;; This contains an exact copy of the original function, but it uses
24304 ;; `org-back-to-heading', to make it work also in invisible
24305 ;; trees. And is uses an invisible-ok argument.
24306 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24307 ;; Furthermore, when used inside Org, finding the end of a large subtree
24308 ;; with many children and grandchildren etc, this can be much faster
24309 ;; than the outline version.
24310 (org-back-to-heading invisible-ok)
24311 (let ((first t)
24312 (level (funcall outline-level)))
24313 (if (and (derived-mode-p 'org-mode) (< level 1000))
24314 ;; A true heading (not a plain list item), in Org-mode
24315 ;; This means we can easily find the end by looking
24316 ;; only for the right number of stars. Using a regexp to do
24317 ;; this is so much faster than using a Lisp loop.
24318 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24319 (forward-char 1)
24320 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24321 ;; something else, do it the slow way
24322 (while (and (not (eobp))
24323 (or first (> (funcall outline-level) level)))
24324 (setq first nil)
24325 (outline-next-heading)))
24326 (unless to-heading
24327 (when (memq (preceding-char) '(?\n ?\^M))
24328 ;; Go to end of line before heading
24329 (forward-char -1)
24330 (when (memq (preceding-char) '(?\n ?\^M))
24331 ;; leave blank line before heading
24332 (forward-char -1)))))
24333 (point))
24335 (defun org-end-of-meta-data (&optional full)
24336 "Skip planning line and properties drawer in current entry.
24337 When optional argument FULL is non-nil, also skip empty lines,
24338 clocking lines and regular drawers at the beginning of the
24339 entry."
24340 (org-back-to-heading t)
24341 (forward-line)
24342 (when (org-looking-at-p org-planning-line-re) (forward-line))
24343 (when (looking-at org-property-drawer-re)
24344 (goto-char (match-end 0))
24345 (forward-line))
24346 (when (and full (not (org-at-heading-p)))
24347 (catch 'exit
24348 (let ((end (save-excursion (outline-next-heading) (point)))
24349 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24350 (while (not (eobp))
24351 (cond ((org-looking-at-p org-drawer-regexp)
24352 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24353 (forward-line)
24354 (throw 'exit t)))
24355 ((org-looking-at-p re) (forward-line))
24356 (t (throw 'exit t))))))))
24358 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24359 "Move forward to the ARG'th subheading at same level as this one.
24360 Stop at the first and last subheadings of a superior heading.
24361 Normally this only looks at visible headings, but when INVISIBLE-OK is
24362 non-nil it will also look at invisible ones."
24363 (interactive "p")
24364 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24365 (if (and arg (< arg 0))
24366 (goto-char (point-min))
24367 (outline-next-heading))
24368 (org-at-heading-p)
24369 (let ((level (- (match-end 0) (match-beginning 0) 1))
24370 (f (if (and arg (< arg 0))
24371 're-search-backward
24372 're-search-forward))
24373 (count (if arg (abs arg) 1))
24374 (result (point)))
24375 (while (and (prog1 (> count 0)
24376 (forward-char (if (and arg (< arg 0)) -1 1)))
24377 (funcall f org-outline-regexp-bol nil 'move))
24378 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24379 (cond ((< l level) (setq count 0))
24380 ((and (= l level)
24381 (or invisible-ok
24382 (progn
24383 (goto-char (line-beginning-position))
24384 (not (outline-invisible-p)))))
24385 (setq count (1- count))
24386 (when (eq l level)
24387 (setq result (point)))))))
24388 (goto-char result))
24389 (beginning-of-line 1)))
24391 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24392 "Move backward to the ARG'th subheading at same level as this one.
24393 Stop at the first and last subheadings of a superior heading."
24394 (interactive "p")
24395 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24397 (defun org-next-visible-heading (arg)
24398 "Move to the next visible heading.
24400 This function wraps `outline-next-visible-heading' with
24401 `org-with-limited-levels' in order to skip over inline tasks and
24402 respect customization of `org-odd-levels-only'."
24403 (interactive "p")
24404 (org-with-limited-levels
24405 (outline-next-visible-heading arg)))
24407 (defun org-previous-visible-heading (arg)
24408 "Move to the next visible heading.
24410 This function wraps `outline-previous-visible-heading' with
24411 `org-with-limited-levels' in order to skip over inline tasks and
24412 respect customization of `org-odd-levels-only'."
24413 (interactive "p")
24414 (org-with-limited-levels
24415 (outline-previous-visible-heading arg)))
24417 (defun org-next-block (arg &optional backward block-regexp)
24418 "Jump to the next block.
24420 With a prefix argument ARG, jump forward ARG many blocks.
24422 When BACKWARD is non-nil, jump to the previous block.
24424 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24425 Match data is set according to this regexp when the function
24426 returns.
24428 Return point at beginning of the opening line of found block.
24429 Throw an error if no block is found."
24430 (interactive "p")
24431 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24432 (case-fold-search t)
24433 (search-fn (if backward #'re-search-backward #'re-search-forward))
24434 (count (or arg 1))
24435 (origin (point))
24436 last-element)
24437 (if backward (beginning-of-line) (end-of-line))
24438 (while (and (> count 0) (funcall search-fn re nil t))
24439 (let ((element (save-excursion
24440 (goto-char (match-beginning 0))
24441 (save-match-data (org-element-at-point)))))
24442 (when (and (memq (org-element-type element)
24443 '(center-block comment-block dynamic-block
24444 example-block export-block quote-block
24445 special-block src-block verse-block))
24446 (<= (match-beginning 0)
24447 (org-element-property :post-affiliated element)))
24448 (setq last-element element)
24449 (cl-decf count))))
24450 (if (= count 0)
24451 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24452 (save-match-data (org-show-context)))
24453 (goto-char origin)
24454 (user-error "No %s code blocks" (if backward "previous" "further")))))
24456 (defun org-previous-block (arg &optional block-regexp)
24457 "Jump to the previous block.
24458 With a prefix argument ARG, jump backward ARG many source blocks.
24459 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24460 (interactive "p")
24461 (org-next-block arg t block-regexp))
24463 (defun org-forward-paragraph ()
24464 "Move forward to beginning of next paragraph or equivalent.
24466 The function moves point to the beginning of the next visible
24467 structural element, which can be a paragraph, a table, a list
24468 item, etc. It also provides some special moves for convenience:
24470 - On an affiliated keyword, jump to the beginning of the
24471 relative element.
24472 - On an item or a footnote definition, move to the second
24473 element inside, if any.
24474 - On a table or a property drawer, jump after it.
24475 - On a verse or source block, stop after blank lines."
24476 (interactive)
24477 (when (eobp) (user-error "Cannot move further down"))
24478 (let* ((deactivate-mark nil)
24479 (element (org-element-at-point))
24480 (type (org-element-type element))
24481 (post-affiliated (org-element-property :post-affiliated element))
24482 (contents-begin (org-element-property :contents-begin element))
24483 (contents-end (org-element-property :contents-end element))
24484 (end (let ((end (org-element-property :end element)) (parent element))
24485 (while (and (setq parent (org-element-property :parent parent))
24486 (= (org-element-property :contents-end parent) end))
24487 (setq end (org-element-property :end parent)))
24488 end)))
24489 (cond ((not element)
24490 (skip-chars-forward " \r\t\n")
24491 (or (eobp) (beginning-of-line)))
24492 ;; On affiliated keywords, move to element's beginning.
24493 ((< (point) post-affiliated)
24494 (goto-char post-affiliated))
24495 ;; At a table row, move to the end of the table. Similarly,
24496 ;; at a node property, move to the end of the property
24497 ;; drawer.
24498 ((memq type '(node-property table-row))
24499 (goto-char (org-element-property
24500 :end (org-element-property :parent element))))
24501 ((memq type '(property-drawer table)) (goto-char end))
24502 ;; Consider blank lines as separators in verse and source
24503 ;; blocks to ease editing.
24504 ((memq type '(src-block verse-block))
24505 (when (eq type 'src-block)
24506 (setq contents-end
24507 (save-excursion (goto-char end)
24508 (skip-chars-backward " \r\t\n")
24509 (line-beginning-position))))
24510 (beginning-of-line)
24511 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24512 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24513 (goto-char end)
24514 (skip-chars-forward " \r\t\n")
24515 (if (= (point) contents-end) (goto-char end)
24516 (beginning-of-line))))
24517 ;; With no contents, just skip element.
24518 ((not contents-begin) (goto-char end))
24519 ;; If contents are invisible, skip the element altogether.
24520 ((outline-invisible-p (line-end-position))
24521 (cl-case type
24522 (headline
24523 (org-with-limited-levels (outline-next-visible-heading 1)))
24524 ;; At a plain list, make sure we move to the next item
24525 ;; instead of skipping the whole list.
24526 (plain-list (forward-char)
24527 (org-forward-paragraph))
24528 (otherwise (goto-char end))))
24529 ((>= (point) contents-end) (goto-char end))
24530 ((>= (point) contents-begin)
24531 ;; This can only happen on paragraphs and plain lists.
24532 (cl-case type
24533 (paragraph (goto-char end))
24534 ;; At a plain list, try to move to second element in
24535 ;; first item, if possible.
24536 (plain-list (end-of-line)
24537 (org-forward-paragraph))))
24538 ;; When contents start on the middle of a line (e.g. in
24539 ;; items and footnote definitions), try to reach first
24540 ;; element starting after current line.
24541 ((> (line-end-position) contents-begin)
24542 (end-of-line)
24543 (org-forward-paragraph))
24544 (t (goto-char contents-begin)))))
24546 (defun org-backward-paragraph ()
24547 "Move backward to start of previous paragraph or equivalent.
24549 The function moves point to the beginning of the current
24550 structural element, which can be a paragraph, a table, a list
24551 item, etc., or to the beginning of the previous visible one if
24552 point is already there. It also provides some special moves for
24553 convenience:
24555 - On an affiliated keyword, jump to the first one.
24556 - On a table or a property drawer, move to its beginning.
24557 - On a verse or source block, stop before blank lines."
24558 (interactive)
24559 (when (bobp) (user-error "Cannot move further up"))
24560 (let* ((deactivate-mark nil)
24561 (element (org-element-at-point))
24562 (type (org-element-type element))
24563 (contents-begin (org-element-property :contents-begin element))
24564 (contents-end (org-element-property :contents-end element))
24565 (post-affiliated (org-element-property :post-affiliated element))
24566 (begin (org-element-property :begin element)))
24567 (cond
24568 ((not element) (goto-char (point-min)))
24569 ((= (point) begin)
24570 (backward-char)
24571 (org-backward-paragraph))
24572 ((<= (point) post-affiliated) (goto-char begin))
24573 ((memq type '(node-property table-row))
24574 (goto-char (org-element-property
24575 :post-affiliated (org-element-property :parent element))))
24576 ((memq type '(property-drawer table)) (goto-char begin))
24577 ((memq type '(src-block verse-block))
24578 (when (eq type 'src-block)
24579 (setq contents-begin
24580 (save-excursion (goto-char begin) (forward-line) (point))))
24581 (if (= (point) contents-begin) (goto-char post-affiliated)
24582 ;; Inside a verse block, see blank lines as paragraph
24583 ;; separators.
24584 (let ((origin (point)))
24585 (skip-chars-backward " \r\t\n" contents-begin)
24586 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24587 (skip-chars-forward " \r\t\n" origin)
24588 (if (= (point) origin) (goto-char contents-begin)
24589 (beginning-of-line))))))
24590 ((not contents-begin) (goto-char (or post-affiliated begin)))
24591 ((eq type 'paragraph)
24592 (goto-char contents-begin)
24593 ;; When at first paragraph in an item or a footnote definition,
24594 ;; move directly to beginning of line.
24595 (let ((parent-contents
24596 (org-element-property
24597 :contents-begin (org-element-property :parent element))))
24598 (when (and parent-contents (= parent-contents contents-begin))
24599 (beginning-of-line))))
24600 ;; At the end of a greater element, move to the beginning of the
24601 ;; last element within.
24602 ((>= (point) contents-end)
24603 (goto-char (1- contents-end))
24604 (org-backward-paragraph))
24605 (t (goto-char (or post-affiliated begin))))
24606 ;; Ensure we never leave point invisible.
24607 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24609 (defun org-forward-element ()
24610 "Move forward by one element.
24611 Move to the next element at the same level, when possible."
24612 (interactive)
24613 (cond ((eobp) (user-error "Cannot move further down"))
24614 ((org-with-limited-levels (org-at-heading-p))
24615 (let ((origin (point)))
24616 (goto-char (org-end-of-subtree nil t))
24617 (unless (org-with-limited-levels (org-at-heading-p))
24618 (goto-char origin)
24619 (user-error "Cannot move further down"))))
24621 (let* ((elem (org-element-at-point))
24622 (end (org-element-property :end elem))
24623 (parent (org-element-property :parent elem)))
24624 (cond ((and parent (= (org-element-property :contents-end parent) end))
24625 (goto-char (org-element-property :end parent)))
24626 ((integer-or-marker-p end) (goto-char end))
24627 (t (message "No element at point")))))))
24629 (defun org-backward-element ()
24630 "Move backward by one element.
24631 Move to the previous element at the same level, when possible."
24632 (interactive)
24633 (cond ((bobp) (user-error "Cannot move further up"))
24634 ((org-with-limited-levels (org-at-heading-p))
24635 ;; At a headline, move to the previous one, if any, or stay
24636 ;; here.
24637 (let ((origin (point)))
24638 (org-with-limited-levels (org-backward-heading-same-level 1))
24639 ;; When current headline has no sibling above, move to its
24640 ;; parent.
24641 (when (= (point) origin)
24642 (or (org-with-limited-levels (org-up-heading-safe))
24643 (progn (goto-char origin)
24644 (user-error "Cannot move further up"))))))
24646 (let* ((elem (org-element-at-point))
24647 (beg (org-element-property :begin elem)))
24648 (cond
24649 ;; Move to beginning of current element if point isn't
24650 ;; there already.
24651 ((null beg) (message "No element at point"))
24652 ((/= (point) beg) (goto-char beg))
24653 (t (goto-char beg)
24654 (skip-chars-backward " \r\t\n")
24655 (unless (bobp)
24656 (let ((prev (org-element-at-point)))
24657 (goto-char (org-element-property :begin prev))
24658 (while (and (setq prev (org-element-property :parent prev))
24659 (<= (org-element-property :end prev) beg))
24660 (goto-char (org-element-property :begin prev)))))))))))
24662 (defun org-up-element ()
24663 "Move to upper element."
24664 (interactive)
24665 (if (org-with-limited-levels (org-at-heading-p))
24666 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24667 (let* ((elem (org-element-at-point))
24668 (parent (org-element-property :parent elem)))
24669 (if parent (goto-char (org-element-property :begin parent))
24670 (if (org-with-limited-levels (org-before-first-heading-p))
24671 (user-error "No surrounding element")
24672 (org-with-limited-levels (org-back-to-heading)))))))
24674 (defvar org-element-greater-elements)
24675 (defun org-down-element ()
24676 "Move to inner element."
24677 (interactive)
24678 (let ((element (org-element-at-point)))
24679 (cond
24680 ((memq (org-element-type element) '(plain-list table))
24681 (goto-char (org-element-property :contents-begin element))
24682 (forward-char))
24683 ((memq (org-element-type element) org-element-greater-elements)
24684 ;; If contents are hidden, first disclose them.
24685 (when (outline-invisible-p (line-end-position)) (org-cycle))
24686 (goto-char (or (org-element-property :contents-begin element)
24687 (user-error "No content for this element"))))
24688 (t (user-error "No inner element")))))
24690 (defun org-drag-element-backward ()
24691 "Move backward element at point."
24692 (interactive)
24693 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24694 (let* ((elem (org-element-at-point))
24695 (prev-elem
24696 (save-excursion
24697 (goto-char (org-element-property :begin elem))
24698 (skip-chars-backward " \r\t\n")
24699 (unless (bobp)
24700 (let* ((beg (org-element-property :begin elem))
24701 (prev (org-element-at-point))
24702 (up prev))
24703 (while (and (setq up (org-element-property :parent up))
24704 (<= (org-element-property :end up) beg))
24705 (setq prev up))
24706 prev)))))
24707 ;; Error out if no previous element or previous element is
24708 ;; a parent of the current one.
24709 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24710 (user-error "Cannot drag element backward")
24711 (let ((pos (point)))
24712 (org-element-swap-A-B prev-elem elem)
24713 (goto-char (+ (org-element-property :begin prev-elem)
24714 (- pos (org-element-property :begin elem)))))))))
24716 (defun org-drag-element-forward ()
24717 "Move forward element at point."
24718 (interactive)
24719 (let* ((pos (point))
24720 (elem (org-element-at-point)))
24721 (when (= (point-max) (org-element-property :end elem))
24722 (user-error "Cannot drag element forward"))
24723 (goto-char (org-element-property :end elem))
24724 (let ((next-elem (org-element-at-point)))
24725 (when (or (org-element-nested-p elem next-elem)
24726 (and (eq (org-element-type next-elem) 'headline)
24727 (not (eq (org-element-type elem) 'headline))))
24728 (goto-char pos)
24729 (user-error "Cannot drag element forward"))
24730 ;; Compute new position of point: it's shifted by NEXT-ELEM
24731 ;; body's length (without final blanks) and by the length of
24732 ;; blanks between ELEM and NEXT-ELEM.
24733 (let ((size-next (- (save-excursion
24734 (goto-char (org-element-property :end next-elem))
24735 (skip-chars-backward " \r\t\n")
24736 (forward-line)
24737 ;; Small correction if buffer doesn't end
24738 ;; with a newline character.
24739 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24740 (org-element-property :begin next-elem)))
24741 (size-blank (- (org-element-property :end elem)
24742 (save-excursion
24743 (goto-char (org-element-property :end elem))
24744 (skip-chars-backward " \r\t\n")
24745 (forward-line)
24746 (point)))))
24747 (org-element-swap-A-B elem next-elem)
24748 (goto-char (+ pos size-next size-blank))))))
24750 (defun org-drag-line-forward (arg)
24751 "Drag the line at point ARG lines forward."
24752 (interactive "p")
24753 (dotimes (_ (abs arg))
24754 (let ((c (current-column)))
24755 (if (< 0 arg)
24756 (progn
24757 (beginning-of-line 2)
24758 (transpose-lines 1)
24759 (beginning-of-line 0))
24760 (transpose-lines 1)
24761 (beginning-of-line -1))
24762 (org-move-to-column c))))
24764 (defun org-drag-line-backward (arg)
24765 "Drag the line at point ARG lines backward."
24766 (interactive "p")
24767 (org-drag-line-forward (- arg)))
24769 (defun org-mark-element ()
24770 "Put point at beginning of this element, mark at end.
24772 Interactively, if this command is repeated or (in Transient Mark
24773 mode) if the mark is active, it marks the next element after the
24774 ones already marked."
24775 (interactive)
24776 (let (deactivate-mark)
24777 (if (and (org-called-interactively-p 'any)
24778 (or (and (eq last-command this-command) (mark t))
24779 (and transient-mark-mode mark-active)))
24780 (set-mark
24781 (save-excursion
24782 (goto-char (mark))
24783 (goto-char (org-element-property :end (org-element-at-point)))))
24784 (let ((element (org-element-at-point)))
24785 (end-of-line)
24786 (push-mark (org-element-property :end element) t t)
24787 (goto-char (org-element-property :begin element))))))
24789 (defun org-narrow-to-element ()
24790 "Narrow buffer to current element."
24791 (interactive)
24792 (let ((elem (org-element-at-point)))
24793 (cond
24794 ((eq (car elem) 'headline)
24795 (narrow-to-region
24796 (org-element-property :begin elem)
24797 (org-element-property :end elem)))
24798 ((memq (car elem) org-element-greater-elements)
24799 (narrow-to-region
24800 (org-element-property :contents-begin elem)
24801 (org-element-property :contents-end elem)))
24803 (narrow-to-region
24804 (org-element-property :begin elem)
24805 (org-element-property :end elem))))))
24807 (defun org-transpose-element ()
24808 "Transpose current and previous elements, keeping blank lines between.
24809 Point is moved after both elements."
24810 (interactive)
24811 (org-skip-whitespace)
24812 (let ((end (org-element-property :end (org-element-at-point))))
24813 (org-drag-element-backward)
24814 (goto-char end)))
24816 (defun org-unindent-buffer ()
24817 "Un-indent the visible part of the buffer.
24818 Relative indentation (between items, inside blocks, etc.) isn't
24819 modified."
24820 (interactive)
24821 (unless (eq major-mode 'org-mode)
24822 (user-error "Cannot un-indent a buffer not in Org mode"))
24823 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24824 (unindent-tree
24825 (lambda (contents)
24826 (dolist (element (reverse contents))
24827 (if (memq (org-element-type element) '(headline section))
24828 (funcall unindent-tree (org-element-contents element))
24829 (save-excursion
24830 (save-restriction
24831 (narrow-to-region
24832 (org-element-property :begin element)
24833 (org-element-property :end element))
24834 (org-do-remove-indentation))))))))
24835 (funcall unindent-tree (org-element-contents parse-tree))))
24837 (defun org-show-children (&optional level)
24838 "Show all direct subheadings of this heading.
24839 Prefix arg LEVEL is how many levels below the current level
24840 should be shown. Default is enough to cause the following
24841 heading to appear."
24842 (interactive "p")
24843 ;; If `orgstruct-mode' is active, use the slower version.
24844 (if orgstruct-mode (call-interactively #'outline-show-children)
24845 (save-excursion
24846 (org-back-to-heading t)
24847 (let* ((current-level (funcall outline-level))
24848 (max-level (org-get-valid-level
24849 current-level
24850 (if level (prefix-numeric-value level) 1)))
24851 (end (save-excursion (org-end-of-subtree t t)))
24852 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24853 (past-first-child nil)
24854 ;; Make sure to skip inlinetasks.
24855 (re (format regexp-fmt
24856 current-level
24857 (cond
24858 ((not (featurep 'org-inlinetask)) "")
24859 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24861 (t (1- org-inlinetask-min-level))))))
24862 ;; Display parent heading.
24863 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24864 (forward-line)
24865 ;; Display children. First child may be deeper than expected
24866 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24867 ;; MAX-LEVEL accordingly.
24868 (while (re-search-forward re end t)
24869 (unless past-first-child
24870 (setq re (format regexp-fmt
24871 current-level
24872 (max (funcall outline-level) max-level)))
24873 (setq past-first-child t))
24874 (outline-flag-region
24875 (line-end-position 0) (line-end-position) nil))))))
24877 (defun org-show-subtree ()
24878 "Show everything after this heading at deeper levels."
24879 (interactive)
24880 (outline-flag-region
24881 (point)
24882 (save-excursion
24883 (org-end-of-subtree t t))
24884 nil))
24886 (defun org-show-entry ()
24887 "Show the body directly following this heading.
24888 Show the heading too, if it is currently invisible."
24889 (interactive)
24890 (save-excursion
24891 (ignore-errors
24892 (org-back-to-heading t)
24893 (outline-flag-region
24894 (max (point-min) (1- (point)))
24895 (save-excursion
24896 (if (re-search-forward
24897 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24898 (match-beginning 1)
24899 (point-max)))
24900 nil)
24901 (org-cycle-hide-drawers 'children))))
24903 (defun org-make-options-regexp (kwds &optional extra)
24904 "Make a regular expression for keyword lines.
24905 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24906 when non-nil, is a regexp matching keywords names."
24907 (concat "^[ \t]*#\\+\\("
24908 (regexp-opt kwds)
24909 (and extra (concat (and kwds "\\|") extra))
24910 "\\):[ \t]*\\(.*\\)"))
24912 ;; Make isearch reveal the necessary context
24913 (defun org-isearch-end ()
24914 "Reveal context after isearch exits."
24915 (when isearch-success ; only if search was successful
24916 (if (featurep 'xemacs)
24917 ;; Under XEmacs, the hook is run in the correct place,
24918 ;; we directly show the context.
24919 (org-show-context 'isearch)
24920 ;; In Emacs the hook runs *before* restoring the overlays.
24921 ;; So we have to use a one-time post-command-hook to do this.
24922 ;; (Emacs 22 has a special variable, see function `org-mode')
24923 (unless (and (boundp 'isearch-mode-end-hook-quit)
24924 isearch-mode-end-hook-quit)
24925 ;; Only when the isearch was not quitted.
24926 (org-add-hook 'post-command-hook 'org-isearch-post-command
24927 'append 'local)))))
24929 (defun org-isearch-post-command ()
24930 "Remove self from hook, and show context."
24931 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24932 (org-show-context 'isearch))
24935 ;;;; Integration with and fixes for other packages
24937 ;;; Imenu support
24939 (defvar-local org-imenu-markers nil
24940 "All markers currently used by Imenu.")
24942 (defun org-imenu-new-marker (&optional pos)
24943 "Return a new marker for use by Imenu, and remember the marker."
24944 (let ((m (make-marker)))
24945 (move-marker m (or pos (point)))
24946 (push m org-imenu-markers)
24949 (defun org-imenu-get-tree ()
24950 "Produce the index for Imenu."
24951 (dolist (x org-imenu-markers) (move-marker x nil))
24952 (setq org-imenu-markers nil)
24953 (let* ((n org-imenu-depth)
24954 (re (concat "^" (org-get-limited-outline-regexp)))
24955 (subs (make-vector (1+ n) nil))
24956 (last-level 0)
24957 m level head0 head)
24958 (save-excursion
24959 (save-restriction
24960 (widen)
24961 (goto-char (point-max))
24962 (while (re-search-backward re nil t)
24963 (setq level (org-reduced-level (funcall outline-level)))
24964 (when (and (<= level n)
24965 (looking-at org-complex-heading-regexp)
24966 (setq head0 (org-match-string-no-properties 4)))
24967 (setq head (org-link-display-format head0)
24968 m (org-imenu-new-marker))
24969 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24970 (if (>= level last-level)
24971 (push (cons head m) (aref subs level))
24972 (push (cons head (aref subs (1+ level))) (aref subs level))
24973 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24974 (setq last-level level)))))
24975 (aref subs 1)))
24977 (eval-after-load "imenu"
24978 '(progn
24979 (add-hook 'imenu-after-jump-hook
24980 (lambda ()
24981 (when (derived-mode-p 'org-mode)
24982 (org-show-context 'org-goto))))))
24984 (defun org-link-display-format (link)
24985 "Replace a link with its the description.
24986 If there is no description, use the link target."
24987 (save-match-data
24988 (if (string-match org-bracket-link-analytic-regexp link)
24989 (replace-match (if (match-end 5)
24990 (match-string 5 link)
24991 (concat (match-string 1 link)
24992 (match-string 3 link)))
24993 nil t link)
24994 link)))
24996 (defun org-toggle-link-display ()
24997 "Toggle the literal or descriptive display of links."
24998 (interactive)
24999 (if org-descriptive-links
25000 (progn (org-remove-from-invisibility-spec '(org-link))
25001 (org-restart-font-lock)
25002 (setq org-descriptive-links nil))
25003 (progn (add-to-invisibility-spec '(org-link))
25004 (org-restart-font-lock)
25005 (setq org-descriptive-links t))))
25007 ;; Speedbar support
25009 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
25010 "Overlay marking the agenda restriction line in speedbar.")
25011 (overlay-put org-speedbar-restriction-lock-overlay
25012 'face 'org-agenda-restriction-lock)
25013 (overlay-put org-speedbar-restriction-lock-overlay
25014 'help-echo "Agendas are currently limited to this item.")
25015 (org-detach-overlay org-speedbar-restriction-lock-overlay)
25017 (defun org-speedbar-set-agenda-restriction ()
25018 "Restrict future agenda commands to the location at point in speedbar.
25019 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
25020 (interactive)
25021 (require 'org-agenda)
25022 (let (p m tp np dir txt)
25023 (cond
25024 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25025 'org-imenu t))
25026 (setq m (get-text-property p 'org-imenu-marker))
25027 (with-current-buffer (marker-buffer m)
25028 (goto-char m)
25029 (org-agenda-set-restriction-lock 'subtree)))
25030 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25031 'speedbar-function 'speedbar-find-file))
25032 (setq tp (previous-single-property-change
25033 (1+ p) 'speedbar-function)
25034 np (next-single-property-change
25035 tp 'speedbar-function)
25036 dir (speedbar-line-directory)
25037 txt (buffer-substring-no-properties (or tp (point-min))
25038 (or np (point-max))))
25039 (with-current-buffer (find-file-noselect
25040 (let ((default-directory dir))
25041 (expand-file-name txt)))
25042 (unless (derived-mode-p 'org-mode)
25043 (user-error "Cannot restrict to non-Org-mode file"))
25044 (org-agenda-set-restriction-lock 'file)))
25045 (t (user-error "Don't know how to restrict Org-mode's agenda")))
25046 (move-overlay org-speedbar-restriction-lock-overlay
25047 (point-at-bol) (point-at-eol))
25048 (setq current-prefix-arg nil)
25049 (org-agenda-maybe-redo)))
25051 (defvar speedbar-file-key-map)
25052 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25053 (eval-after-load "speedbar"
25054 '(progn
25055 (speedbar-add-supported-extension ".org")
25056 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25057 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25058 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25059 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25060 (add-hook 'speedbar-visiting-tag-hook
25061 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25063 ;;; Fixes and Hacks for problems with other packages
25065 (defun org--flyspell-object-check-p (element)
25066 "Non-nil when Flyspell can check object at point.
25067 ELEMENT is the element at point."
25068 (let ((object (save-excursion
25069 (when (org-looking-at-p "\\>") (backward-char))
25070 (org-element-context element))))
25071 (cl-case (org-element-type object)
25072 ;; Prevent checks in links due to keybinding conflict with
25073 ;; Flyspell.
25074 ((code entity export-snippet inline-babel-call
25075 inline-src-block line-break latex-fragment link macro
25076 statistics-cookie target timestamp verbatim)
25077 nil)
25078 (footnote-reference
25079 ;; Only in inline footnotes, within the definition.
25080 (and (eq (org-element-property :type object) 'inline)
25081 (< (save-excursion
25082 (goto-char (org-element-property :begin object))
25083 (search-forward ":" nil t 2))
25084 (point))))
25085 (otherwise t))))
25087 (defun org-mode-flyspell-verify ()
25088 "Function used for `flyspell-generic-check-word-predicate'."
25089 (if (org-at-heading-p)
25090 ;; At a headline or an inlinetask, check title only. This is
25091 ;; faster than relying on `org-element-at-point'.
25092 (and (save-excursion (beginning-of-line)
25093 (and (let ((case-fold-search t))
25094 (not (looking-at "\\*+ END[ \t]*$")))
25095 (looking-at org-complex-heading-regexp)))
25096 (match-beginning 4)
25097 (>= (point) (match-beginning 4))
25098 (or (not (match-beginning 5))
25099 (< (point) (match-beginning 5))))
25100 (let* ((element (org-element-at-point))
25101 (post-affiliated (org-element-property :post-affiliated element)))
25102 (cond
25103 ;; Ignore checks in all affiliated keywords but captions.
25104 ((< (point) post-affiliated)
25105 (and (save-excursion
25106 (beginning-of-line)
25107 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25108 (> (point) (match-end 0))
25109 (org--flyspell-object-check-p element)))
25110 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25111 ((let ((log (org-log-into-drawer)))
25112 (and log
25113 (let ((drawer (org-element-lineage element '(drawer))))
25114 (and drawer
25115 (eq (compare-strings
25116 log nil nil
25117 (org-element-property :drawer-name drawer) nil nil t)
25118 t)))))
25119 nil)
25121 (cl-case (org-element-type element)
25122 ((comment quote-section) t)
25123 (comment-block
25124 ;; Allow checks between block markers, not on them.
25125 (and (> (line-beginning-position) post-affiliated)
25126 (save-excursion
25127 (end-of-line)
25128 (skip-chars-forward " \r\t\n")
25129 (< (point) (org-element-property :end element)))))
25130 ;; Arbitrary list of keywords where checks are meaningful.
25131 ;; Make sure point is on the value part of the element.
25132 (keyword
25133 (and (member (org-element-property :key element)
25134 '("DESCRIPTION" "TITLE"))
25135 (save-excursion
25136 (search-backward ":" (line-beginning-position) t))))
25137 ;; Check is globally allowed in paragraphs verse blocks and
25138 ;; table rows (after affiliated keywords) but some objects
25139 ;; must not be affected.
25140 ((paragraph table-row verse-block)
25141 (let ((cbeg (org-element-property :contents-begin element))
25142 (cend (org-element-property :contents-end element)))
25143 (and cbeg (>= (point) cbeg) (< (point) cend)
25144 (org--flyspell-object-check-p element))))))))))
25145 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25147 (defun org-remove-flyspell-overlays-in (beg end)
25148 "Remove flyspell overlays in region."
25149 (and (org-bound-and-true-p flyspell-mode)
25150 (fboundp 'flyspell-delete-region-overlays)
25151 (flyspell-delete-region-overlays beg end)))
25153 (defvar flyspell-delayed-commands)
25154 (eval-after-load "flyspell"
25155 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25157 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25158 (eval-after-load "bookmark"
25159 '(if (boundp 'bookmark-after-jump-hook)
25160 ;; We can use the hook
25161 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25162 ;; Hook not available, use advice
25163 (defadvice bookmark-jump (after org-make-visible activate)
25164 "Make the position visible."
25165 (org-bookmark-jump-unhide))))
25167 ;; Make sure saveplace shows the location if it was hidden
25168 (eval-after-load "saveplace"
25169 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25170 "Make the position visible."
25171 (org-bookmark-jump-unhide)))
25173 ;; Make sure ecb shows the location if it was hidden
25174 (eval-after-load "ecb"
25175 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25176 "Make hierarchy visible when jumping into location from ECB tree buffer."
25177 (when (derived-mode-p 'org-mode)
25178 (org-show-context))))
25180 (defun org-bookmark-jump-unhide ()
25181 "Unhide the current position, to show the bookmark location."
25182 (and (derived-mode-p 'org-mode)
25183 (or (outline-invisible-p)
25184 (save-excursion (goto-char (max (point-min) (1- (point))))
25185 (outline-invisible-p)))
25186 (org-show-context 'bookmark-jump)))
25188 (defun org-mark-jump-unhide ()
25189 "Make the point visible with `org-show-context' after jumping to the mark."
25190 (when (and (derived-mode-p 'org-mode)
25191 (outline-invisible-p))
25192 (org-show-context 'mark-goto)))
25194 (eval-after-load "simple"
25195 '(defadvice pop-to-mark-command (after org-make-visible activate)
25196 "Make the point visible with `org-show-context'."
25197 (org-mark-jump-unhide)))
25199 (eval-after-load "simple"
25200 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25201 "Make the point visible with `org-show-context'."
25202 (org-mark-jump-unhide)))
25204 (eval-after-load "simple"
25205 '(defadvice pop-global-mark (after org-make-visible activate)
25206 "Make the point visible with `org-show-context'."
25207 (org-mark-jump-unhide)))
25209 ;; Make session.el ignore our circular variable
25210 (defvar session-globals-exclude)
25211 (eval-after-load "session"
25212 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25214 ;;;; Finish up
25216 (provide 'org)
25218 (run-hooks 'org-load-hook)
25220 ;;; org.el ends here