Improve docstrings regarding latex_compiler
[org-mode.git] / lisp / org.el
blob3645d5d185ec7fd13e56a81b3f05a39c4464fcea
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2015 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 org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (equal this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
114 (unless (boundp 'calendar-view-holidays-initially-flag)
115 (org-defvaralias 'calendar-view-holidays-initially-flag
116 'view-calendar-holidays-initially))
117 (unless (boundp 'calendar-view-diary-initially-flag)
118 (org-defvaralias 'calendar-view-diary-initially-flag
119 'view-diary-entries-initially))
120 (unless (boundp 'diary-fancy-buffer)
121 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
123 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
124 (declare-function org-add-archive-files "org-archive" (files))
125 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
126 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
127 (declare-function org-agenda-redo "org-agenda" (&optional all))
128 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
129 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
130 (declare-function org-beamer-mode "ox-beamer" ())
131 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
132 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
133 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
134 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
135 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
136 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
137 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
138 (declare-function org-clock-update-time-maybe "org-clock" ())
139 (declare-function org-clocktable-shift "org-clock" (dir n))
140 (declare-function org-element-at-point "org-element" ())
141 (declare-function org-element-cache-refresh "org-element" (pos))
142 (declare-function org-element-cache-reset "org-element" (&optional all))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-copy "org-element" (datum))
146 (declare-function org-element-interpret-data "org-element" (data &optional parent))
147 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
148 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
149 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
150 (declare-function org-element-property "org-element" (property element))
151 (declare-function org-element-put-property "org-element" (element property value))
152 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
153 (declare-function org-element-type "org-element" (element))
154 (declare-function org-element-update-syntax "org-element" ())
155 (declare-function org-id-find-id-file "org-id" (id))
156 (declare-function org-id-get-create "org-id" (&optional force))
157 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
158 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
159 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
160 (declare-function org-plot/gnuplot "org-plot" (&optional params))
161 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
162 (declare-function org-table-align "org-table" ())
163 (declare-function org-table-begin "org-table" (&optional table-type))
164 (declare-function org-table-beginning-of-field "org-table" (&optional n))
165 (declare-function org-table-blank-field "org-table" ())
166 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
167 (declare-function org-table-edit-field "org-table" (arg))
168 (declare-function org-table-end "org-table" (&optional table-type))
169 (declare-function org-table-end-of-field "org-table" (&optional n))
170 (declare-function org-table-insert-row "org-table" (&optional arg))
171 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
172 (declare-function org-table-maybe-eval-formula "org-table" ())
173 (declare-function org-table-maybe-recalculate-line "org-table" ())
174 (declare-function org-table-next-row "org-table" ())
175 (declare-function org-table-paste-rectangle "org-table" ())
176 (declare-function org-table-wrap-region "org-table" (arg))
177 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
178 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
179 (declare-function orgtbl-mode "org-table" (&optional arg))
181 (defsubst org-uniquify (list)
182 "Non-destructively remove duplicate elements from LIST."
183 (let ((res (copy-sequence list))) (delete-dups res)))
185 (defsubst org-get-at-bol (property)
186 "Get text property PROPERTY at the beginning of line."
187 (get-text-property (point-at-bol) property))
189 (defsubst org-trim (s)
190 "Remove whitespace at the beginning and the end of string S."
191 (replace-regexp-in-string
192 "\\`[ \t\n\r]+" ""
193 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
195 ;; load languages based on value of `org-babel-load-languages'
196 (defvar org-babel-load-languages)
198 ;;;###autoload
199 (defun org-babel-do-load-languages (sym value)
200 "Load the languages defined in `org-babel-load-languages'."
201 (set-default sym value)
202 (mapc (lambda (pair)
203 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
204 (if active
205 (progn
206 (require (intern (concat "ob-" lang))))
207 (progn
208 (funcall 'fmakunbound
209 (intern (concat "org-babel-execute:" lang)))
210 (funcall 'fmakunbound
211 (intern (concat "org-babel-expand-body:" lang)))))))
212 org-babel-load-languages))
214 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
215 ;;;###autoload
216 (defun org-babel-load-file (file &optional compile)
217 "Load Emacs Lisp source code blocks in the Org-mode FILE.
218 This function exports the source code using `org-babel-tangle'
219 and then loads the resulting file using `load-file'. With prefix
220 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
221 file to byte-code before it is loaded."
222 (interactive "fFile to load: \nP")
223 (let* ((age (lambda (file)
224 (float-time
225 (time-subtract (current-time)
226 (nth 5 (or (file-attributes (file-truename file))
227 (file-attributes file)))))))
228 (base-name (file-name-sans-extension file))
229 (exported-file (concat base-name ".el")))
230 ;; tangle if the org-mode file is newer than the elisp file
231 (unless (and (file-exists-p exported-file)
232 (> (funcall age file) (funcall age exported-file)))
233 ;; Tangle-file traversal returns reversed list of tangled files
234 ;; and we want to evaluate the first target.
235 (setq exported-file
236 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
237 (message "%s %s"
238 (if compile
239 (progn (byte-compile-file exported-file 'load)
240 "Compiled and loaded")
241 (progn (load-file exported-file) "Loaded"))
242 exported-file)))
244 (defcustom org-babel-load-languages '((emacs-lisp . t))
245 "Languages which can be evaluated in Org-mode buffers.
246 This list can be used to load support for any of the languages
247 below, note that each language will depend on a different set of
248 system executables and/or Emacs modes. When a language is
249 \"loaded\", then code blocks in that language can be evaluated
250 with `org-babel-execute-src-block' bound by default to C-c
251 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
252 be set to remove code block evaluation from the C-c C-c
253 keybinding. By default only Emacs Lisp (which has no
254 requirements) is loaded."
255 :group 'org-babel
256 :set 'org-babel-do-load-languages
257 :version "24.1"
258 :type '(alist :tag "Babel Languages"
259 :key-type
260 (choice
261 (const :tag "Awk" awk)
262 (const :tag "C" C)
263 (const :tag "R" R)
264 (const :tag "Asymptote" asymptote)
265 (const :tag "Calc" calc)
266 (const :tag "Clojure" clojure)
267 (const :tag "CSS" css)
268 (const :tag "Ditaa" ditaa)
269 (const :tag "Dot" dot)
270 (const :tag "Emacs Lisp" emacs-lisp)
271 (const :tag "Forth" forth)
272 (const :tag "Fortran" fortran)
273 (const :tag "Gnuplot" gnuplot)
274 (const :tag "Haskell" haskell)
275 (const :tag "IO" io)
276 (const :tag "J" J)
277 (const :tag "Java" java)
278 (const :tag "Javascript" js)
279 (const :tag "LaTeX" latex)
280 (const :tag "Ledger" ledger)
281 (const :tag "Lilypond" lilypond)
282 (const :tag "Lisp" lisp)
283 (const :tag "Makefile" makefile)
284 (const :tag "Maxima" maxima)
285 (const :tag "Matlab" matlab)
286 (const :tag "Mscgen" mscgen)
287 (const :tag "Ocaml" ocaml)
288 (const :tag "Octave" octave)
289 (const :tag "Org" org)
290 (const :tag "Perl" perl)
291 (const :tag "Pico Lisp" picolisp)
292 (const :tag "PlantUML" plantuml)
293 (const :tag "Python" python)
294 (const :tag "Ruby" ruby)
295 (const :tag "Sass" sass)
296 (const :tag "Scala" scala)
297 (const :tag "Scheme" scheme)
298 (const :tag "Screen" screen)
299 (const :tag "Shell Script" shell)
300 (const :tag "Shen" shen)
301 (const :tag "Sql" sql)
302 (const :tag "Sqlite" sqlite)
303 (const :tag "Stan" stan)
304 (const :tag "ebnf2ps" ebnf2ps))
305 :value-type (boolean :tag "Activate" :value t)))
307 ;;;; Customization variables
308 (defcustom org-clone-delete-id nil
309 "Remove ID property of clones of a subtree.
310 When non-nil, clones of a subtree don't inherit the ID property.
311 Otherwise they inherit the ID property with a new unique
312 identifier."
313 :type 'boolean
314 :version "24.1"
315 :group 'org-id)
317 ;;; Version
318 (org-check-version)
320 ;;;###autoload
321 (defun org-version (&optional here full message)
322 "Show the org-mode version.
323 Interactively, or when MESSAGE is non-nil, show it in echo area.
324 With prefix argument, or when HERE is non-nil, insert it at point.
325 In non-interactive uses, a reduced version string is output unless
326 FULL is given."
327 (interactive (list current-prefix-arg t (not current-prefix-arg)))
328 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
329 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
330 (load-suffixes (list ".el"))
331 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
332 (org-trash (or
333 (and (fboundp 'org-release) (fboundp 'org-git-version))
334 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
335 (load-suffixes save-load-suffixes)
336 (org-version (org-release))
337 (git-version (org-git-version))
338 (version (format "Org-mode version %s (%s @ %s)"
339 org-version
340 git-version
341 (if org-install-dir
342 (if (string= org-dir org-install-dir)
343 org-install-dir
344 (concat "mixed installation! " org-install-dir " and " org-dir))
345 "org-loaddefs.el can not be found!")))
346 (version1 (if full version org-version)))
347 (when here (insert version1))
348 (when message (message "%s" version1))
349 version1))
351 (defconst org-version (org-version))
354 ;;; Syntax Constants
356 ;;;; Block
358 (defconst org-block-regexp
359 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
360 "Regular expression for hiding blocks.")
362 (defconst org-dblock-start-re
363 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
364 "Matches the start line of a dynamic block, with parameters.")
366 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
367 "Matches the end of a dynamic block.")
369 ;;;; Clock and Planning
371 (defconst org-clock-string "CLOCK:"
372 "String used as prefix for timestamps clocking work hours on an item.")
374 (defvar org-closed-string "CLOSED:"
375 "String used as the prefix for timestamps logging closing a TODO entry.")
377 (defvar org-deadline-string "DEADLINE:"
378 "String to mark deadline entries.
379 A deadline is this string, followed by a time stamp. Should be a word,
380 terminated by a colon. You can insert a schedule keyword and
381 a timestamp with \\[org-deadline].")
383 (defvar org-scheduled-string "SCHEDULED:"
384 "String to mark scheduled TODO entries.
385 A schedule is this string, followed by a time stamp. Should be a word,
386 terminated by a colon. You can insert a schedule keyword and
387 a timestamp with \\[org-schedule].")
389 (defconst org-ds-keyword-length
390 (+ 2
391 (apply #'max
392 (mapcar #'length
393 (list org-deadline-string org-scheduled-string
394 org-clock-string org-closed-string))))
395 "Maximum length of the DEADLINE and SCHEDULED keywords.")
397 (defconst org-planning-line-re
398 (concat "^[ \t]*"
399 (regexp-opt
400 (list org-closed-string org-deadline-string org-scheduled-string)
402 "Matches a line with planning info.
403 Matched keyword is in group 1.")
405 (defconst org-clock-line-re
406 (concat "^[ \t]*" org-clock-string)
407 "Matches a line with clock info.")
409 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
410 "Matches the DEADLINE keyword.")
412 (defconst org-deadline-time-regexp
413 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
414 "Matches the DEADLINE keyword together with a time stamp.")
416 (defconst org-deadline-time-hour-regexp
417 (concat "\\<" org-deadline-string
418 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
419 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
421 (defconst org-deadline-line-regexp
422 (concat "\\<\\(" org-deadline-string "\\).*")
423 "Matches the DEADLINE keyword and the rest of the line.")
425 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
426 "Matches the SCHEDULED keyword.")
428 (defconst org-scheduled-time-regexp
429 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
430 "Matches the SCHEDULED keyword together with a time stamp.")
432 (defconst org-scheduled-time-hour-regexp
433 (concat "\\<" org-scheduled-string
434 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
435 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
437 (defconst org-closed-time-regexp
438 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
439 "Matches the CLOSED keyword together with a time stamp.")
441 (defconst org-keyword-time-regexp
442 (concat "\\<"
443 (regexp-opt
444 (list org-scheduled-string org-deadline-string org-closed-string
445 org-clock-string)
447 " *[[<]\\([^]>]+\\)[]>]")
448 "Matches any of the 4 keywords, together with the time stamp.")
450 (defconst org-keyword-time-not-clock-regexp
451 (concat
452 "\\<"
453 (regexp-opt
454 (list org-scheduled-string org-deadline-string org-closed-string) t)
455 " *[[<]\\([^]>]+\\)[]>]")
456 "Matches any of the 3 keywords, together with the time stamp.")
458 (defconst org-maybe-keyword-time-regexp
459 (concat "\\(\\<"
460 (regexp-opt
461 (list org-scheduled-string org-deadline-string org-closed-string
462 org-clock-string)
464 "\\)?"
465 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
466 "\\|"
467 "<%%([^\r\n>]*>\\)")
468 "Matches a timestamp, possibly preceded by a keyword.")
470 (defconst org-all-time-keywords
471 (mapcar (lambda (w) (substring w 0 -1))
472 (list org-scheduled-string org-deadline-string
473 org-clock-string org-closed-string))
474 "List of time keywords.")
476 ;;;; Drawer
478 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
479 "Matches first or last line of a hidden block.
480 Group 1 contains drawer's name or \"END\".")
482 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
483 "Regular expression matching the first line of a property drawer.")
485 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
486 "Regular expression matching the last line of a property drawer.")
488 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
489 "Regular expression matching the first line of a clock drawer.")
491 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
492 "Regular expression matching the last line of a clock drawer.")
494 (defconst org-property-drawer-re
495 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
496 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
497 "[ \t]*:END:[ \t]*$")
498 "Matches an entire property drawer.")
500 (defconst org-clock-drawer-re
501 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
502 org-clock-drawer-end-re "\\)\n?")
503 "Matches an entire clock drawer.")
505 ;;;; Headline
507 (defconst org-heading-keyword-regexp-format
508 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
509 "Printf format for a regexp matching a headline with some keyword.
510 This regexp will match the headline of any node which has the
511 exact keyword that is put into the format. The keyword isn't in
512 any group by default, but the stars and the body are.")
514 (defconst org-heading-keyword-maybe-regexp-format
515 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
516 "Printf format for a regexp matching a headline, possibly with some keyword.
517 This regexp can match any headline with the specified keyword, or
518 without a keyword. The keyword isn't in any group by default,
519 but the stars and the body are.")
521 (defconst org-archive-tag "ARCHIVE"
522 "The tag that marks a subtree as archived.
523 An archived subtree does not open during visibility cycling, and does
524 not contribute to the agenda listings.")
526 (defconst org-comment-string "COMMENT"
527 "Entries starting with this keyword will never be exported.
528 An entry can be toggled between COMMENT and normal with
529 \\[org-toggle-comment].")
532 ;;;; LaTeX Environments and Fragments
534 (defconst org-latex-regexps
535 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
536 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
537 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
538 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
539 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
540 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
541 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
542 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
543 "Regular expressions for matching embedded LaTeX.")
545 ;;;; Node Property
547 (defconst org-effort-property "Effort"
548 "The property that is being used to keep track of effort estimates.
549 Effort estimates given in this property need to have the format H:MM.")
551 ;;;; Table
553 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
554 "Detect an org-type or table-type table.")
556 (defconst org-table-line-regexp "^[ \t]*|"
557 "Detect an org-type table line.")
559 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
560 "Detect an org-type table line.")
562 (defconst org-table-hline-regexp "^[ \t]*|-"
563 "Detect an org-type table hline.")
565 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
566 "Detect a table-type table hline.")
568 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
569 "Detect the first line outside a table when searching from within it.
570 This works for both table types.")
572 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
573 "Detect a #+TBLFM line.")
575 ;;;; Timestamp
577 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
578 "Regular expression for fast time stamp matching.")
580 (defconst org-ts-regexp-inactive
581 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
582 "Regular expression for fast inactive time stamp matching.")
584 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
585 "Regular expression for fast time stamp matching.")
587 (defconst org-ts-regexp0
588 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
589 "Regular expression matching time strings for analysis.
590 This one does not require the space after the date, so it can be used
591 on a string that terminates immediately after the date.")
593 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
594 "Regular expression matching time strings for analysis.")
596 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
597 "Regular expression matching time stamps, with groups.")
599 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
600 "Regular expression matching time stamps (also [..]), with groups.")
602 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
603 "Regular expression matching a time stamp range.")
605 (defconst org-tr-regexp-both
606 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
607 "Regular expression matching a time stamp range.")
609 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
610 org-ts-regexp "\\)?")
611 "Regular expression matching a time stamp or time stamp range.")
613 (defconst org-tsr-regexp-both
614 (concat org-ts-regexp-both "\\(--?-?"
615 org-ts-regexp-both "\\)?")
616 "Regular expression matching a time stamp or time stamp range.
617 The time stamps may be either active or inactive.")
619 (defconst org-repeat-re
620 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
621 "Regular expression for specifying repeated events.
622 After a match, group 1 contains the repeat expression.")
624 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
625 "Formats for `format-time-string' which are used for time stamps.")
628 ;;; The custom variables
630 (defgroup org nil
631 "Outline-based notes management and organizer."
632 :tag "Org"
633 :group 'outlines
634 :group 'calendar)
636 (defcustom org-mode-hook nil
637 "Mode hook for Org-mode, run after the mode was turned on."
638 :group 'org
639 :type 'hook)
641 (defcustom org-load-hook nil
642 "Hook that is run after org.el has been loaded."
643 :group 'org
644 :type 'hook)
646 (defcustom org-log-buffer-setup-hook nil
647 "Hook that is run after an Org log buffer is created."
648 :group 'org
649 :version "24.1"
650 :type 'hook)
652 (defvar org-modules) ; defined below
653 (defvar org-modules-loaded nil
654 "Have the modules been loaded already?")
656 (defun org-load-modules-maybe (&optional force)
657 "Load all extensions listed in `org-modules'."
658 (when (or force (not org-modules-loaded))
659 (mapc (lambda (ext)
660 (condition-case nil (require ext)
661 (error (message "Problems while trying to load feature `%s'" ext))))
662 org-modules)
663 (setq org-modules-loaded t)))
665 (defun org-set-modules (var value)
666 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
667 (set var value)
668 (when (featurep 'org)
669 (org-load-modules-maybe 'force)
670 (org-element-cache-reset 'all)))
672 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
673 "Modules that should always be loaded together with org.el.
675 If a description starts with <C>, the file is not part of Emacs
676 and loading it will require that you have downloaded and properly
677 installed the Org mode distribution.
679 You can also use this system to load external packages (i.e. neither Org
680 core modules, nor modules from the CONTRIB directory). Just add symbols
681 to the end of the list. If the package is called org-xyz.el, then you need
682 to add the symbol `xyz', and the package must have a call to:
684 (provide \\='org-xyz)
686 For export specific modules, see also `org-export-backends'."
687 :group 'org
688 :set 'org-set-modules
689 :version "24.4"
690 :package-version '(Org . "8.0")
691 :type
692 '(set :greedy t
693 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
694 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
695 (const :tag " crypt: Encryption of subtrees" org-crypt)
696 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
697 (const :tag " docview: Links to doc-view buffers" org-docview)
698 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
699 (const :tag " habit: Track your consistency with habits" org-habit)
700 (const :tag " id: Global IDs for identifying entries" org-id)
701 (const :tag " info: Links to Info nodes" org-info)
702 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
703 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
704 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
705 (const :tag " mouse: Additional mouse support" org-mouse)
706 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
707 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
708 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
710 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
711 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
712 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
713 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
714 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
715 (const :tag "C collector: Collect properties into tables" org-collector)
716 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
717 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
718 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
719 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
720 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
721 (const :tag "C eval: Include command output as text" org-eval)
722 (const :tag "C eww: Store link to url of eww" org-eww)
723 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
724 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
725 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
726 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
727 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
728 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
729 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
730 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
731 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
732 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
733 (const :tag "C mew: Links to Mew folders/messages" org-mew)
734 (const :tag "C mtags: Support for muse-like tags" org-mtags)
735 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
736 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
737 (const :tag "C registry: A registry for Org-mode links" org-registry)
738 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
739 (const :tag "C secretary: Team management with org-mode" org-secretary)
740 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
741 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
742 (const :tag "C track: Keep up with Org-mode development" org-track)
743 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
744 (const :tag "C vm: Links to VM folders/messages" org-vm)
745 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
746 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
747 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
749 (defvar org-export-registered-backends) ; From ox.el.
750 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
751 (declare-function org-export-backend-name "ox" (backend))
752 (defcustom org-export-backends '(ascii html icalendar latex)
753 "List of export back-ends that should be always available.
755 If a description starts with <C>, the file is not part of Emacs
756 and loading it will require that you have downloaded and properly
757 installed the Org mode distribution.
759 Unlike to `org-modules', libraries in this list will not be
760 loaded along with Org, but only once the export framework is
761 needed.
763 This variable needs to be set before org.el is loaded. If you
764 need to make a change while Emacs is running, use the customize
765 interface or run the following code, where VAL stands for the new
766 value of the variable, after updating it:
768 (progn
769 (setq org-export-registered-backends
770 (org-remove-if-not
771 (lambda (backend)
772 (let ((name (org-export-backend-name backend)))
773 (or (memq name val)
774 (catch \\='parentp
775 (dolist (b val)
776 (and (org-export-derived-backend-p b name)
777 (throw \\='parentp t)))))))
778 org-export-registered-backends))
779 (let ((new-list (mapcar #\\='org-export-backend-name
780 org-export-registered-backends)))
781 (dolist (backend val)
782 (cond
783 ((not (load (format \"ox-%s\" backend) t t))
784 (message \"Problems while trying to load export back-end \\=`%s\\='\"
785 backend))
786 ((not (memq backend new-list)) (push backend new-list))))
787 (set-default \\='org-export-backends new-list)))
789 Adding a back-end to this list will also pull the back-end it
790 depends on, if any."
791 :group 'org
792 :group 'org-export
793 :version "24.4"
794 :package-version '(Org . "8.0")
795 :initialize 'custom-initialize-set
796 :set (lambda (var val)
797 (if (not (featurep 'ox)) (set-default var val)
798 ;; Any back-end not required anymore (not present in VAL and not
799 ;; a parent of any back-end in the new value) is removed from the
800 ;; list of registered back-ends.
801 (setq org-export-registered-backends
802 (org-remove-if-not
803 (lambda (backend)
804 (let ((name (org-export-backend-name backend)))
805 (or (memq name val)
806 (catch 'parentp
807 (dolist (b val)
808 (and (org-export-derived-backend-p b name)
809 (throw 'parentp t)))))))
810 org-export-registered-backends))
811 ;; Now build NEW-LIST of both new back-ends and required
812 ;; parents.
813 (let ((new-list (mapcar #'org-export-backend-name
814 org-export-registered-backends)))
815 (dolist (backend val)
816 (cond
817 ((not (load (format "ox-%s" backend) t t))
818 (message "Problems while trying to load export back-end `%s'"
819 backend))
820 ((not (memq backend new-list)) (push backend new-list))))
821 ;; Set VAR to that list with fixed dependencies.
822 (set-default var new-list))))
823 :type '(set :greedy t
824 (const :tag " ascii Export buffer to ASCII format" ascii)
825 (const :tag " beamer Export buffer to Beamer presentation" beamer)
826 (const :tag " html Export buffer to HTML format" html)
827 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
828 (const :tag " latex Export buffer to LaTeX format" latex)
829 (const :tag " man Export buffer to MAN format" man)
830 (const :tag " md Export buffer to Markdown format" md)
831 (const :tag " odt Export buffer to ODT format" odt)
832 (const :tag " org Export buffer to Org format" org)
833 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
834 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
835 (const :tag "C deck Export buffer to deck.js presentations" deck)
836 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
837 (const :tag "C groff Export buffer to Groff format" groff)
838 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
839 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
840 (const :tag "C s5 Export buffer to s5 presentations" s5)
841 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
843 (eval-after-load 'ox
844 '(mapc
845 (lambda (backend)
846 (condition-case nil (require (intern (format "ox-%s" backend)))
847 (error (message "Problems while trying to load export back-end `%s'"
848 backend))))
849 org-export-backends))
851 (defcustom org-support-shift-select nil
852 "Non-nil means make shift-cursor commands select text when possible.
853 \\<org-mode-map>\
855 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
856 start selecting a region, or enlarge regions started in this way.
857 In Org-mode, in special contexts, these same keys are used for
858 other purposes, important enough to compete with shift selection.
859 Org tries to balance these needs by supporting `shift-select-mode'
860 outside these special contexts, under control of this variable.
862 The default of this variable is nil, to avoid confusing behavior. Shifted
863 cursor keys will then execute Org commands in the following contexts:
864 - on a headline, changing TODO state (left/right) and priority (up/down)
865 - on a time stamp, changing the time
866 - in a plain list item, changing the bullet type
867 - in a property definition line, switching between allowed values
868 - in the BEGIN line of a clock table (changing the time block).
869 Outside these contexts, the commands will throw an error.
871 When this variable is t and the cursor is not in a special
872 context, Org-mode will support shift-selection for making and
873 enlarging regions. To make this more effective, the bullet
874 cycling will no longer happen anywhere in an item line, but only
875 if the cursor is exactly on the bullet.
877 If you set this variable to the symbol `always', then the keys
878 will not be special in headlines, property lines, and item lines,
879 to make shift selection work there as well. If this is what you
880 want, you can use the following alternative commands:
881 `\\[org-todo]' and `\\[org-priority]' \
882 to change TODO state and priority,
883 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
884 can be used to switch TODO sets,
885 `\\[org-ctrl-c-minus]' to cycle item bullet types,
886 and properties can be edited by hand or in column view.
888 However, when the cursor is on a timestamp, shift-cursor commands
889 will still edit the time stamp - this is just too good to give up.
891 XEmacs user should have this variable set to nil, because
892 `shift-select-mode' is in Emacs 23 or later only."
893 :group 'org
894 :type '(choice
895 (const :tag "Never" nil)
896 (const :tag "When outside special context" t)
897 (const :tag "Everywhere except timestamps" always)))
899 (defcustom org-loop-over-headlines-in-active-region nil
900 "Shall some commands act upon headlines in the active region?
902 When set to t, some commands will be performed in all headlines
903 within the active region.
905 When set to `start-level', some commands will be performed in all
906 headlines within the active region, provided that these headlines
907 are of the same level than the first one.
909 When set to a string, those commands will be performed on the
910 matching headlines within the active region. Such string must be
911 a tags/property/todo match as it is used in the agenda tags view.
913 The list of commands is: `org-schedule', `org-deadline',
914 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
915 `org-archive-to-archive-sibling'. The archiving commands skip
916 already archived entries."
917 :type '(choice (const :tag "Don't loop" nil)
918 (const :tag "All headlines in active region" t)
919 (const :tag "In active region, headlines at the same level than the first one" start-level)
920 (string :tag "Tags/Property/Todo matcher"))
921 :version "24.1"
922 :group 'org-todo
923 :group 'org-archive)
925 (defgroup org-startup nil
926 "Options concerning startup of Org-mode."
927 :tag "Org Startup"
928 :group 'org)
930 (defcustom org-startup-folded t
931 "Non-nil means entering Org-mode will switch to OVERVIEW.
932 This can also be configured on a per-file basis by adding one of
933 the following lines anywhere in the buffer:
935 #+STARTUP: fold (or `overview', this is equivalent)
936 #+STARTUP: nofold (or `showall', this is equivalent)
937 #+STARTUP: content
938 #+STARTUP: showeverything
940 By default, this option is ignored when Org opens agenda files
941 for the first time. If you want the agenda to honor the startup
942 option, set `org-agenda-inhibit-startup' to nil."
943 :group 'org-startup
944 :type '(choice
945 (const :tag "nofold: show all" nil)
946 (const :tag "fold: overview" t)
947 (const :tag "content: all headlines" content)
948 (const :tag "show everything, even drawers" showeverything)))
950 (defcustom org-startup-truncated t
951 "Non-nil means entering Org-mode will set `truncate-lines'.
952 This is useful since some lines containing links can be very long and
953 uninteresting. Also tables look terrible when wrapped."
954 :group 'org-startup
955 :type 'boolean)
957 (defcustom org-startup-indented nil
958 "Non-nil means turn on `org-indent-mode' on startup.
959 This can also be configured on a per-file basis by adding one of
960 the following lines anywhere in the buffer:
962 #+STARTUP: indent
963 #+STARTUP: noindent"
964 :group 'org-structure
965 :type '(choice
966 (const :tag "Not" nil)
967 (const :tag "Globally (slow on startup in large files)" t)))
969 (defcustom org-use-sub-superscripts t
970 "Non-nil means interpret \"_\" and \"^\" for display.
972 If you want to control how Org exports those characters, see
973 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
974 used to be an alias for `org-export-with-sub-superscripts' in
975 Org <8.0, it is not anymore.
977 When this option is turned on, you can use TeX-like syntax for
978 sub- and superscripts within the buffer. Several characters after
979 \"_\" or \"^\" will be considered as a single item - so grouping
980 with {} is normally not needed. For example, the following things
981 will be parsed as single sub- or superscripts:
983 10^24 or 10^tau several digits will be considered 1 item.
984 10^-12 or 10^-tau a leading sign with digits or a word
985 x^2-y^3 will be read as x^2 - y^3, because items are
986 terminated by almost any nonword/nondigit char.
987 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
989 Still, ambiguity is possible. So when in doubt, use {} to enclose
990 the sub/superscript. If you set this variable to the symbol `{}',
991 the braces are *required* in order to trigger interpretations as
992 sub/superscript. This can be helpful in documents that need \"_\"
993 frequently in plain text."
994 :group 'org-startup
995 :version "24.4"
996 :package-version '(Org . "8.0")
997 :type '(choice
998 (const :tag "Always interpret" t)
999 (const :tag "Only with braces" {})
1000 (const :tag "Never interpret" nil)))
1002 (defcustom org-startup-with-beamer-mode nil
1003 "Non-nil means turn on `org-beamer-mode' on startup.
1004 This can also be configured on a per-file basis by adding one of
1005 the following lines anywhere in the buffer:
1007 #+STARTUP: beamer"
1008 :group 'org-startup
1009 :version "24.1"
1010 :type 'boolean)
1012 (defcustom org-startup-align-all-tables nil
1013 "Non-nil means align all tables when visiting a file.
1014 This is useful when the column width in tables is forced with <N> cookies
1015 in table fields. Such tables will look correct only after the first re-align.
1016 This can also be configured on a per-file basis by adding one of
1017 the following lines anywhere in the buffer:
1018 #+STARTUP: align
1019 #+STARTUP: noalign"
1020 :group 'org-startup
1021 :type 'boolean)
1023 (defcustom org-startup-with-inline-images nil
1024 "Non-nil means show inline images when loading a new Org file.
1025 This can also be configured on a per-file basis by adding one of
1026 the following lines anywhere in the buffer:
1027 #+STARTUP: inlineimages
1028 #+STARTUP: noinlineimages"
1029 :group 'org-startup
1030 :version "24.1"
1031 :type 'boolean)
1033 (defcustom org-startup-with-latex-preview nil
1034 "Non-nil means preview LaTeX fragments when loading a new Org file.
1036 This can also be configured on a per-file basis by adding one of
1037 the following lines anywhere in the buffer:
1038 #+STARTUP: latexpreview
1039 #+STARTUP: nolatexpreview"
1040 :group 'org-startup
1041 :version "24.4"
1042 :package-version '(Org . "8.0")
1043 :type 'boolean)
1045 (defcustom org-insert-mode-line-in-empty-file nil
1046 "Non-nil means insert the first line setting Org-mode in empty files.
1047 When the function `org-mode' is called interactively in an empty file, this
1048 normally means that the file name does not automatically trigger Org-mode.
1049 To ensure that the file will always be in Org-mode in the future, a
1050 line enforcing Org-mode will be inserted into the buffer, if this option
1051 has been set."
1052 :group 'org-startup
1053 :type 'boolean)
1055 (defcustom org-replace-disputed-keys nil
1056 "Non-nil means use alternative key bindings for some keys.
1057 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
1058 These keys are also used by other packages like shift-selection-mode'
1059 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1060 If you want to use Org-mode together with one of these other modes,
1061 or more generally if you would like to move some Org-mode commands to
1062 other keys, set this variable and configure the keys with the variable
1063 `org-disputed-keys'.
1065 This option is only relevant at load-time of Org-mode, and must be set
1066 *before* org.el is loaded. Changing it requires a restart of Emacs to
1067 become effective."
1068 :group 'org-startup
1069 :type 'boolean)
1071 (defcustom org-use-extra-keys nil
1072 "Non-nil means use extra key sequence definitions for certain commands.
1073 This happens automatically if you run XEmacs or if `window-system'
1074 is nil. This variable lets you do the same manually. You must
1075 set it before loading org.
1077 Example: on Carbon Emacs 22 running graphically, with an external
1078 keyboard on a Powerbook, the default way of setting M-left might
1079 not work for either Alt or ESC. Setting this variable will make
1080 it work for ESC."
1081 :group 'org-startup
1082 :type 'boolean)
1084 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1086 (defcustom org-disputed-keys
1087 '(([(shift up)] . [(meta p)])
1088 ([(shift down)] . [(meta n)])
1089 ([(shift left)] . [(meta -)])
1090 ([(shift right)] . [(meta +)])
1091 ([(control shift right)] . [(meta shift +)])
1092 ([(control shift left)] . [(meta shift -)]))
1093 "Keys for which Org-mode and other modes compete.
1094 This is an alist, cars are the default keys, second element specifies
1095 the alternative to use when `org-replace-disputed-keys' is t.
1097 Keys can be specified in any syntax supported by `define-key'.
1098 The value of this option takes effect only at Org-mode's startup,
1099 therefore you'll have to restart Emacs to apply it after changing."
1100 :group 'org-startup
1101 :type 'alist)
1103 (defun org-key (key)
1104 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1105 Or return the original if not disputed.
1106 Also apply the translations defined in `org-xemacs-key-equivalents'."
1107 (when org-replace-disputed-keys
1108 (let* ((nkey (key-description key))
1109 (x (org-find-if (lambda (x)
1110 (equal (key-description (car x)) nkey))
1111 org-disputed-keys)))
1112 (setq key (if x (cdr x) key))))
1113 (when (featurep 'xemacs)
1114 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1115 key)
1117 (defun org-find-if (predicate seq)
1118 (catch 'exit
1119 (while seq
1120 (if (funcall predicate (car seq))
1121 (throw 'exit (car seq))
1122 (pop seq)))))
1124 (defun org-defkey (keymap key def)
1125 "Define a key, possibly translated, as returned by `org-key'."
1126 (define-key keymap (org-key key) def))
1128 (defcustom org-ellipsis nil
1129 "The ellipsis to use in the Org-mode outline.
1130 When nil, just use the standard three dots.
1131 When a string, use that string instead.
1132 When a face, use the standard 3 dots, but with the specified face.
1133 The change affects only Org-mode (which will then use its own display table).
1134 Changing this requires executing \\[org-mode] in a buffer to become
1135 effective."
1136 :group 'org-startup
1137 :type '(choice (const :tag "Default" nil)
1138 (face :tag "Face" :value org-warning)
1139 (string :tag "String" :value "...#")))
1141 (defvar org-display-table nil
1142 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1144 (defgroup org-keywords nil
1145 "Keywords in Org-mode."
1146 :tag "Org Keywords"
1147 :group 'org)
1149 (defcustom org-closed-keep-when-no-todo nil
1150 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1151 :group 'org-todo
1152 :group 'org-keywords
1153 :version "24.4"
1154 :package-version '(Org . "8.0")
1155 :type 'boolean)
1157 (defgroup org-structure nil
1158 "Options concerning the general structure of Org-mode files."
1159 :tag "Org Structure"
1160 :group 'org)
1162 (defgroup org-reveal-location nil
1163 "Options about how to make context of a location visible."
1164 :tag "Org Reveal Location"
1165 :group 'org-structure)
1167 (defcustom org-show-context-detail '((isearch . lineage)
1168 (bookmark-jump . lineage)
1169 (default . ancestors))
1170 "Alist between context and visibility span when revealing a location.
1172 \\<org-mode-map>Some actions may move point into invisible
1173 locations. As a consequence, Org always expose a neighborhood
1174 around point. How much is shown depends on the initial action,
1175 or context. Valid contexts are
1177 agenda when exposing an entry from the agenda
1178 org-goto when using the command `org-goto' (\\[org-goto])
1179 occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
1180 tags-tree when constructing a sparse tree based on tags matches
1181 link-search when exposing search matches associated with a link
1182 mark-goto when exposing the jump goal of a mark
1183 bookmark-jump when exposing a bookmark location
1184 isearch when exiting from an incremental search
1185 default default for all contexts not set explicitly
1187 Allowed visibility spans are
1189 minimal show current headline; if point is not on headline,
1190 also show entry
1192 local show current headline, entry and next headline
1194 ancestors show current headline and its direct ancestors; if
1195 point is not on headline, also show entry
1197 lineage show current headline, its direct ancestors and all
1198 their children; if point is not on headline, also show
1199 entry and first child
1201 tree show current headline, its direct ancestors and all
1202 their children; if point is not on headline, also show
1203 entry and all children
1205 canonical show current headline, its direct ancestors along with
1206 their entries and children; if point is not located on
1207 the headline, also show current entry and all children
1209 As special cases, a nil or t value means show all contexts in
1210 `minimal' or `canonical' view, respectively.
1212 Some views can make displayed information very compact, but also
1213 make it harder to edit the location of the match. In such
1214 a case, use the command `org-reveal' (\\[org-reveal]) to show
1215 more context."
1216 :group 'org-reveal-location
1217 :version "25.1"
1218 :package-version '(Org . "8.3")
1219 :type '(choice
1220 (const :tag "Canonical" t)
1221 (const :tag "Minimal" nil)
1222 (repeat :greedy t :tag "Individual contexts"
1223 (cons
1224 (choice :tag "Context"
1225 (const agenda)
1226 (const org-goto)
1227 (const occur-tree)
1228 (const tags-tree)
1229 (const link-search)
1230 (const mark-goto)
1231 (const bookmark-jump)
1232 (const isearch)
1233 (const default))
1234 (choice :tag "Detail level"
1235 (const minimal)
1236 (const local)
1237 (const ancestors)
1238 (const lineage)
1239 (const tree)
1240 (const canonical))))))
1242 (defcustom org-indirect-buffer-display 'other-window
1243 "How should indirect tree buffers be displayed?
1244 This applies to indirect buffers created with the commands
1245 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1246 Valid values are:
1247 current-window Display in the current window
1248 other-window Just display in another window.
1249 dedicated-frame Create one new frame, and re-use it each time.
1250 new-frame Make a new frame each time. Note that in this case
1251 previously-made indirect buffers are kept, and you need to
1252 kill these buffers yourself."
1253 :group 'org-structure
1254 :group 'org-agenda-windows
1255 :type '(choice
1256 (const :tag "In current window" current-window)
1257 (const :tag "In current frame, other window" other-window)
1258 (const :tag "Each time a new frame" new-frame)
1259 (const :tag "One dedicated frame" dedicated-frame)))
1261 (defcustom org-use-speed-commands nil
1262 "Non-nil means activate single letter commands at beginning of a headline.
1263 This may also be a function to test for appropriate locations where speed
1264 commands should be active.
1266 For example, to activate speed commands when the point is on any
1267 star at the beginning of the headline, you can do this:
1269 (setq org-use-speed-commands
1270 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1271 :group 'org-structure
1272 :type '(choice
1273 (const :tag "Never" nil)
1274 (const :tag "At beginning of headline stars" t)
1275 (function)))
1277 (defcustom org-speed-commands-user nil
1278 "Alist of additional speed commands.
1279 This list will be checked before `org-speed-commands-default'
1280 when the variable `org-use-speed-commands' is non-nil
1281 and when the cursor is at the beginning of a headline.
1282 The car if each entry is a string with a single letter, which must
1283 be assigned to `self-insert-command' in the global map.
1284 The cdr is either a command to be called interactively, a function
1285 to be called, or a form to be evaluated.
1286 An entry that is just a list with a single string will be interpreted
1287 as a descriptive headline that will be added when listing the speed
1288 commands in the Help buffer using the `?' speed command."
1289 :group 'org-structure
1290 :type '(repeat :value ("k" . ignore)
1291 (choice :value ("k" . ignore)
1292 (list :tag "Descriptive Headline" (string :tag "Headline"))
1293 (cons :tag "Letter and Command"
1294 (string :tag "Command letter")
1295 (choice
1296 (function)
1297 (sexp))))))
1299 (defcustom org-bookmark-names-plist
1300 '(:last-capture "org-capture-last-stored"
1301 :last-refile "org-refile-last-stored"
1302 :last-capture-marker "org-capture-last-stored-marker")
1303 "Names for bookmarks automatically set by some Org commands.
1304 This can provide strings as names for a number of bookmarks Org sets
1305 automatically. The following keys are currently implemented:
1306 :last-capture
1307 :last-capture-marker
1308 :last-refile
1309 When a key does not show up in the property list, the corresponding bookmark
1310 is not set."
1311 :group 'org-structure
1312 :type 'plist)
1314 (defgroup org-cycle nil
1315 "Options concerning visibility cycling in Org-mode."
1316 :tag "Org Cycle"
1317 :group 'org-structure)
1319 (defcustom org-cycle-skip-children-state-if-no-children t
1320 "Non-nil means skip CHILDREN state in entries that don't have any."
1321 :group 'org-cycle
1322 :type 'boolean)
1324 (defcustom org-cycle-max-level nil
1325 "Maximum level which should still be subject to visibility cycling.
1326 Levels higher than this will, for cycling, be treated as text, not a headline.
1327 When `org-odd-levels-only' is set, a value of N in this variable actually
1328 means 2N-1 stars as the limiting headline.
1329 When nil, cycle all levels.
1330 Note that the limiting level of cycling is also influenced by
1331 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1332 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1333 than its value."
1334 :group 'org-cycle
1335 :type '(choice
1336 (const :tag "No limit" nil)
1337 (integer :tag "Maximum level")))
1339 (defcustom org-hide-block-startup nil
1340 "Non-nil means entering Org-mode will fold all blocks.
1341 This can also be set in on a per-file basis with
1343 #+STARTUP: hideblocks
1344 #+STARTUP: showblocks"
1345 :group 'org-startup
1346 :group 'org-cycle
1347 :type 'boolean)
1349 (defcustom org-cycle-global-at-bob nil
1350 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1351 This makes it possible to do global cycling without having to use S-TAB or
1352 \\[universal-argument] TAB. For this special case to work, the first line
1353 of the buffer must not be a headline -- it may be empty or some other text.
1354 When used in this way, `org-cycle-hook' is disabled temporarily to make
1355 sure the cursor stays at the beginning of the buffer. When this option is
1356 nil, don't do anything special at the beginning of the buffer."
1357 :group 'org-cycle
1358 :type 'boolean)
1360 (defcustom org-cycle-level-after-item/entry-creation t
1361 "Non-nil means cycle entry level or item indentation in new empty entries.
1363 When the cursor is at the end of an empty headline, i.e., with only stars
1364 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1365 and then all possible ancestor states, before returning to the original state.
1366 This makes data entry extremely fast: M-RET to create a new headline,
1367 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1369 When the cursor is at the end of an empty plain list item, one TAB will
1370 make it a subitem, two or more tabs will back up to make this an item
1371 higher up in the item hierarchy."
1372 :group 'org-cycle
1373 :type 'boolean)
1375 (defcustom org-cycle-emulate-tab t
1376 "Where should `org-cycle' emulate TAB.
1377 nil Never
1378 white Only in completely white lines
1379 whitestart Only at the beginning of lines, before the first non-white char
1380 t Everywhere except in headlines
1381 exc-hl-bol Everywhere except at the start of a headline
1382 If TAB is used in a place where it does not emulate TAB, the current subtree
1383 visibility is cycled."
1384 :group 'org-cycle
1385 :type '(choice (const :tag "Never" nil)
1386 (const :tag "Only in completely white lines" white)
1387 (const :tag "Before first char in a line" whitestart)
1388 (const :tag "Everywhere except in headlines" t)
1389 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1391 (defcustom org-cycle-separator-lines 2
1392 "Number of empty lines needed to keep an empty line between collapsed trees.
1393 If you leave an empty line between the end of a subtree and the following
1394 headline, this empty line is hidden when the subtree is folded.
1395 Org-mode will leave (exactly) one empty line visible if the number of
1396 empty lines is equal or larger to the number given in this variable.
1397 So the default 2 means at least 2 empty lines after the end of a subtree
1398 are needed to produce free space between a collapsed subtree and the
1399 following headline.
1401 If the number is negative, and the number of empty lines is at least -N,
1402 all empty lines are shown.
1404 Special case: when 0, never leave empty lines in collapsed view."
1405 :group 'org-cycle
1406 :type 'integer)
1407 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1409 (defcustom org-pre-cycle-hook nil
1410 "Hook that is run before visibility cycling is happening.
1411 The function(s) in this hook must accept a single argument which indicates
1412 the new state that will be set right after running this hook. The
1413 argument is a symbol. Before a global state change, it can have the values
1414 `overview', `content', or `all'. Before a local state change, it can have
1415 the values `folded', `children', or `subtree'."
1416 :group 'org-cycle
1417 :type 'hook)
1419 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1420 org-cycle-hide-drawers
1421 org-cycle-show-empty-lines
1422 org-optimize-window-after-visibility-change)
1423 "Hook that is run after `org-cycle' has changed the buffer visibility.
1424 The function(s) in this hook must accept a single argument which indicates
1425 the new state that was set by the most recent `org-cycle' command. The
1426 argument is a symbol. After a global state change, it can have the values
1427 `overview', `contents', or `all'. After a local state change, it can have
1428 the values `folded', `children', or `subtree'."
1429 :group 'org-cycle
1430 :type 'hook
1431 :version "25.1"
1432 :package-version '(Org . "8.3"))
1434 (defgroup org-edit-structure nil
1435 "Options concerning structure editing in Org-mode."
1436 :tag "Org Edit Structure"
1437 :group 'org-structure)
1439 (defcustom org-odd-levels-only nil
1440 "Non-nil means skip even levels and only use odd levels for the outline.
1441 This has the effect that two stars are being added/taken away in
1442 promotion/demotion commands. It also influences how levels are
1443 handled by the exporters.
1444 Changing it requires restart of `font-lock-mode' to become effective
1445 for fontification also in regions already fontified.
1446 You may also set this on a per-file basis by adding one of the following
1447 lines to the buffer:
1449 #+STARTUP: odd
1450 #+STARTUP: oddeven"
1451 :group 'org-edit-structure
1452 :group 'org-appearance
1453 :type 'boolean)
1455 (defcustom org-adapt-indentation t
1456 "Non-nil means adapt indentation to outline node level.
1458 When this variable is set, Org assumes that you write outlines by
1459 indenting text in each node to align with the headline (after the
1460 stars). The following issues are influenced by this variable:
1462 - The indentation is increased by one space in a demotion
1463 command, and decreased by one in a promotion command. However,
1464 in the latter case, if shifting some line in the entry body
1465 would alter document structure (e.g., insert a new headline),
1466 indentation is not changed at all.
1468 - Property drawers and planning information is inserted indented
1469 when this variable is set. When nil, they will not be indented.
1471 - TAB indents a line relative to current level. The lines below
1472 a headline will be indented when this variable is set.
1474 Note that this is all about true indentation, by adding and
1475 removing space characters. See also `org-indent.el' which does
1476 level-dependent indentation in a virtual way, i.e. at display
1477 time in Emacs."
1478 :group 'org-edit-structure
1479 :type 'boolean)
1481 (defcustom org-special-ctrl-a/e nil
1482 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1484 When t, `C-a' will bring back the cursor to the beginning of the
1485 headline text, i.e. after the stars and after a possible TODO
1486 keyword. In an item, this will be the position after bullet and
1487 check-box, if any. When the cursor is already at that position,
1488 another `C-a' will bring it to the beginning of the line.
1490 `C-e' will jump to the end of the headline, ignoring the presence
1491 of tags in the headline. A second `C-e' will then jump to the
1492 true end of the line, after any tags. This also means that, when
1493 this variable is non-nil, `C-e' also will never jump beyond the
1494 end of the heading of a folded section, i.e. not after the
1495 ellipses.
1497 When set to the symbol `reversed', the first `C-a' or `C-e' works
1498 normally, going to the true line boundary first. Only a directly
1499 following, identical keypress will bring the cursor to the
1500 special positions.
1502 This may also be a cons cell where the behavior for `C-a' and
1503 `C-e' is set separately."
1504 :group 'org-edit-structure
1505 :type '(choice
1506 (const :tag "off" nil)
1507 (const :tag "on: after stars/bullet and before tags first" t)
1508 (const :tag "reversed: true line boundary first" reversed)
1509 (cons :tag "Set C-a and C-e separately"
1510 (choice :tag "Special C-a"
1511 (const :tag "off" nil)
1512 (const :tag "on: after stars/bullet first" t)
1513 (const :tag "reversed: before stars/bullet first" reversed))
1514 (choice :tag "Special C-e"
1515 (const :tag "off" nil)
1516 (const :tag "on: before tags first" t)
1517 (const :tag "reversed: after tags first" reversed)))))
1518 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1520 (defcustom org-special-ctrl-k nil
1521 "Non-nil means `C-k' will behave specially in headlines.
1522 When nil, `C-k' will call the default `kill-line' command.
1523 When t, the following will happen while the cursor is in the headline:
1525 - When the cursor is at the beginning of a headline, kill the entire
1526 line and possible the folded subtree below the line.
1527 - When in the middle of the headline text, kill the headline up to the tags.
1528 - When after the headline text, kill the tags."
1529 :group 'org-edit-structure
1530 :type 'boolean)
1532 (defcustom org-ctrl-k-protect-subtree nil
1533 "Non-nil means, do not delete a hidden subtree with C-k.
1534 When set to the symbol `error', simply throw an error when C-k is
1535 used to kill (part-of) a headline that has hidden text behind it.
1536 Any other non-nil value will result in a query to the user, if it is
1537 OK to kill that hidden subtree. When nil, kill without remorse."
1538 :group 'org-edit-structure
1539 :version "24.1"
1540 :type '(choice
1541 (const :tag "Do not protect hidden subtrees" nil)
1542 (const :tag "Protect hidden subtrees with a security query" t)
1543 (const :tag "Never kill a hidden subtree with C-k" error)))
1545 (defcustom org-special-ctrl-o t
1546 "Non-nil means, make `C-o' insert a row in tables."
1547 :group 'org-edit-structure
1548 :type 'boolean)
1550 (defcustom org-catch-invisible-edits nil
1551 "Check if in invisible region before inserting or deleting a character.
1552 Valid values are:
1554 nil Do not check, so just do invisible edits.
1555 error Throw an error and do nothing.
1556 show Make point visible, and do the requested edit.
1557 show-and-error Make point visible, then throw an error and abort the edit.
1558 smart Make point visible, and do insertion/deletion if it is
1559 adjacent to visible text and the change feels predictable.
1560 Never delete a previously invisible character or add in the
1561 middle or right after an invisible region. Basically, this
1562 allows insertion and backward-delete right before ellipses.
1563 FIXME: maybe in this case we should not even show?"
1564 :group 'org-edit-structure
1565 :version "24.1"
1566 :type '(choice
1567 (const :tag "Do not check" nil)
1568 (const :tag "Throw error when trying to edit" error)
1569 (const :tag "Unhide, but do not do the edit" show-and-error)
1570 (const :tag "Show invisible part and do the edit" show)
1571 (const :tag "Be smart and do the right thing" smart)))
1573 (defcustom org-yank-folded-subtrees t
1574 "Non-nil means when yanking subtrees, fold them.
1575 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1576 it starts with a heading and all other headings in it are either children
1577 or siblings, then fold all the subtrees. However, do this only if no
1578 text after the yank would be swallowed into a folded tree by this action."
1579 :group 'org-edit-structure
1580 :type 'boolean)
1582 (defcustom org-yank-adjusted-subtrees nil
1583 "Non-nil means when yanking subtrees, adjust the level.
1584 With this setting, `org-paste-subtree' is used to insert the subtree, see
1585 this function for details."
1586 :group 'org-edit-structure
1587 :type 'boolean)
1589 (defcustom org-M-RET-may-split-line '((default . t))
1590 "Non-nil means M-RET will split the line at the cursor position.
1591 When nil, it will go to the end of the line before making a
1592 new line.
1593 You may also set this option in a different way for different
1594 contexts. Valid contexts are:
1596 headline when creating a new headline
1597 item when creating a new item
1598 table in a table field
1599 default the value to be used for all contexts not explicitly
1600 customized"
1601 :group 'org-structure
1602 :group 'org-table
1603 :type '(choice
1604 (const :tag "Always" t)
1605 (const :tag "Never" nil)
1606 (repeat :greedy t :tag "Individual contexts"
1607 (cons
1608 (choice :tag "Context"
1609 (const headline)
1610 (const item)
1611 (const table)
1612 (const default))
1613 (boolean)))))
1616 (defcustom org-insert-heading-respect-content nil
1617 "Non-nil means insert new headings after the current subtree.
1618 When nil, the new heading is created directly after the current line.
1619 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1620 this variable on for the duration of the command."
1621 :group 'org-structure
1622 :type 'boolean)
1624 (defcustom org-blank-before-new-entry '((heading . auto)
1625 (plain-list-item . auto))
1626 "Should `org-insert-heading' leave a blank line before new heading/item?
1627 The value is an alist, with `heading' and `plain-list-item' as CAR,
1628 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1629 which case Org will look at the surrounding headings/items and try to
1630 make an intelligent decision whether to insert a blank line or not."
1631 :group 'org-edit-structure
1632 :type '(list
1633 (cons (const heading)
1634 (choice (const :tag "Never" nil)
1635 (const :tag "Always" t)
1636 (const :tag "Auto" auto)))
1637 (cons (const plain-list-item)
1638 (choice (const :tag "Never" nil)
1639 (const :tag "Always" t)
1640 (const :tag "Auto" auto)))))
1642 (defcustom org-insert-heading-hook nil
1643 "Hook being run after inserting a new heading."
1644 :group 'org-edit-structure
1645 :type 'hook)
1647 (defcustom org-enable-fixed-width-editor t
1648 "Non-nil means lines starting with \":\" are treated as fixed-width.
1649 This currently only means they are never auto-wrapped.
1650 When nil, such lines will be treated like ordinary lines."
1651 :group 'org-edit-structure
1652 :type 'boolean)
1654 (defcustom org-goto-auto-isearch t
1655 "Non-nil means typing characters in `org-goto' starts incremental search.
1656 When nil, you can use these keybindings to navigate the buffer:
1658 q Quit the org-goto interface
1659 n Go to the next visible heading
1660 p Go to the previous visible heading
1661 f Go one heading forward on same level
1662 b Go one heading backward on same level
1663 u Go one heading up"
1664 :group 'org-edit-structure
1665 :type 'boolean)
1667 (defgroup org-sparse-trees nil
1668 "Options concerning sparse trees in Org-mode."
1669 :tag "Org Sparse Trees"
1670 :group 'org-structure)
1672 (defcustom org-highlight-sparse-tree-matches t
1673 "Non-nil means highlight all matches that define a sparse tree.
1674 The highlights will automatically disappear the next time the buffer is
1675 changed by an edit command."
1676 :group 'org-sparse-trees
1677 :type 'boolean)
1679 (defcustom org-remove-highlights-with-change t
1680 "Non-nil means any change to the buffer will remove temporary highlights.
1681 \\<org-mode-map>\
1682 Such highlights are created by `org-occur' and `org-clock-display'.
1683 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1684 to get rid of the highlights.
1685 The highlights created by `org-toggle-latex-fragment' always need
1686 `\\[org-toggle-latex-fragment]' to be removed."
1687 :group 'org-sparse-trees
1688 :group 'org-time
1689 :type 'boolean)
1692 (defcustom org-occur-hook '(org-first-headline-recenter)
1693 "Hook that is run after `org-occur' has constructed a sparse tree.
1694 This can be used to recenter the window to show as much of the structure
1695 as possible."
1696 :group 'org-sparse-trees
1697 :type 'hook)
1699 (defgroup org-imenu-and-speedbar nil
1700 "Options concerning imenu and speedbar in Org-mode."
1701 :tag "Org Imenu and Speedbar"
1702 :group 'org-structure)
1704 (defcustom org-imenu-depth 2
1705 "The maximum level for Imenu access to Org-mode headlines.
1706 This also applied for speedbar access."
1707 :group 'org-imenu-and-speedbar
1708 :type 'integer)
1710 (defgroup org-table nil
1711 "Options concerning tables in Org-mode."
1712 :tag "Org Table"
1713 :group 'org)
1715 (defcustom org-enable-table-editor 'optimized
1716 "Non-nil means lines starting with \"|\" are handled by the table editor.
1717 When nil, such lines will be treated like ordinary lines.
1719 When equal to the symbol `optimized', the table editor will be optimized to
1720 do the following:
1721 - Automatic overwrite mode in front of whitespace in table fields.
1722 This makes the structure of the table stay in tact as long as the edited
1723 field does not exceed the column width.
1724 - Minimize the number of realigns. Normally, the table is aligned each time
1725 TAB or RET are pressed to move to another field. With optimization this
1726 happens only if changes to a field might have changed the column width.
1727 Optimization requires replacing the functions `self-insert-command',
1728 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1729 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1730 very good at guessing when a re-align will be necessary, but you can always
1731 force one with \\[org-ctrl-c-ctrl-c].
1733 If you would like to use the optimized version in Org-mode, but the
1734 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1736 This variable can be used to turn on and off the table editor during a session,
1737 but in order to toggle optimization, a restart is required.
1739 See also the variable `org-table-auto-blank-field'."
1740 :group 'org-table
1741 :type '(choice
1742 (const :tag "off" nil)
1743 (const :tag "on" t)
1744 (const :tag "on, optimized" optimized)))
1746 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1747 (version<= emacs-version "24.1"))
1748 "Non-nil means cluster self-insert commands for undo when possible.
1749 If this is set, then, like in the Emacs command loop, 20 consecutive
1750 characters will be undone together.
1751 This is configurable, because there is some impact on typing performance."
1752 :group 'org-table
1753 :type 'boolean)
1755 (defcustom org-table-tab-recognizes-table.el t
1756 "Non-nil means TAB will automatically notice a table.el table.
1757 When it sees such a table, it moves point into it and - if necessary -
1758 calls `table-recognize-table'."
1759 :group 'org-table-editing
1760 :type 'boolean)
1762 (defgroup org-link nil
1763 "Options concerning links in Org-mode."
1764 :tag "Org Link"
1765 :group 'org)
1767 (defvar org-link-abbrev-alist-local nil
1768 "Buffer-local version of `org-link-abbrev-alist', which see.
1769 The value of this is taken from the #+LINK lines.")
1770 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1772 (defcustom org-link-abbrev-alist nil
1773 "Alist of link abbreviations.
1774 The car of each element is a string, to be replaced at the start of a link.
1775 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1776 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1778 [[linkkey:tag][description]]
1780 The `linkkey' must be a word word, starting with a letter, followed
1781 by letters, numbers, `-' or `_'.
1783 If REPLACE is a string, the tag will simply be appended to create the link.
1784 If the string contains \"%s\", the tag will be inserted there. If the string
1785 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1786 at that point (see the function `url-hexify-string'). If the string contains
1787 the specifier \"%(my-function)\", then the custom function `my-function' will
1788 be invoked: this function takes the tag as its only argument and must return
1789 a string.
1791 REPLACE may also be a function that will be called with the tag as the
1792 only argument to create the link, which should be returned as a string.
1794 See the manual for examples."
1795 :group 'org-link
1796 :type '(repeat
1797 (cons
1798 (string :tag "Protocol")
1799 (choice
1800 (string :tag "Format")
1801 (function)))))
1803 (defcustom org-descriptive-links t
1804 "Non-nil means Org will display descriptive links.
1805 E.g. [[http://orgmode.org][Org website]] will be displayed as
1806 \"Org Website\", hiding the link itself and just displaying its
1807 description. When set to nil, Org will display the full links
1808 literally.
1810 You can interactively set the value of this variable by calling
1811 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1812 :group 'org-link
1813 :type 'boolean)
1815 (defcustom org-link-file-path-type 'adaptive
1816 "How the path name in file links should be stored.
1817 Valid values are:
1819 relative Relative to the current directory, i.e. the directory of the file
1820 into which the link is being inserted.
1821 absolute Absolute path, if possible with ~ for home directory.
1822 noabbrev Absolute path, no abbreviation of home directory.
1823 adaptive Use relative path for files in the current directory and sub-
1824 directories of it. For other files, use an absolute path."
1825 :group 'org-link
1826 :type '(choice
1827 (const relative)
1828 (const absolute)
1829 (const noabbrev)
1830 (const adaptive)))
1832 (defvaralias 'org-activate-links 'org-highlight-links)
1833 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1834 "Types of links that should be highlighted in Org-mode files.
1836 This is a list of symbols, each one of them leading to the
1837 highlighting of a certain link type.
1839 You can still open links that are not highlighted.
1841 In principle, it does not hurt to turn on highlighting for all
1842 link types. There may be a small gain when turning off unused
1843 link types. The types are:
1845 bracket The recommended [[link][description]] or [[link]] links with hiding.
1846 angle Links in angular brackets that may contain whitespace like
1847 <bbdb:Carsten Dominik>.
1848 plain Plain links in normal text, no whitespace, like http://google.com.
1849 radio Text that is matched by a radio target, see manual for details.
1850 tag Tag settings in a headline (link to tag search).
1851 date Time stamps (link to calendar).
1852 footnote Footnote labels.
1854 If you set this variable during an Emacs session, use `org-mode-restart'
1855 in the Org buffer so that the change takes effect."
1856 :group 'org-link
1857 :group 'org-appearance
1858 :type '(set :greedy t
1859 (const :tag "Double bracket links" bracket)
1860 (const :tag "Angular bracket links" angle)
1861 (const :tag "Plain text links" plain)
1862 (const :tag "Radio target matches" radio)
1863 (const :tag "Tags" tag)
1864 (const :tag "Timestamps" date)
1865 (const :tag "Footnotes" footnote)))
1867 (defcustom org-make-link-description-function nil
1868 "Function to use for generating link descriptions from links.
1869 When nil, the link location will be used. This function must take
1870 two parameters: the first one is the link, the second one is the
1871 description generated by `org-insert-link'. The function should
1872 return the description to use."
1873 :group 'org-link
1874 :type '(choice (const nil) (function)))
1876 (defgroup org-link-store nil
1877 "Options concerning storing links in Org-mode."
1878 :tag "Org Store Link"
1879 :group 'org-link)
1881 (defcustom org-url-hexify-p t
1882 "When non-nil, hexify URL when creating a link."
1883 :type 'boolean
1884 :version "24.3"
1885 :group 'org-link-store)
1887 (defcustom org-email-link-description-format "Email %c: %.30s"
1888 "Format of the description part of a link to an email or usenet message.
1889 The following %-escapes will be replaced by corresponding information:
1891 %F full \"From\" field
1892 %f name, taken from \"From\" field, address if no name
1893 %T full \"To\" field
1894 %t first name in \"To\" field, address if no name
1895 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1896 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1897 %s subject
1898 %d date
1899 %m message-id.
1901 You may use normal field width specification between the % and the letter.
1902 This is for example useful to limit the length of the subject.
1904 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1905 :group 'org-link-store
1906 :type 'string)
1908 (defcustom org-from-is-user-regexp
1909 (let (r1 r2)
1910 (when (and user-mail-address (not (string= user-mail-address "")))
1911 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1912 (when (and user-full-name (not (string= user-full-name "")))
1913 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1914 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1915 "Regexp matched against the \"From:\" header of an email or usenet message.
1916 It should match if the message is from the user him/herself."
1917 :group 'org-link-store
1918 :type 'regexp)
1920 (defcustom org-context-in-file-links t
1921 "Non-nil means file links from `org-store-link' contain context.
1922 A search string will be added to the file name with :: as separator and
1923 used to find the context when the link is activated by the command
1924 `org-open-at-point'. When this option is t, the entire active region
1925 will be placed in the search string of the file link. If set to a
1926 positive integer, only the first n lines of context will be stored.
1928 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1929 negates this setting for the duration of the command."
1930 :group 'org-link-store
1931 :type '(choice boolean integer))
1933 (defcustom org-keep-stored-link-after-insertion nil
1934 "Non-nil means keep link in list for entire session.
1936 The command `org-store-link' adds a link pointing to the current
1937 location to an internal list. These links accumulate during a session.
1938 The command `org-insert-link' can be used to insert links into any
1939 Org-mode file (offering completion for all stored links). When this
1940 option is nil, every link which has been inserted once using \\[org-insert-link]
1941 will be removed from the list, to make completing the unused links
1942 more efficient."
1943 :group 'org-link-store
1944 :type 'boolean)
1946 (defgroup org-link-follow nil
1947 "Options concerning following links in Org-mode."
1948 :tag "Org Follow Link"
1949 :group 'org-link)
1951 (defcustom org-link-translation-function nil
1952 "Function to translate links with different syntax to Org syntax.
1953 This can be used to translate links created for example by the Planner
1954 or emacs-wiki packages to Org syntax.
1955 The function must accept two parameters, a TYPE containing the link
1956 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1957 which is everything after the link protocol. It should return a cons
1958 with possibly modified values of type and path.
1959 Org contains a function for this, so if you set this variable to
1960 `org-translate-link-from-planner', you should be able follow many
1961 links created by planner."
1962 :group 'org-link-follow
1963 :type '(choice (const nil) (function)))
1965 (defcustom org-follow-link-hook nil
1966 "Hook that is run after a link has been followed."
1967 :group 'org-link-follow
1968 :type 'hook)
1970 (defcustom org-tab-follows-link nil
1971 "Non-nil means on links TAB will follow the link.
1972 Needs to be set before org.el is loaded.
1973 This really should not be used, it does not make sense, and the
1974 implementation is bad."
1975 :group 'org-link-follow
1976 :type 'boolean)
1978 (defcustom org-return-follows-link nil
1979 "Non-nil means on links RET will follow the link.
1980 In tables, the special behavior of RET has precedence."
1981 :group 'org-link-follow
1982 :type 'boolean)
1984 (defcustom org-mouse-1-follows-link
1985 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1986 "Non-nil means mouse-1 on a link will follow the link.
1987 A longer mouse click will still set point. Does not work on XEmacs.
1988 Needs to be set before org.el is loaded."
1989 :group 'org-link-follow
1990 :version "24.4"
1991 :package-version '(Org . "8.3")
1992 :type '(choice
1993 (const :tag "A double click follows the link" double)
1994 (const :tag "Unconditionally follow the link with mouse-1" t)
1995 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1997 (defcustom org-mark-ring-length 4
1998 "Number of different positions to be recorded in the ring.
1999 Changing this requires a restart of Emacs to work correctly."
2000 :group 'org-link-follow
2001 :type 'integer)
2003 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2004 "Non-nil means internal links in Org files must exactly match a headline.
2005 When nil, the link search tries to match a phrase with all words
2006 in the search text."
2007 :group 'org-link-follow
2008 :version "24.1"
2009 :type '(choice
2010 (const :tag "Use fuzzy text search" nil)
2011 (const :tag "Match only exact headline" t)
2012 (const :tag "Match exact headline or query to create it"
2013 query-to-create)))
2015 (defcustom org-link-frame-setup
2016 '((vm . vm-visit-folder-other-frame)
2017 (vm-imap . vm-visit-imap-folder-other-frame)
2018 (gnus . org-gnus-no-new-news)
2019 (file . find-file-other-window)
2020 (wl . wl-other-frame))
2021 "Setup the frame configuration for following links.
2022 When following a link with Emacs, it may often be useful to display
2023 this link in another window or frame. This variable can be used to
2024 set this up for the different types of links.
2025 For VM, use any of
2026 `vm-visit-folder'
2027 `vm-visit-folder-other-window'
2028 `vm-visit-folder-other-frame'
2029 For Gnus, use any of
2030 `gnus'
2031 `gnus-other-frame'
2032 `org-gnus-no-new-news'
2033 For FILE, use any of
2034 `find-file'
2035 `find-file-other-window'
2036 `find-file-other-frame'
2037 For Wanderlust use any of
2038 `wl'
2039 `wl-other-frame'
2040 For the calendar, use the variable `calendar-setup'.
2041 For BBDB, it is currently only possible to display the matches in
2042 another window."
2043 :group 'org-link-follow
2044 :type '(list
2045 (cons (const vm)
2046 (choice
2047 (const vm-visit-folder)
2048 (const vm-visit-folder-other-window)
2049 (const vm-visit-folder-other-frame)))
2050 (cons (const vm-imap)
2051 (choice
2052 (const vm-visit-imap-folder)
2053 (const vm-visit-imap-folder-other-window)
2054 (const vm-visit-imap-folder-other-frame)))
2055 (cons (const gnus)
2056 (choice
2057 (const gnus)
2058 (const gnus-other-frame)
2059 (const org-gnus-no-new-news)))
2060 (cons (const file)
2061 (choice
2062 (const find-file)
2063 (const find-file-other-window)
2064 (const find-file-other-frame)))
2065 (cons (const wl)
2066 (choice
2067 (const wl)
2068 (const wl-other-frame)))))
2070 (defcustom org-display-internal-link-with-indirect-buffer nil
2071 "Non-nil means use indirect buffer to display infile links.
2072 Activating internal links (from one location in a file to another location
2073 in the same file) normally just jumps to the location. When the link is
2074 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2075 is displayed in
2076 another window. When this option is set, the other window actually displays
2077 an indirect buffer clone of the current buffer, to avoid any visibility
2078 changes to the current buffer."
2079 :group 'org-link-follow
2080 :type 'boolean)
2082 (defcustom org-open-non-existing-files nil
2083 "Non-nil means `org-open-file' will open non-existing files.
2084 When nil, an error will be generated.
2085 This variable applies only to external applications because they
2086 might choke on non-existing files. If the link is to a file that
2087 will be opened in Emacs, the variable is ignored."
2088 :group 'org-link-follow
2089 :type 'boolean)
2091 (defcustom org-open-directory-means-index-dot-org nil
2092 "Non-nil means a link to a directory really means to index.org.
2093 When nil, following a directory link will run dired or open a finder/explorer
2094 window on that directory."
2095 :group 'org-link-follow
2096 :type 'boolean)
2098 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2099 "Non-nil means ask for confirmation before executing shell links.
2100 Shell links can be dangerous: just think about a link
2102 [[shell:rm -rf ~/*][Google Search]]
2104 This link would show up in your Org-mode document as \"Google Search\",
2105 but really it would remove your entire home directory.
2106 Therefore we advise against setting this variable to nil.
2107 Just change it to `y-or-n-p' if you want to confirm with a
2108 single keystroke rather than having to type \"yes\"."
2109 :group 'org-link-follow
2110 :type '(choice
2111 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2112 (const :tag "with y-or-n (faster)" y-or-n-p)
2113 (const :tag "no confirmation (dangerous)" nil)))
2114 (put 'org-confirm-shell-link-function
2115 'safe-local-variable
2116 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2118 (defcustom org-confirm-shell-link-not-regexp ""
2119 "A regexp to skip confirmation for shell links."
2120 :group 'org-link-follow
2121 :version "24.1"
2122 :type 'regexp)
2124 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2125 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2126 Elisp links can be dangerous: just think about a link
2128 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2130 This link would show up in your Org-mode document as \"Google Search\",
2131 but really it would remove your entire home directory.
2132 Therefore we advise against setting this variable to nil.
2133 Just change it to `y-or-n-p' if you want to confirm with a
2134 single keystroke rather than having to type \"yes\"."
2135 :group 'org-link-follow
2136 :type '(choice
2137 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2138 (const :tag "with y-or-n (faster)" y-or-n-p)
2139 (const :tag "no confirmation (dangerous)" nil)))
2140 (put 'org-confirm-shell-link-function
2141 'safe-local-variable
2142 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2144 (defcustom org-confirm-elisp-link-not-regexp ""
2145 "A regexp to skip confirmation for Elisp links."
2146 :group 'org-link-follow
2147 :version "24.1"
2148 :type 'regexp)
2150 (defconst org-file-apps-defaults-gnu
2151 '((remote . emacs)
2152 (system . mailcap)
2153 (t . mailcap))
2154 "Default file applications on a UNIX or GNU/Linux system.
2155 See `org-file-apps'.")
2157 (defconst org-file-apps-defaults-macosx
2158 '((remote . emacs)
2159 (t . "open %s")
2160 (system . "open %s")
2161 ("ps.gz" . "gv %s")
2162 ("eps.gz" . "gv %s")
2163 ("dvi" . "xdvi %s")
2164 ("fig" . "xfig %s"))
2165 "Default file applications on a MacOS X system.
2166 The system \"open\" is known as a default, but we use X11 applications
2167 for some files for which the OS does not have a good default.
2168 See `org-file-apps'.")
2170 (defconst org-file-apps-defaults-windowsnt
2171 (list
2172 '(remote . emacs)
2173 (cons t
2174 (list (if (featurep 'xemacs)
2175 'mswindows-shell-execute
2176 'w32-shell-execute)
2177 "open" 'file))
2178 (cons 'system
2179 (list (if (featurep 'xemacs)
2180 'mswindows-shell-execute
2181 'w32-shell-execute)
2182 "open" 'file)))
2183 "Default file applications on a Windows NT system.
2184 The system \"open\" is used for most files.
2185 See `org-file-apps'.")
2187 (defcustom org-file-apps
2188 '((auto-mode . emacs)
2189 ("\\.mm\\'" . default)
2190 ("\\.x?html?\\'" . default)
2191 ("\\.pdf\\'" . default))
2192 "External applications for opening `file:path' items in a document.
2193 Org-mode uses system defaults for different file types, but
2194 you can use this variable to set the application for a given file
2195 extension. The entries in this list are cons cells where the car identifies
2196 files and the cdr the corresponding command. Possible values for the
2197 file identifier are
2198 \"string\" A string as a file identifier can be interpreted in different
2199 ways, depending on its contents:
2201 - Alphanumeric characters only:
2202 Match links with this file extension.
2203 Example: (\"pdf\" . \"evince %s\")
2204 to open PDFs with evince.
2206 - Regular expression: Match links where the
2207 filename matches the regexp. If you want to
2208 use groups here, use shy groups.
2210 Example: (\"\\.x?html\\\\='\" . \"firefox %s\")
2211 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2212 to open *.html and *.xhtml with firefox.
2214 - Regular expression which contains (non-shy) groups:
2215 Match links where the whole link, including \"::\", and
2216 anything after that, matches the regexp.
2217 In a custom command string, %1, %2, etc. are replaced with
2218 the parts of the link that were matched by the groups.
2219 For backwards compatibility, if a command string is given
2220 that does not use any of the group matches, this case is
2221 handled identically to the second one (i.e. match against
2222 file name only).
2223 In a custom lisp form, you can access the group matches with
2224 (match-string n link).
2226 Example: (\"\\.pdf::\\(\\d+\\)\\\\='\" . \"evince -p %1 %s\")
2227 to open [[file:document.pdf::5]] with evince at page 5.
2229 `directory' Matches a directory
2230 `remote' Matches a remote file, accessible through tramp or efs.
2231 Remote files most likely should be visited through Emacs
2232 because external applications cannot handle such paths.
2233 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2234 so all files Emacs knows how to handle. Using this with
2235 command `emacs' will open most files in Emacs. Beware that this
2236 will also open html files inside Emacs, unless you add
2237 (\"html\" . default) to the list as well.
2238 t Default for files not matched by any of the other options.
2239 `system' The system command to open files, like `open' on Windows
2240 and Mac OS X, and mailcap under GNU/Linux. This is the command
2241 that will be selected if you call `C-c C-o' with a double
2242 \\[universal-argument] \\[universal-argument] prefix.
2244 Possible values for the command are:
2245 `emacs' The file will be visited by the current Emacs process.
2246 `default' Use the default application for this file type, which is the
2247 association for t in the list, most likely in the system-specific
2248 part.
2249 This can be used to overrule an unwanted setting in the
2250 system-specific variable.
2251 `system' Use the system command for opening files, like \"open\".
2252 This command is specified by the entry whose car is `system'.
2253 Most likely, the system-specific version of this variable
2254 does define this command, but you can overrule/replace it
2255 here.
2256 string A command to be executed by a shell; %s will be replaced
2257 by the path to the file.
2258 sexp A Lisp form which will be evaluated. The file path will
2259 be available in the Lisp variable `file'.
2260 For more examples, see the system specific constants
2261 `org-file-apps-defaults-macosx'
2262 `org-file-apps-defaults-windowsnt'
2263 `org-file-apps-defaults-gnu'."
2264 :group 'org-link-follow
2265 :type '(repeat
2266 (cons (choice :value ""
2267 (string :tag "Extension")
2268 (const :tag "System command to open files" system)
2269 (const :tag "Default for unrecognized files" t)
2270 (const :tag "Remote file" remote)
2271 (const :tag "Links to a directory" directory)
2272 (const :tag "Any files that have Emacs modes"
2273 auto-mode))
2274 (choice :value ""
2275 (const :tag "Visit with Emacs" emacs)
2276 (const :tag "Use default" default)
2277 (const :tag "Use the system command" system)
2278 (string :tag "Command")
2279 (sexp :tag "Lisp form")))))
2281 (defcustom org-doi-server-url "http://dx.doi.org/"
2282 "The URL of the DOI server."
2283 :type 'string
2284 :version "24.3"
2285 :group 'org-link-follow)
2287 (defgroup org-refile nil
2288 "Options concerning refiling entries in Org-mode."
2289 :tag "Org Refile"
2290 :group 'org)
2292 (defcustom org-directory "~/org"
2293 "Directory with org files.
2294 This is just a default location to look for Org files. There is no need
2295 at all to put your files into this directory. It is only used in the
2296 following situations:
2298 1. When a capture template specifies a target file that is not an
2299 absolute path. The path will then be interpreted relative to
2300 `org-directory'
2301 2. When a capture note is filed away in an interactive way (when exiting the
2302 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2303 with `org-directory' as the default path."
2304 :group 'org-refile
2305 :group 'org-capture
2306 :type 'directory)
2308 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2309 "Default target for storing notes.
2310 Used as a fall back file for org-capture.el, for templates that
2311 do not specify a target file."
2312 :group 'org-refile
2313 :group 'org-capture
2314 :type 'file)
2316 (defcustom org-goto-interface 'outline
2317 "The default interface to be used for `org-goto'.
2318 Allowed values are:
2319 outline The interface shows an outline of the relevant file
2320 and the correct heading is found by moving through
2321 the outline or by searching with incremental search.
2322 outline-path-completion Headlines in the current buffer are offered via
2323 completion. This is the interface also used by
2324 the refile command."
2325 :group 'org-refile
2326 :type '(choice
2327 (const :tag "Outline" outline)
2328 (const :tag "Outline-path-completion" outline-path-completion)))
2330 (defcustom org-goto-max-level 5
2331 "Maximum target level when running `org-goto' with refile interface."
2332 :group 'org-refile
2333 :type 'integer)
2335 (defcustom org-reverse-note-order nil
2336 "Non-nil means store new notes at the beginning of a file or entry.
2337 When nil, new notes will be filed to the end of a file or entry.
2338 This can also be a list with cons cells of regular expressions that
2339 are matched against file names, and values."
2340 :group 'org-capture
2341 :group 'org-refile
2342 :type '(choice
2343 (const :tag "Reverse always" t)
2344 (const :tag "Reverse never" nil)
2345 (repeat :tag "By file name regexp"
2346 (cons regexp boolean))))
2348 (defcustom org-log-refile nil
2349 "Information to record when a task is refiled.
2351 Possible values are:
2353 nil Don't add anything
2354 time Add a time stamp to the task
2355 note Prompt for a note and add it with template `org-log-note-headings'
2357 This option can also be set with on a per-file-basis with
2359 #+STARTUP: nologrefile
2360 #+STARTUP: logrefile
2361 #+STARTUP: lognoterefile
2363 You can have local logging settings for a subtree by setting the LOGGING
2364 property to one or more of these keywords.
2366 When bulk-refiling from the agenda, the value `note' is forbidden and
2367 will temporarily be changed to `time'."
2368 :group 'org-refile
2369 :group 'org-progress
2370 :version "24.1"
2371 :type '(choice
2372 (const :tag "No logging" nil)
2373 (const :tag "Record timestamp" time)
2374 (const :tag "Record timestamp with note." note)))
2376 (defcustom org-refile-targets nil
2377 "Targets for refiling entries with \\[org-refile].
2378 This is a list of cons cells. Each cell contains:
2379 - a specification of the files to be considered, either a list of files,
2380 or a symbol whose function or variable value will be used to retrieve
2381 a file name or a list of file names. If you use `org-agenda-files' for
2382 that, all agenda files will be scanned for targets. Nil means consider
2383 headings in the current buffer.
2384 - A specification of how to find candidate refile targets. This may be
2385 any of:
2386 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2387 This tag has to be present in all target headlines, inheritance will
2388 not be considered.
2389 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2390 todo keyword.
2391 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2392 headlines that are refiling targets.
2393 - a cons cell (:level . N). Any headline of level N is considered a target.
2394 Note that, when `org-odd-levels-only' is set, level corresponds to
2395 order in hierarchy, not to the number of stars.
2396 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2397 Note that, when `org-odd-levels-only' is set, level corresponds to
2398 order in hierarchy, not to the number of stars.
2400 Each element of this list generates a set of possible targets.
2401 The union of these sets is presented (with completion) to
2402 the user by `org-refile'.
2404 You can set the variable `org-refile-target-verify-function' to a function
2405 to verify each headline found by the simple criteria above.
2407 When this variable is nil, all top-level headlines in the current buffer
2408 are used, equivalent to the value `((nil . (:level . 1))'."
2409 :group 'org-refile
2410 :type '(repeat
2411 (cons
2412 (choice :value org-agenda-files
2413 (const :tag "All agenda files" org-agenda-files)
2414 (const :tag "Current buffer" nil)
2415 (function) (variable) (file))
2416 (choice :tag "Identify target headline by"
2417 (cons :tag "Specific tag" (const :value :tag) (string))
2418 (cons :tag "TODO keyword" (const :value :todo) (string))
2419 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2420 (cons :tag "Level number" (const :value :level) (integer))
2421 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2423 (defcustom org-refile-target-verify-function nil
2424 "Function to verify if the headline at point should be a refile target.
2425 The function will be called without arguments, with point at the
2426 beginning of the headline. It should return t and leave point
2427 where it is if the headline is a valid target for refiling.
2429 If the target should not be selected, the function must return nil.
2430 In addition to this, it may move point to a place from where the search
2431 should be continued. For example, the function may decide that the entire
2432 subtree of the current entry should be excluded and move point to the end
2433 of the subtree."
2434 :group 'org-refile
2435 :type '(choice
2436 (const nil)
2437 (function)))
2439 (defcustom org-refile-use-cache nil
2440 "Non-nil means cache refile targets to speed up the process.
2441 \\<org-mode-map>\
2442 The cache for a particular file will be updated automatically when
2443 the buffer has been killed, or when any of the marker used for flagging
2444 refile targets no longer points at a live buffer.
2445 If you have added new entries to a buffer that might themselves be targets,
2446 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2447 if you find that easier, \
2448 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2449 \\[org-refile]'."
2450 :group 'org-refile
2451 :version "24.1"
2452 :type 'boolean)
2454 (defcustom org-refile-use-outline-path nil
2455 "Non-nil means provide refile targets as paths.
2456 So a level 3 headline will be available as level1/level2/level3.
2458 When the value is `file', also include the file name (without directory)
2459 into the path. In this case, you can also stop the completion after
2460 the file name, to get entries inserted as top level in the file.
2462 When `full-file-path', include the full file path."
2463 :group 'org-refile
2464 :type '(choice
2465 (const :tag "Not" nil)
2466 (const :tag "Yes" t)
2467 (const :tag "Start with file name" file)
2468 (const :tag "Start with full file path" full-file-path)))
2470 (defcustom org-outline-path-complete-in-steps t
2471 "Non-nil means complete the outline path in hierarchical steps.
2472 When Org-mode uses the refile interface to select an outline path
2473 \(see variable `org-refile-use-outline-path'), the completion of
2474 the path can be done in a single go, or it can be done in steps down
2475 the headline hierarchy. Going in steps is probably the best if you
2476 do not use a special completion package like `ido' or `icicles'.
2477 However, when using these packages, going in one step can be very
2478 fast, while still showing the whole path to the entry."
2479 :group 'org-refile
2480 :type 'boolean)
2482 (defcustom org-refile-allow-creating-parent-nodes nil
2483 "Non-nil means allow to create new nodes as refile targets.
2484 New nodes are then created by adding \"/new node name\" to the completion
2485 of an existing node. When the value of this variable is `confirm',
2486 new node creation must be confirmed by the user (recommended).
2487 When nil, the completion must match an existing entry.
2489 Note that, if the new heading is not seen by the criteria
2490 listed in `org-refile-targets', multiple instances of the same
2491 heading would be created by trying again to file under the new
2492 heading."
2493 :group 'org-refile
2494 :type '(choice
2495 (const :tag "Never" nil)
2496 (const :tag "Always" t)
2497 (const :tag "Prompt for confirmation" confirm)))
2499 (defcustom org-refile-active-region-within-subtree nil
2500 "Non-nil means also refile active region within a subtree.
2502 By default `org-refile' doesn't allow refiling regions if they
2503 don't contain a set of subtrees, but it might be convenient to
2504 do so sometimes: in that case, the first line of the region is
2505 converted to a headline before refiling."
2506 :group 'org-refile
2507 :version "24.1"
2508 :type 'boolean)
2510 (defgroup org-todo nil
2511 "Options concerning TODO items in Org-mode."
2512 :tag "Org TODO"
2513 :group 'org)
2515 (defgroup org-progress nil
2516 "Options concerning Progress logging in Org-mode."
2517 :tag "Org Progress"
2518 :group 'org-time)
2520 (defvar org-todo-interpretation-widgets
2521 '((:tag "Sequence (cycling hits every state)" sequence)
2522 (:tag "Type (cycling directly to DONE)" type))
2523 "The available interpretation symbols for customizing `org-todo-keywords'.
2524 Interested libraries should add to this list.")
2526 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2527 "List of TODO entry keyword sequences and their interpretation.
2528 \\<org-mode-map>This is a list of sequences.
2530 Each sequence starts with a symbol, either `sequence' or `type',
2531 indicating if the keywords should be interpreted as a sequence of
2532 action steps, or as different types of TODO items. The first
2533 keywords are states requiring action - these states will select a headline
2534 for inclusion into the global TODO list Org-mode produces. If one of
2535 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2536 signify that no further action is necessary. If \"|\" is not found,
2537 the last keyword is treated as the only DONE state of the sequence.
2539 The command \\[org-todo] cycles an entry through these states, and one
2540 additional state where no keyword is present. For details about this
2541 cycling, see the manual.
2543 TODO keywords and interpretation can also be set on a per-file basis with
2544 the special #+SEQ_TODO and #+TYP_TODO lines.
2546 Each keyword can optionally specify a character for fast state selection
2547 \(in combination with the variable `org-use-fast-todo-selection')
2548 and specifiers for state change logging, using the same syntax that
2549 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2550 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2551 indicates to record a time stamp each time this state is selected.
2553 Each keyword may also specify if a timestamp or a note should be
2554 recorded when entering or leaving the state, by adding additional
2555 characters in the parenthesis after the keyword. This looks like this:
2556 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2557 record only the time of the state change. With X and Y being either
2558 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2559 Y when leaving the state if and only if the *target* state does not
2560 define X. You may omit any of the fast-selection key or X or /Y,
2561 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2563 For backward compatibility, this variable may also be just a list
2564 of keywords. In this case the interpretation (sequence or type) will be
2565 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2566 :group 'org-todo
2567 :group 'org-keywords
2568 :type '(choice
2569 (repeat :tag "Old syntax, just keywords"
2570 (string :tag "Keyword"))
2571 (repeat :tag "New syntax"
2572 (cons
2573 (choice
2574 :tag "Interpretation"
2575 ;;Quick and dirty way to see
2576 ;;`org-todo-interpretations'. This takes the
2577 ;;place of item arguments
2578 :convert-widget
2579 (lambda (widget)
2580 (widget-put widget
2581 :args (mapcar
2582 (lambda (x)
2583 (widget-convert
2584 (cons 'const x)))
2585 org-todo-interpretation-widgets))
2586 widget))
2587 (repeat
2588 (string :tag "Keyword"))))))
2590 (defvar org-todo-keywords-1 nil
2591 "All TODO and DONE keywords active in a buffer.")
2592 (make-variable-buffer-local 'org-todo-keywords-1)
2593 (defvar org-todo-keywords-for-agenda nil)
2594 (defvar org-done-keywords-for-agenda nil)
2595 (defvar org-todo-keyword-alist-for-agenda nil)
2596 (defvar org-tag-alist-for-agenda nil
2597 "Alist of all tags from all agenda files.")
2598 (defvar org-tag-groups-alist-for-agenda nil
2599 "Alist of all groups tags from all current agenda files.")
2600 (defvar org-tag-groups-alist nil)
2601 (make-variable-buffer-local 'org-tag-groups-alist)
2602 (defvar org-agenda-contributing-files nil)
2603 (defvar org-not-done-keywords nil)
2604 (make-variable-buffer-local 'org-not-done-keywords)
2605 (defvar org-done-keywords nil)
2606 (make-variable-buffer-local 'org-done-keywords)
2607 (defvar org-todo-heads nil)
2608 (make-variable-buffer-local 'org-todo-heads)
2609 (defvar org-todo-sets nil)
2610 (make-variable-buffer-local 'org-todo-sets)
2611 (defvar org-todo-log-states nil)
2612 (make-variable-buffer-local 'org-todo-log-states)
2613 (defvar org-todo-kwd-alist nil)
2614 (make-variable-buffer-local 'org-todo-kwd-alist)
2615 (defvar org-todo-key-alist nil)
2616 (make-variable-buffer-local 'org-todo-key-alist)
2617 (defvar org-todo-key-trigger nil)
2618 (make-variable-buffer-local 'org-todo-key-trigger)
2620 (defcustom org-todo-interpretation 'sequence
2621 "Controls how TODO keywords are interpreted.
2622 This variable is in principle obsolete and is only used for
2623 backward compatibility, if the interpretation of todo keywords is
2624 not given already in `org-todo-keywords'. See that variable for
2625 more information."
2626 :group 'org-todo
2627 :group 'org-keywords
2628 :type '(choice (const sequence)
2629 (const type)))
2631 (defcustom org-use-fast-todo-selection t
2632 "\\<org-mode-map>\
2633 Non-nil means use the fast todo selection scheme with \\[org-todo].
2634 This variable describes if and under what circumstances the cycling
2635 mechanism for TODO keywords will be replaced by a single-key, direct
2636 selection scheme.
2638 When nil, fast selection is never used.
2640 When the symbol `prefix', it will be used when `org-todo' is called
2641 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2642 in an Org-mode buffer, and
2643 `\\[universal-argument] t' in an agenda buffer.
2645 When t, fast selection is used by default. In this case, the prefix
2646 argument forces cycling instead.
2648 In all cases, the special interface is only used if access keys have
2649 actually been assigned by the user, i.e. if keywords in the configuration
2650 are followed by a letter in parenthesis, like TODO(t)."
2651 :group 'org-todo
2652 :type '(choice
2653 (const :tag "Never" nil)
2654 (const :tag "By default" t)
2655 (const :tag "Only with C-u C-c C-t" prefix)))
2657 (defcustom org-provide-todo-statistics t
2658 "Non-nil means update todo statistics after insert and toggle.
2659 ALL-HEADLINES means update todo statistics by including headlines
2660 with no TODO keyword as well, counting them as not done.
2661 A list of TODO keywords means the same, but skip keywords that are
2662 not in this list.
2663 When set to a list of two lists, the first list contains keywords
2664 to consider as TODO keywords, the second list contains keywords
2665 to consider as DONE keywords.
2667 When this is set, todo statistics is updated in the parent of the
2668 current entry each time a todo state is changed."
2669 :group 'org-todo
2670 :type '(choice
2671 (const :tag "Yes, only for TODO entries" t)
2672 (const :tag "Yes, including all entries" all-headlines)
2673 (repeat :tag "Yes, for TODOs in this list"
2674 (string :tag "TODO keyword"))
2675 (list :tag "Yes, for TODOs and DONEs in these lists"
2676 (repeat (string :tag "TODO keyword"))
2677 (repeat (string :tag "DONE keyword")))
2678 (other :tag "No TODO statistics" nil)))
2680 (defcustom org-hierarchical-todo-statistics t
2681 "Non-nil means TODO statistics covers just direct children.
2682 When nil, all entries in the subtree are considered.
2683 This has only an effect if `org-provide-todo-statistics' is set.
2684 To set this to nil for only a single subtree, use a COOKIE_DATA
2685 property and include the word \"recursive\" into the value."
2686 :group 'org-todo
2687 :type 'boolean)
2689 (defcustom org-after-todo-state-change-hook nil
2690 "Hook which is run after the state of a TODO item was changed.
2691 The new state (a string with a TODO keyword, or nil) is available in the
2692 Lisp variable `org-state'."
2693 :group 'org-todo
2694 :type 'hook)
2696 (defvar org-blocker-hook nil
2697 "Hook for functions that are allowed to block a state change.
2699 Functions in this hook should not modify the buffer.
2700 Each function gets as its single argument a property list,
2701 see `org-trigger-hook' for more information about this list.
2703 If any of the functions in this hook returns nil, the state change
2704 is blocked.")
2706 (defvar org-trigger-hook nil
2707 "Hook for functions that are triggered by a state change.
2709 Each function gets as its single argument a property list with at
2710 least the following elements:
2712 (:type type-of-change :position pos-at-entry-start
2713 :from old-state :to new-state)
2715 Depending on the type, more properties may be present.
2717 This mechanism is currently implemented for:
2719 TODO state changes
2720 ------------------
2721 :type todo-state-change
2722 :from previous state (keyword as a string), or nil, or a symbol
2723 `todo' or `done', to indicate the general type of state.
2724 :to new state, like in :from")
2726 (defcustom org-enforce-todo-dependencies nil
2727 "Non-nil means undone TODO entries will block switching the parent to DONE.
2728 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2729 be blocked if any prior sibling is not yet done.
2730 Finally, if the parent is blocked because of ordered siblings of its own,
2731 the child will also be blocked."
2732 :set (lambda (var val)
2733 (set var val)
2734 (if val
2735 (add-hook 'org-blocker-hook
2736 'org-block-todo-from-children-or-siblings-or-parent)
2737 (remove-hook 'org-blocker-hook
2738 'org-block-todo-from-children-or-siblings-or-parent)))
2739 :group 'org-todo
2740 :type 'boolean)
2742 (defcustom org-enforce-todo-checkbox-dependencies nil
2743 "Non-nil means unchecked boxes will block switching the parent to DONE.
2744 When this is nil, checkboxes have no influence on switching TODO states.
2745 When non-nil, you first need to check off all check boxes before the TODO
2746 entry can be switched to DONE.
2747 This variable needs to be set before org.el is loaded, and you need to
2748 restart Emacs after a change to make the change effective. The only way
2749 to change is while Emacs is running is through the customize interface."
2750 :set (lambda (var val)
2751 (set var val)
2752 (if val
2753 (add-hook 'org-blocker-hook
2754 'org-block-todo-from-checkboxes)
2755 (remove-hook 'org-blocker-hook
2756 'org-block-todo-from-checkboxes)))
2757 :group 'org-todo
2758 :type 'boolean)
2760 (defcustom org-treat-insert-todo-heading-as-state-change nil
2761 "Non-nil means inserting a TODO heading is treated as state change.
2762 So when the command \\[org-insert-todo-heading] is used, state change
2763 logging will apply if appropriate. When nil, the new TODO item will
2764 be inserted directly, and no logging will take place."
2765 :group 'org-todo
2766 :type 'boolean)
2768 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2769 "Non-nil means switching TODO states with S-cursor counts as state change.
2770 This is the default behavior. However, setting this to nil allows a
2771 convenient way to select a TODO state and bypass any logging associated
2772 with that."
2773 :group 'org-todo
2774 :type 'boolean)
2776 (defcustom org-todo-state-tags-triggers nil
2777 "Tag changes that should be triggered by TODO state changes.
2778 This is a list. Each entry is
2780 (state-change (tag . flag) .......)
2782 State-change can be a string with a state, and empty string to indicate the
2783 state that has no TODO keyword, or it can be one of the symbols `todo'
2784 or `done', meaning any not-done or done state, respectively."
2785 :group 'org-todo
2786 :group 'org-tags
2787 :type '(repeat
2788 (cons (choice :tag "When changing to"
2789 (const :tag "Not-done state" todo)
2790 (const :tag "Done state" done)
2791 (string :tag "State"))
2792 (repeat
2793 (cons :tag "Tag action"
2794 (string :tag "Tag")
2795 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2797 (defcustom org-log-done nil
2798 "Information to record when a task moves to the DONE state.
2800 Possible values are:
2802 nil Don't add anything, just change the keyword
2803 time Add a time stamp to the task
2804 note Prompt for a note and add it with template `org-log-note-headings'
2806 This option can also be set with on a per-file-basis with
2808 #+STARTUP: nologdone
2809 #+STARTUP: logdone
2810 #+STARTUP: lognotedone
2812 You can have local logging settings for a subtree by setting the LOGGING
2813 property to one or more of these keywords."
2814 :group 'org-todo
2815 :group 'org-progress
2816 :type '(choice
2817 (const :tag "No logging" nil)
2818 (const :tag "Record CLOSED timestamp" time)
2819 (const :tag "Record CLOSED timestamp with note." note)))
2821 ;; Normalize old uses of org-log-done.
2822 (cond
2823 ((eq org-log-done t) (setq org-log-done 'time))
2824 ((and (listp org-log-done) (memq 'done org-log-done))
2825 (setq org-log-done 'note)))
2827 (defcustom org-log-reschedule nil
2828 "Information to record when the scheduling date of a tasks is modified.
2830 Possible values are:
2832 nil Don't add anything, just change the date
2833 time Add a time stamp to the task
2834 note Prompt for a note and add it with template `org-log-note-headings'
2836 This option can also be set with on a per-file-basis with
2838 #+STARTUP: nologreschedule
2839 #+STARTUP: logreschedule
2840 #+STARTUP: lognotereschedule"
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-redeadline nil
2849 "Information to record when the deadline date of a tasks is modified.
2851 Possible values are:
2853 nil Don't add anything, just change the date
2854 time Add a time stamp to the task
2855 note Prompt for a note and add it with template `org-log-note-headings'
2857 This option can also be set with on a per-file-basis with
2859 #+STARTUP: nologredeadline
2860 #+STARTUP: logredeadline
2861 #+STARTUP: lognoteredeadline
2863 You can have local logging settings for a subtree by setting the LOGGING
2864 property to one or more of these keywords."
2865 :group 'org-todo
2866 :group 'org-progress
2867 :type '(choice
2868 (const :tag "No logging" nil)
2869 (const :tag "Record timestamp" time)
2870 (const :tag "Record timestamp with note." note)))
2872 (defcustom org-log-note-clock-out nil
2873 "Non-nil means record a note when clocking out of an item.
2874 This can also be configured on a per-file basis by adding one of
2875 the following lines anywhere in the buffer:
2877 #+STARTUP: lognoteclock-out
2878 #+STARTUP: nolognoteclock-out"
2879 :group 'org-todo
2880 :group 'org-progress
2881 :type 'boolean)
2883 (defcustom org-log-done-with-time t
2884 "Non-nil means the CLOSED time stamp will contain date and time.
2885 When nil, only the date will be recorded."
2886 :group 'org-progress
2887 :type 'boolean)
2889 (defcustom org-log-note-headings
2890 '((done . "CLOSING NOTE %t")
2891 (state . "State %-12s from %-12S %t")
2892 (note . "Note taken on %t")
2893 (reschedule . "Rescheduled from %S on %t")
2894 (delschedule . "Not scheduled, was %S on %t")
2895 (redeadline . "New deadline from %S on %t")
2896 (deldeadline . "Removed deadline, was %S on %t")
2897 (refile . "Refiled on %t")
2898 (clock-out . ""))
2899 "Headings for notes added to entries.
2901 The value is an alist, with the car being a symbol indicating the
2902 note context, and the cdr is the heading to be used. The heading
2903 may also be the empty string. The following placeholders can be
2904 used:
2906 %t a time stamp.
2907 %T an active time stamp instead the default inactive one
2908 %d a short-format time stamp.
2909 %D an active short-format time stamp.
2910 %s the new TODO state or time stamp (inactive), in double quotes.
2911 %S the old TODO state or time stamp (inactive), in double quotes.
2912 %u the user name.
2913 %U full user name.
2915 In fact, it is not a good idea to change the `state' entry,
2916 because Agenda Log mode depends on the format of these entries."
2917 :group 'org-todo
2918 :group 'org-progress
2919 :type '(list :greedy t
2920 (cons (const :tag "Heading when closing an item" done) string)
2921 (cons (const :tag
2922 "Heading when changing todo state (todo sequence only)"
2923 state) string)
2924 (cons (const :tag "Heading when just taking a note" note) string)
2925 (cons (const :tag "Heading when rescheduling" reschedule) string)
2926 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2927 (cons (const :tag "Heading when changing deadline" redeadline) string)
2928 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2929 (cons (const :tag "Heading when refiling" refile) string)
2930 (cons (const :tag "Heading when clocking out" clock-out) string)))
2932 (unless (assq 'note org-log-note-headings)
2933 (push '(note . "%t") org-log-note-headings))
2935 (defcustom org-log-into-drawer nil
2936 "Non-nil means insert state change notes and time stamps into a drawer.
2937 When nil, state changes notes will be inserted after the headline and
2938 any scheduling and clock lines, but not inside a drawer.
2940 The value of this variable should be the name of the drawer to use.
2941 LOGBOOK is proposed as the default drawer for this purpose, you can
2942 also set this to a string to define the drawer of your choice.
2944 A value of t is also allowed, representing \"LOGBOOK\".
2946 A value of t or nil can also be set with on a per-file-basis with
2948 #+STARTUP: logdrawer
2949 #+STARTUP: nologdrawer
2951 If this variable is set, `org-log-state-notes-insert-after-drawers'
2952 will be ignored.
2954 You can set the property LOG_INTO_DRAWER to overrule this setting for
2955 a subtree.
2957 Do not check directly this variable in a Lisp program. Call
2958 function `org-log-into-drawer' instead."
2959 :group 'org-todo
2960 :group 'org-progress
2961 :type '(choice
2962 (const :tag "Not into a drawer" nil)
2963 (const :tag "LOGBOOK" t)
2964 (string :tag "Other")))
2966 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2968 (defun org-log-into-drawer ()
2969 "Name of the log drawer, as a string, or nil.
2970 This is the value of `org-log-into-drawer'. However, if the
2971 current entry has or inherits a LOG_INTO_DRAWER property, it will
2972 be used instead of the default value."
2973 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2974 (cond ((equal p "nil") nil)
2975 ((equal p "t") "LOGBOOK")
2976 ((stringp p) p)
2977 (p "LOGBOOK")
2978 ((stringp org-log-into-drawer) org-log-into-drawer)
2979 (org-log-into-drawer "LOGBOOK"))))
2981 (defcustom org-log-state-notes-insert-after-drawers nil
2982 "Non-nil means insert state change notes after any drawers in entry.
2983 Only the drawers that *immediately* follow the headline and the
2984 deadline/scheduled line are skipped.
2985 When nil, insert notes right after the heading and perhaps the line
2986 with deadline/scheduling if present.
2988 This variable will have no effect if `org-log-into-drawer' is
2989 set."
2990 :group 'org-todo
2991 :group 'org-progress
2992 :type 'boolean)
2994 (defcustom org-log-states-order-reversed t
2995 "Non-nil means the latest state note will be directly after heading.
2996 When nil, the state change notes will be ordered according to time.
2998 This option can also be set with on a per-file-basis with
3000 #+STARTUP: logstatesreversed
3001 #+STARTUP: nologstatesreversed"
3002 :group 'org-todo
3003 :group 'org-progress
3004 :type 'boolean)
3006 (defcustom org-todo-repeat-to-state nil
3007 "The TODO state to which a repeater should return the repeating task.
3008 By default this is the first task in a TODO sequence, or the previous state
3009 in a TODO_TYP set. But you can specify another task here.
3010 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3011 :group 'org-todo
3012 :version "24.1"
3013 :type '(choice (const :tag "Head of sequence" nil)
3014 (string :tag "Specific state")))
3016 (defcustom org-log-repeat 'time
3017 "Non-nil means record moving through the DONE state when triggering repeat.
3018 An auto-repeating task is immediately switched back to TODO when
3019 marked DONE. If you are not logging state changes (by adding \"@\"
3020 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3021 record a closing note, there will be no record of the task moving
3022 through DONE. This variable forces taking a note anyway.
3024 nil Don't force a record
3025 time Record a time stamp
3026 note Prompt for a note and add it with template `org-log-note-headings'
3028 This option can also be set with on a per-file-basis with
3030 #+STARTUP: nologrepeat
3031 #+STARTUP: logrepeat
3032 #+STARTUP: lognoterepeat
3034 You can have local logging settings for a subtree by setting the LOGGING
3035 property to one or more of these keywords."
3036 :group 'org-todo
3037 :group 'org-progress
3038 :type '(choice
3039 (const :tag "Don't force a record" nil)
3040 (const :tag "Force recording the DONE state" time)
3041 (const :tag "Force recording a note with the DONE state" note)))
3044 (defgroup org-priorities nil
3045 "Priorities in Org-mode."
3046 :tag "Org Priorities"
3047 :group 'org-todo)
3049 (defcustom org-enable-priority-commands t
3050 "Non-nil means priority commands are active.
3051 When nil, these commands will be disabled, so that you never accidentally
3052 set a priority."
3053 :group 'org-priorities
3054 :type 'boolean)
3056 (defcustom org-highest-priority ?A
3057 "The highest priority of TODO items. A character like ?A, ?B etc.
3058 Must have a smaller ASCII number than `org-lowest-priority'."
3059 :group 'org-priorities
3060 :type 'character)
3062 (defcustom org-lowest-priority ?C
3063 "The lowest priority of TODO items. A character like ?A, ?B etc.
3064 Must have a larger ASCII number than `org-highest-priority'."
3065 :group 'org-priorities
3066 :type 'character)
3068 (defcustom org-default-priority ?B
3069 "The default priority of TODO items.
3070 This is the priority an item gets if no explicit priority is given.
3071 When starting to cycle on an empty priority the first step in the cycle
3072 depends on `org-priority-start-cycle-with-default'. The resulting first
3073 step priority must not exceed the range from `org-highest-priority' to
3074 `org-lowest-priority' which means that `org-default-priority' has to be
3075 in this range exclusive or inclusive the range boundaries. Else the
3076 first step refuses to set the default and the second will fall back
3077 to (depending on the command used) the highest or lowest priority."
3078 :group 'org-priorities
3079 :type 'character)
3081 (defcustom org-priority-start-cycle-with-default t
3082 "Non-nil means start with default priority when starting to cycle.
3083 When this is nil, the first step in the cycle will be (depending on the
3084 command used) one higher or lower than the default priority.
3085 See also `org-default-priority'."
3086 :group 'org-priorities
3087 :type 'boolean)
3089 (defcustom org-get-priority-function nil
3090 "Function to extract the priority from a string.
3091 The string is normally the headline. If this is nil Org computes the
3092 priority from the priority cookie like [#A] in the headline. It returns
3093 an integer, increasing by 1000 for each priority level.
3094 The user can set a different function here, which should take a string
3095 as an argument and return the numeric priority."
3096 :group 'org-priorities
3097 :version "24.1"
3098 :type '(choice
3099 (const nil)
3100 (function)))
3102 (defgroup org-time nil
3103 "Options concerning time stamps and deadlines in Org-mode."
3104 :tag "Org Time"
3105 :group 'org)
3107 (defcustom org-time-stamp-rounding-minutes '(0 5)
3108 "Number of minutes to round time stamps to.
3109 \\<org-mode-map>\
3110 These are two values, the first applies when first creating a time stamp.
3111 The second applies when changing it with the commands `S-up' and `S-down'.
3112 When changing the time stamp, this means that it will change in steps
3113 of N minutes, as given by the second value.
3115 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3116 numbers should be factors of 60, so for example 5, 10, 15.
3118 When this is larger than 1, you can still force an exact time stamp by using
3119 a double prefix argument to a time stamp command like \
3120 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3121 and by using a prefix arg to `S-up/down' to specify the exact number
3122 of minutes to shift."
3123 :group 'org-time
3124 :get (lambda (var) ; Make sure both elements are there
3125 (if (integerp (default-value var))
3126 (list (default-value var) 5)
3127 (default-value var)))
3128 :type '(list
3129 (integer :tag "when inserting times")
3130 (integer :tag "when modifying times")))
3132 ;; Normalize old customizations of this variable.
3133 (when (integerp org-time-stamp-rounding-minutes)
3134 (setq org-time-stamp-rounding-minutes
3135 (list org-time-stamp-rounding-minutes
3136 org-time-stamp-rounding-minutes)))
3138 (defcustom org-display-custom-times nil
3139 "Non-nil means overlay custom formats over all time stamps.
3140 The formats are defined through the variable `org-time-stamp-custom-formats'.
3141 To turn this on on a per-file basis, insert anywhere in the file:
3142 #+STARTUP: customtime"
3143 :group 'org-time
3144 :set 'set-default
3145 :type 'sexp)
3146 (make-variable-buffer-local 'org-display-custom-times)
3148 (defcustom org-time-stamp-custom-formats
3149 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3150 "Custom formats for time stamps. See `format-time-string' for the syntax.
3151 These are overlaid over the default ISO format if the variable
3152 `org-display-custom-times' is set. Time like %H:%M should be at the
3153 end of the second format. The custom formats are also honored by export
3154 commands, if custom time display is turned on at the time of export."
3155 :group 'org-time
3156 :type 'sexp)
3158 (defun org-time-stamp-format (&optional long inactive)
3159 "Get the right format for a time string."
3160 (let ((f (if long (cdr org-time-stamp-formats)
3161 (car org-time-stamp-formats))))
3162 (if inactive
3163 (concat "[" (substring f 1 -1) "]")
3164 f)))
3166 (defcustom org-time-clocksum-format
3167 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3168 "The format string used when creating CLOCKSUM lines.
3169 This is also used when Org mode generates a time duration.
3171 The value can be a single format string containing two
3172 %-sequences, which will be filled with the number of hours and
3173 minutes in that order.
3175 Alternatively, the value can be a plist associating any of the
3176 keys :years, :months, :weeks, :days, :hours or :minutes with
3177 format strings. The time duration is formatted using only the
3178 time components that are needed and concatenating the results.
3179 If a time unit in absent, it falls back to the next smallest
3180 unit.
3182 The keys :require-years, :require-months, :require-days,
3183 :require-weeks, :require-hours, :require-minutes are also
3184 meaningful. A non-nil value for these keys indicates that the
3185 corresponding time component should always be included, even if
3186 its value is 0.
3189 For example,
3191 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3192 :require-minutes t)
3194 means durations longer than a day will be expressed in days,
3195 hours and minutes, and durations less than a day will always be
3196 expressed in hours and minutes (even for durations less than an
3197 hour).
3199 The value
3201 (:days \"%dd\" :minutes \"%dm\")
3203 means durations longer than a day will be expressed in days and
3204 minutes, and durations less than a day will be expressed entirely
3205 in minutes (even for durations longer than an hour)."
3206 :group 'org-time
3207 :group 'org-clock
3208 :version "24.4"
3209 :package-version '(Org . "8.0")
3210 :type '(choice (string :tag "Format string")
3211 (set :tag "Plist"
3212 (group :inline t (const :tag "Years" :years)
3213 (string :tag "Format string"))
3214 (group :inline t
3215 (const :tag "Always show years" :require-years)
3216 (const t))
3217 (group :inline t (const :tag "Months" :months)
3218 (string :tag "Format string"))
3219 (group :inline t
3220 (const :tag "Always show months" :require-months)
3221 (const t))
3222 (group :inline t (const :tag "Weeks" :weeks)
3223 (string :tag "Format string"))
3224 (group :inline t
3225 (const :tag "Always show weeks" :require-weeks)
3226 (const t))
3227 (group :inline t (const :tag "Days" :days)
3228 (string :tag "Format string"))
3229 (group :inline t
3230 (const :tag "Always show days" :require-days)
3231 (const t))
3232 (group :inline t (const :tag "Hours" :hours)
3233 (string :tag "Format string"))
3234 (group :inline t
3235 (const :tag "Always show hours" :require-hours)
3236 (const t))
3237 (group :inline t (const :tag "Minutes" :minutes)
3238 (string :tag "Format string"))
3239 (group :inline t
3240 (const :tag "Always show minutes" :require-minutes)
3241 (const t)))))
3243 (defcustom org-time-clocksum-use-fractional nil
3244 "When non-nil, \\[org-clock-display] uses fractional times.
3245 See `org-time-clocksum-format' for more on time clock formats."
3246 :group 'org-time
3247 :group 'org-clock
3248 :version "24.3"
3249 :type 'boolean)
3251 (defcustom org-time-clocksum-use-effort-durations nil
3252 "When non-nil, \\[org-clock-display] uses effort durations.
3253 E.g. by default, one day is considered to be a 8 hours effort,
3254 so a task that has been clocked for 16 hours will be displayed
3255 as during 2 days in the clock display or in the clocktable.
3257 See `org-effort-durations' on how to set effort durations
3258 and `org-time-clocksum-format' for more on time clock formats."
3259 :group 'org-time
3260 :group 'org-clock
3261 :version "24.4"
3262 :package-version '(Org . "8.0")
3263 :type 'boolean)
3265 (defcustom org-time-clocksum-fractional-format "%.2f"
3266 "The format string used when creating CLOCKSUM lines,
3267 or when Org mode generates a time duration, if
3268 `org-time-clocksum-use-fractional' is enabled.
3270 The value can be a single format string containing one
3271 %-sequence, which will be filled with the number of hours as
3272 a float.
3274 Alternatively, the value can be a plist associating any of the
3275 keys :years, :months, :weeks, :days, :hours or :minutes with
3276 a format string. The time duration is formatted using the
3277 largest time unit which gives a non-zero integer part. If all
3278 specified formats have zero integer part, the smallest time unit
3279 is used."
3280 :group 'org-time
3281 :type '(choice (string :tag "Format string")
3282 (set (group :inline t (const :tag "Years" :years)
3283 (string :tag "Format string"))
3284 (group :inline t (const :tag "Months" :months)
3285 (string :tag "Format string"))
3286 (group :inline t (const :tag "Weeks" :weeks)
3287 (string :tag "Format string"))
3288 (group :inline t (const :tag "Days" :days)
3289 (string :tag "Format string"))
3290 (group :inline t (const :tag "Hours" :hours)
3291 (string :tag "Format string"))
3292 (group :inline t (const :tag "Minutes" :minutes)
3293 (string :tag "Format string")))))
3295 (defcustom org-deadline-warning-days 14
3296 "Number of days before expiration during which a deadline becomes active.
3297 This variable governs the display in sparse trees and in the agenda.
3298 When 0 or negative, it means use this number (the absolute value of it)
3299 even if a deadline has a different individual lead time specified.
3301 Custom commands can set this variable in the options section."
3302 :group 'org-time
3303 :group 'org-agenda-daily/weekly
3304 :type 'integer)
3306 (defcustom org-scheduled-delay-days 0
3307 "Number of days before a scheduled item becomes active.
3308 This variable governs the display in sparse trees and in the agenda.
3309 The default value (i.e. 0) means: don't delay scheduled item.
3310 When negative, it means use this number (the absolute value of it)
3311 even if a scheduled item has a different individual delay time
3312 specified.
3314 Custom commands can set this variable in the options section."
3315 :group 'org-time
3316 :group 'org-agenda-daily/weekly
3317 :version "24.4"
3318 :package-version '(Org . "8.0")
3319 :type 'integer)
3321 (defcustom org-read-date-prefer-future t
3322 "Non-nil means assume future for incomplete date input from user.
3323 This affects the following situations:
3324 1. The user gives a month but not a year.
3325 For example, if it is April and you enter \"feb 2\", this will be read
3326 as Feb 2, *next* year. \"May 5\", however, will be this year.
3327 2. The user gives a day, but no month.
3328 For example, if today is the 15th, and you enter \"3\", Org-mode will
3329 read this as the third of *next* month. However, if you enter \"17\",
3330 it will be considered as *this* month.
3332 If you set this variable to the symbol `time', then also the following
3333 will work:
3335 3. If the user gives a time.
3336 If the time is before now, it will be interpreted as tomorrow.
3338 Currently none of this works for ISO week specifications.
3340 When this option is nil, the current day, month and year will always be
3341 used as defaults.
3343 See also `org-agenda-jump-prefer-future'."
3344 :group 'org-time
3345 :type '(choice
3346 (const :tag "Never" nil)
3347 (const :tag "Check month and day" t)
3348 (const :tag "Check month, day, and time" time)))
3350 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3351 "Should the agenda jump command prefer the future for incomplete dates?
3352 The default is to do the same as configured in `org-read-date-prefer-future'.
3353 But you can also set a deviating value here.
3354 This may t or nil, or the symbol `org-read-date-prefer-future'."
3355 :group 'org-agenda
3356 :group 'org-time
3357 :version "24.1"
3358 :type '(choice
3359 (const :tag "Use org-read-date-prefer-future"
3360 org-read-date-prefer-future)
3361 (const :tag "Never" nil)
3362 (const :tag "Always" t)))
3364 (defcustom org-read-date-force-compatible-dates t
3365 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3367 Depending on the system Emacs is running on, certain dates cannot
3368 be represented with the type used internally to represent time.
3369 Dates between 1970-1-1 and 2038-1-1 can always be represented
3370 correctly. Some systems allow for earlier dates, some for later,
3371 some for both. One way to find out it to insert any date into an
3372 Org buffer, putting the cursor on the year and hitting S-up and
3373 S-down to test the range.
3375 When this variable is set to t, the date/time prompt will not let
3376 you specify dates outside the 1970-2037 range, so it is certain that
3377 these dates will work in whatever version of Emacs you are
3378 running, and also that you can move a file from one Emacs implementation
3379 to another. WHenever Org is forcing the year for you, it will display
3380 a message and beep.
3382 When this variable is nil, Org will check if the date is
3383 representable in the specific Emacs implementation you are using.
3384 If not, it will force a year, usually the current year, and beep
3385 to remind you. Currently this setting is not recommended because
3386 the likelihood that you will open your Org files in an Emacs that
3387 has limited date range is not negligible.
3389 A workaround for this problem is to use diary sexp dates for time
3390 stamps outside of this range."
3391 :group 'org-time
3392 :version "24.1"
3393 :type 'boolean)
3395 (defcustom org-read-date-display-live t
3396 "Non-nil means display current interpretation of date prompt live.
3397 This display will be in an overlay, in the minibuffer."
3398 :group 'org-time
3399 :type 'boolean)
3401 (defcustom org-read-date-popup-calendar t
3402 "Non-nil means pop up a calendar when prompting for a date.
3403 In the calendar, the date can be selected with mouse-1. However, the
3404 minibuffer will also be active, and you can simply enter the date as well.
3405 When nil, only the minibuffer will be available."
3406 :group 'org-time
3407 :type 'boolean)
3408 (org-defvaralias 'org-popup-calendar-for-date-prompt
3409 'org-read-date-popup-calendar)
3411 (make-obsolete-variable
3412 'org-read-date-minibuffer-setup-hook
3413 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3414 (defcustom org-read-date-minibuffer-setup-hook nil
3415 "Hook to be used to set up keys for the date/time interface.
3416 Add key definitions to `minibuffer-local-map', which will be a
3417 temporary copy.
3419 WARNING: This option is obsolete, you should use
3420 `org-read-date-minibuffer-local-map' to set up keys."
3421 :group 'org-time
3422 :type 'hook)
3424 (defcustom org-extend-today-until 0
3425 "The hour when your day really ends. Must be an integer.
3426 This has influence for the following applications:
3427 - When switching the agenda to \"today\". It it is still earlier than
3428 the time given here, the day recognized as TODAY is actually yesterday.
3429 - When a date is read from the user and it is still before the time given
3430 here, the current date and time will be assumed to be yesterday, 23:59.
3431 Also, timestamps inserted in capture templates follow this rule.
3433 IMPORTANT: This is a feature whose implementation is and likely will
3434 remain incomplete. Really, it is only here because past midnight seems to
3435 be the favorite working time of John Wiegley :-)"
3436 :group 'org-time
3437 :type 'integer)
3439 (defcustom org-use-effective-time nil
3440 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3441 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3442 \"effective time\" of any timestamps between midnight and 8am will be
3443 23:59 of the previous day."
3444 :group 'org-time
3445 :version "24.1"
3446 :type 'boolean)
3448 (defcustom org-use-last-clock-out-time-as-effective-time nil
3449 "When non-nil, use the last clock out time for `org-todo'.
3450 Note that this option has precedence over the combined use of
3451 `org-use-effective-time' and `org-extend-today-until'."
3452 :group 'org-time
3453 :version "24.4"
3454 :package-version '(Org . "8.0")
3455 :type 'boolean)
3457 (defcustom org-edit-timestamp-down-means-later nil
3458 "Non-nil means S-down will increase the time in a time stamp.
3459 When nil, S-up will increase."
3460 :group 'org-time
3461 :type 'boolean)
3463 (defcustom org-calendar-follow-timestamp-change t
3464 "Non-nil means make the calendar window follow timestamp changes.
3465 When a timestamp is modified and the calendar window is visible, it will be
3466 moved to the new date."
3467 :group 'org-time
3468 :type 'boolean)
3470 (defgroup org-tags nil
3471 "Options concerning tags in Org-mode."
3472 :tag "Org Tags"
3473 :group 'org)
3475 (defcustom org-tag-alist nil
3476 "List of tags allowed in Org-mode files.
3477 When this list is nil, Org-mode will base TAG input on what is already in the
3478 buffer.
3479 The value of this variable is an alist, the car of each entry must be a
3480 keyword as a string, the cdr may be a character that is used to select
3481 that tag through the fast-tag-selection interface.
3482 See the manual for details."
3483 :group 'org-tags
3484 :type '(repeat
3485 (choice
3486 (cons (string :tag "Tag name")
3487 (character :tag "Access char"))
3488 (list :tag "Start radio group"
3489 (const :startgroup)
3490 (option (string :tag "Group description")))
3491 (list :tag "Start tag group, non distinct"
3492 (const :startgrouptag)
3493 (option (string :tag "Group description")))
3494 (list :tag "Group tags delimiter"
3495 (const :grouptags))
3496 (list :tag "End radio group"
3497 (const :endgroup)
3498 (option (string :tag "Group description")))
3499 (list :tag "End tag group, non distinct"
3500 (const :endgrouptag)
3501 (option (string :tag "Group description")))
3502 (const :tag "New line" (:newline)))))
3504 (defcustom org-tag-persistent-alist nil
3505 "List of tags that will always appear in all Org-mode files.
3506 This is in addition to any in buffer settings or customizations
3507 of `org-tag-alist'.
3508 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3509 The value of this variable is an alist, the car of each entry must be a
3510 keyword as a string, the cdr may be a character that is used to select
3511 that tag through the fast-tag-selection interface.
3512 See the manual for details.
3513 To disable these tags on a per-file basis, insert anywhere in the file:
3514 #+STARTUP: noptag"
3515 :group 'org-tags
3516 :type '(repeat
3517 (choice
3518 (cons (string :tag "Tag name")
3519 (character :tag "Access char"))
3520 (const :tag "Start radio group" (:startgroup))
3521 (const :tag "Group tags delimiter" (:grouptags))
3522 (const :tag "End radio group" (:endgroup))
3523 (const :tag "New line" (:newline)))))
3525 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3526 "If non-nil, always offer completion for all tags of all agenda files.
3527 Instead of customizing this variable directly, you might want to
3528 set it locally for capture buffers, because there no list of
3529 tags in that file can be created dynamically (there are none).
3531 (add-hook \\='org-capture-mode-hook
3532 (lambda ()
3533 (set (make-local-variable
3534 \\='org-complete-tags-always-offer-all-agenda-tags)
3535 t)))"
3536 :group 'org-tags
3537 :version "24.1"
3538 :type 'boolean)
3540 (defvar org-file-tags nil
3541 "List of tags that can be inherited by all entries in the file.
3542 The tags will be inherited if the variable `org-use-tag-inheritance'
3543 says they should be.
3544 This variable is populated from #+FILETAGS lines.")
3546 (defcustom org-use-fast-tag-selection 'auto
3547 "Non-nil means use fast tag selection scheme.
3548 This is a special interface to select and deselect tags with single keys.
3549 When nil, fast selection is never used.
3550 When the symbol `auto', fast selection is used if and only if selection
3551 characters for tags have been configured, either through the variable
3552 `org-tag-alist' or through a #+TAGS line in the buffer.
3553 When t, fast selection is always used and selection keys are assigned
3554 automatically if necessary."
3555 :group 'org-tags
3556 :type '(choice
3557 (const :tag "Always" t)
3558 (const :tag "Never" nil)
3559 (const :tag "When selection characters are configured" auto)))
3561 (defcustom org-fast-tag-selection-single-key nil
3562 "Non-nil means fast tag selection exits after first change.
3563 When nil, you have to press RET to exit it.
3564 During fast tag selection, you can toggle this flag with `C-c'.
3565 This variable can also have the value `expert'. In this case, the window
3566 displaying the tags menu is not even shown, until you press C-c again."
3567 :group 'org-tags
3568 :type '(choice
3569 (const :tag "No" nil)
3570 (const :tag "Yes" t)
3571 (const :tag "Expert" expert)))
3573 (defvar org-fast-tag-selection-include-todo nil
3574 "Non-nil means fast tags selection interface will also offer TODO states.
3575 This is an undocumented feature, you should not rely on it.")
3577 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3578 "The column to which tags should be indented in a headline.
3579 If this number is positive, it specifies the column. If it is negative,
3580 it means that the tags should be flushright to that column. For example,
3581 -80 works well for a normal 80 character screen.
3582 When 0, place tags directly after headline text, with only one space in
3583 between."
3584 :group 'org-tags
3585 :type 'integer)
3587 (defcustom org-auto-align-tags t
3588 "Non-nil keeps tags aligned when modifying headlines.
3589 Some operations (i.e. demoting) change the length of a headline and
3590 therefore shift the tags around. With this option turned on, after
3591 each such operation the tags are again aligned to `org-tags-column'."
3592 :group 'org-tags
3593 :type 'boolean)
3595 (defcustom org-use-tag-inheritance t
3596 "Non-nil means tags in levels apply also for sublevels.
3597 When nil, only the tags directly given in a specific line apply there.
3598 This may also be a list of tags that should be inherited, or a regexp that
3599 matches tags that should be inherited. Additional control is possible
3600 with the variable `org-tags-exclude-from-inheritance' which gives an
3601 explicit list of tags to be excluded from inheritance, even if the value of
3602 `org-use-tag-inheritance' would select it for inheritance.
3604 If this option is t, a match early-on in a tree can lead to a large
3605 number of matches in the subtree when constructing the agenda or creating
3606 a sparse tree. If you only want to see the first match in a tree during
3607 a search, check out the variable `org-tags-match-list-sublevels'."
3608 :group 'org-tags
3609 :type '(choice
3610 (const :tag "Not" nil)
3611 (const :tag "Always" t)
3612 (repeat :tag "Specific tags" (string :tag "Tag"))
3613 (regexp :tag "Tags matched by regexp")))
3615 (defcustom org-tags-exclude-from-inheritance nil
3616 "List of tags that should never be inherited.
3617 This is a way to exclude a few tags from inheritance. For way to do
3618 the opposite, to actively allow inheritance for selected tags,
3619 see the variable `org-use-tag-inheritance'."
3620 :group 'org-tags
3621 :type '(repeat (string :tag "Tag")))
3623 (defun org-tag-inherit-p (tag)
3624 "Check if TAG is one that should be inherited."
3625 (cond
3626 ((member tag org-tags-exclude-from-inheritance) nil)
3627 ((eq org-use-tag-inheritance t) t)
3628 ((not org-use-tag-inheritance) nil)
3629 ((stringp org-use-tag-inheritance)
3630 (string-match org-use-tag-inheritance tag))
3631 ((listp org-use-tag-inheritance)
3632 (member tag org-use-tag-inheritance))
3633 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3635 (defcustom org-tags-match-list-sublevels t
3636 "Non-nil means list also sublevels of headlines matching a search.
3637 This variable applies to tags/property searches, and also to stuck
3638 projects because this search is based on a tags match as well.
3640 When set to the symbol `indented', sublevels are indented with
3641 leading dots.
3643 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3644 the sublevels of a headline matching a tag search often also match
3645 the same search. Listing all of them can create very long lists.
3646 Setting this variable to nil causes subtrees of a match to be skipped.
3648 This variable is semi-obsolete and probably should always be true. It
3649 is better to limit inheritance to certain tags using the variables
3650 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3651 :group 'org-tags
3652 :type '(choice
3653 (const :tag "No, don't list them" nil)
3654 (const :tag "Yes, do list them" t)
3655 (const :tag "List them, indented with leading dots" indented)))
3657 (defcustom org-tags-sort-function nil
3658 "When set, tags are sorted using this function as a comparator."
3659 :group 'org-tags
3660 :type '(choice
3661 (const :tag "No sorting" nil)
3662 (const :tag "Alphabetical" string<)
3663 (const :tag "Reverse alphabetical" string>)
3664 (function :tag "Custom function" nil)))
3666 (defvar org-tags-history nil
3667 "History of minibuffer reads for tags.")
3668 (defvar org-last-tags-completion-table nil
3669 "The last used completion table for tags.")
3670 (defvar org-after-tags-change-hook nil
3671 "Hook that is run after the tags in a line have changed.")
3673 (defgroup org-properties nil
3674 "Options concerning properties in Org-mode."
3675 :tag "Org Properties"
3676 :group 'org)
3678 (defcustom org-property-format "%-10s %s"
3679 "How property key/value pairs should be formatted by `indent-line'.
3680 When `indent-line' hits a property definition, it will format the line
3681 according to this format, mainly to make sure that the values are
3682 lined-up with respect to each other."
3683 :group 'org-properties
3684 :type 'string)
3686 (defcustom org-properties-postprocess-alist nil
3687 "Alist of properties and functions to adjust inserted values.
3688 Elements of this alist must be of the form
3690 ([string] [function])
3692 where [string] must be a property name and [function] must be a
3693 lambda expression: this lambda expression must take one argument,
3694 the value to adjust, and return the new value as a string.
3696 For example, this element will allow the property \"Remaining\"
3697 to be updated wrt the relation between the \"Effort\" property
3698 and the clock summary:
3700 ((\"Remaining\" (lambda(value)
3701 (let ((clocksum (org-clock-sum-current-item))
3702 (effort (org-duration-string-to-minutes
3703 (org-entry-get (point) \"Effort\"))))
3704 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3705 :group 'org-properties
3706 :version "24.1"
3707 :type '(alist :key-type (string :tag "Property")
3708 :value-type (function :tag "Function")))
3710 (defcustom org-use-property-inheritance nil
3711 "Non-nil means properties apply also for sublevels.
3713 This setting is chiefly used during property searches. Turning it on can
3714 cause significant overhead when doing a search, which is why it is not
3715 on by default.
3717 When nil, only the properties directly given in the current entry count.
3718 When t, every property is inherited. The value may also be a list of
3719 properties that should have inheritance, or a regular expression matching
3720 properties that should be inherited.
3722 However, note that some special properties use inheritance under special
3723 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3724 and the properties ending in \"_ALL\" when they are used as descriptor
3725 for valid values of a property.
3727 Note for programmers:
3728 When querying an entry with `org-entry-get', you can control if inheritance
3729 should be used. By default, `org-entry-get' looks only at the local
3730 properties. You can request inheritance by setting the inherit argument
3731 to t (to force inheritance) or to `selective' (to respect the setting
3732 in this variable)."
3733 :group 'org-properties
3734 :type '(choice
3735 (const :tag "Not" nil)
3736 (const :tag "Always" t)
3737 (repeat :tag "Specific properties" (string :tag "Property"))
3738 (regexp :tag "Properties matched by regexp")))
3740 (defun org-property-inherit-p (property)
3741 "Check if PROPERTY is one that should be inherited."
3742 (cond
3743 ((eq org-use-property-inheritance t) t)
3744 ((not org-use-property-inheritance) nil)
3745 ((stringp org-use-property-inheritance)
3746 (string-match org-use-property-inheritance property))
3747 ((listp org-use-property-inheritance)
3748 (member property org-use-property-inheritance))
3749 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3751 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3752 "The default column format, if no other format has been defined.
3753 This variable can be set on the per-file basis by inserting a line
3755 #+COLUMNS: %25ITEM ....."
3756 :group 'org-properties
3757 :type 'string)
3759 (defcustom org-columns-ellipses ".."
3760 "The ellipses to be used when a field in column view is truncated.
3761 When this is the empty string, as many characters as possible are shown,
3762 but then there will be no visual indication that the field has been truncated.
3763 When this is a string of length N, the last N characters of a truncated
3764 field are replaced by this string. If the column is narrower than the
3765 ellipses string, only part of the ellipses string will be shown."
3766 :group 'org-properties
3767 :type 'string)
3769 (defcustom org-columns-modify-value-for-display-function nil
3770 "Function that modifies values for display in column view.
3771 For example, it can be used to cut out a certain part from a time stamp.
3772 The function must take 2 arguments:
3774 column-title The title of the column (*not* the property name)
3775 value The value that should be modified.
3777 The function should return the value that should be displayed,
3778 or nil if the normal value should be used."
3779 :group 'org-properties
3780 :type '(choice (const nil) (function)))
3782 (defconst org-global-properties-fixed
3783 '(("VISIBILITY_ALL" . "folded children content all")
3784 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3785 "List of property/value pairs that can be inherited by any entry.
3787 These are fixed values, for the preset properties. The user variable
3788 that can be used to add to this list is `org-global-properties'.
3790 The entries in this list are cons cells where the car is a property
3791 name and cdr is a string with the value. If the value represents
3792 multiple items like an \"_ALL\" property, separate the items by
3793 spaces.")
3795 (defcustom org-global-properties nil
3796 "List of property/value pairs that can be inherited by any entry.
3798 This list will be combined with the constant `org-global-properties-fixed'.
3800 The entries in this list are cons cells where the car is a property
3801 name and cdr is a string with the value.
3803 You can set buffer-local values for the same purpose in the variable
3804 `org-file-properties' this by adding lines like
3806 #+PROPERTY: NAME VALUE"
3807 :group 'org-properties
3808 :type '(repeat
3809 (cons (string :tag "Property")
3810 (string :tag "Value"))))
3812 (defvar org-file-properties nil
3813 "List of property/value pairs that can be inherited by any entry.
3814 Valid for the current buffer.
3815 This variable is populated from #+PROPERTY lines.")
3816 (make-variable-buffer-local 'org-file-properties)
3818 (defgroup org-agenda nil
3819 "Options concerning agenda views in Org-mode."
3820 :tag "Org Agenda"
3821 :group 'org)
3823 (defvar org-category nil
3824 "Variable used by org files to set a category for agenda display.
3825 Such files should use a file variable to set it, for example
3827 # -*- mode: org; org-category: \"ELisp\"
3829 or contain a special line
3831 #+CATEGORY: ELisp
3833 If the file does not specify a category, then file's base name
3834 is used instead.")
3835 (make-variable-buffer-local 'org-category)
3836 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3838 (defcustom org-agenda-files nil
3839 "The files to be used for agenda display.
3840 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3841 \\[org-remove-file]. You can also use customize to edit the list.
3843 If an entry is a directory, all files in that directory that are matched by
3844 `org-agenda-file-regexp' will be part of the file list.
3846 If the value of the variable is not a list but a single file name, then
3847 the list of agenda files is actually stored and maintained in that file, one
3848 agenda file per line. In this file paths can be given relative to
3849 `org-directory'. Tilde expansion and environment variable substitution
3850 are also made."
3851 :group 'org-agenda
3852 :type '(choice
3853 (repeat :tag "List of files and directories" file)
3854 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3856 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3857 "Regular expression to match files for `org-agenda-files'.
3858 If any element in the list in that variable contains a directory instead
3859 of a normal file, all files in that directory that are matched by this
3860 regular expression will be included."
3861 :group 'org-agenda
3862 :type 'regexp)
3864 (defcustom org-agenda-text-search-extra-files nil
3865 "List of extra files to be searched by text search commands.
3866 These files will be searched in addition to the agenda files by the
3867 commands `org-search-view' (`\\[org-agenda] s') \
3868 and `org-occur-in-agenda-files'.
3869 Note that these files will only be searched for text search commands,
3870 not for the other agenda views like todo lists, tag searches or the weekly
3871 agenda. This variable is intended to list notes and possibly archive files
3872 that should also be searched by these two commands.
3873 In fact, if the first element in the list is the symbol `agenda-archives',
3874 then all archive files of all agenda files will be added to the search
3875 scope."
3876 :group 'org-agenda
3877 :type '(set :greedy t
3878 (const :tag "Agenda Archives" agenda-archives)
3879 (repeat :inline t (file))))
3881 (org-defvaralias 'org-agenda-multi-occur-extra-files
3882 'org-agenda-text-search-extra-files)
3884 (defcustom org-agenda-skip-unavailable-files nil
3885 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3886 A nil value means to remove them, after a query, from the list."
3887 :group 'org-agenda
3888 :type 'boolean)
3890 (defcustom org-calendar-to-agenda-key [?c]
3891 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3892 The command `org-calendar-goto-agenda' will be bound to this key. The
3893 default is the character `c' because then `c' can be used to switch back and
3894 forth between agenda and calendar."
3895 :group 'org-agenda
3896 :type 'sexp)
3898 (defcustom org-calendar-insert-diary-entry-key [?i]
3899 "The key to be installed in `calendar-mode-map' for adding diary entries.
3900 This option is irrelevant until `org-agenda-diary-file' has been configured
3901 to point to an Org-mode file. When that is the case, the command
3902 `org-agenda-diary-entry' will be bound to the key given here, by default
3903 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3904 if you want to continue doing this, you need to change this to a different
3905 key."
3906 :group 'org-agenda
3907 :type 'sexp)
3909 (defcustom org-agenda-diary-file 'diary-file
3910 "File to which to add new entries with the `i' key in agenda and calendar.
3911 When this is the symbol `diary-file', the functionality in the Emacs
3912 calendar will be used to add entries to the `diary-file'. But when this
3913 points to a file, `org-agenda-diary-entry' will be used instead."
3914 :group 'org-agenda
3915 :type '(choice
3916 (const :tag "The standard Emacs diary file" diary-file)
3917 (file :tag "Special Org file diary entries")))
3919 (eval-after-load "calendar"
3920 '(progn
3921 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3922 'org-calendar-goto-agenda)
3923 (add-hook 'calendar-mode-hook
3924 (lambda ()
3925 (unless (eq org-agenda-diary-file 'diary-file)
3926 (define-key calendar-mode-map
3927 org-calendar-insert-diary-entry-key
3928 'org-agenda-diary-entry))))))
3930 (defgroup org-latex nil
3931 "Options for embedding LaTeX code into Org-mode."
3932 :tag "Org LaTeX"
3933 :group 'org)
3935 (defcustom org-format-latex-options
3936 '(:foreground default :background default :scale 1.0
3937 :html-foreground "Black" :html-background "Transparent"
3938 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3939 "Options for creating images from LaTeX fragments.
3940 This is a property list with the following properties:
3941 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3942 `default' means use the foreground of the default face.
3943 `auto' means use the foreground from the text face.
3944 :background the background color, or \"Transparent\".
3945 `default' means use the background of the default face.
3946 `auto' means use the background from the text face.
3947 :scale a scaling factor for the size of the images, to get more pixels
3948 :html-foreground, :html-background, :html-scale
3949 the same numbers for HTML export.
3950 :matchers a list indicating which matchers should be used to
3951 find LaTeX fragments. Valid members of this list are:
3952 \"begin\" find environments
3953 \"$1\" find single characters surrounded by $.$
3954 \"$\" find math expressions surrounded by $...$
3955 \"$$\" find math expressions surrounded by $$....$$
3956 \"\\(\" find math expressions surrounded by \\(...\\)
3957 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3958 :group 'org-latex
3959 :type 'plist)
3961 (defcustom org-format-latex-signal-error t
3962 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3963 When nil, just push out a message."
3964 :group 'org-latex
3965 :version "24.1"
3966 :type 'boolean)
3968 (defcustom org-latex-to-mathml-jar-file nil
3969 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3970 Use this to specify additional executable file say a jar file.
3972 When using MathToWeb as the converter, specify the full-path to
3973 your mathtoweb.jar file."
3974 :group 'org-latex
3975 :version "24.1"
3976 :type '(choice
3977 (const :tag "None" nil)
3978 (file :tag "JAR file" :must-match t)))
3980 (defcustom org-latex-to-mathml-convert-command nil
3981 "Command to convert LaTeX fragments to MathML.
3982 Replace format-specifiers in the command as noted below and use
3983 `shell-command' to convert LaTeX to MathML.
3984 %j: Executable file in fully expanded form as specified by
3985 `org-latex-to-mathml-jar-file'.
3986 %I: Input LaTeX file in fully expanded form.
3987 %i: The latex fragment to be converted.
3988 %o: Output MathML file.
3990 This command is used by `org-create-math-formula'.
3992 When using MathToWeb as the converter, set this option to
3993 \"java -jar %j -unicode -force -df %o %I\".
3995 When using LaTeXML set this option to
3996 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3997 :group 'org-latex
3998 :version "24.1"
3999 :type '(choice
4000 (const :tag "None" nil)
4001 (string :tag "\nShell command")))
4003 (defcustom org-latex-create-formula-image-program 'dvipng
4004 "Program to convert LaTeX fragments with.
4006 dvipng Process the LaTeX fragments to dvi file, then convert
4007 dvi files to png files using dvipng.
4008 This will also include processing of non-math environments.
4009 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
4010 to convert pdf files to png files"
4011 :group 'org-latex
4012 :version "24.1"
4013 :type '(choice
4014 (const :tag "dvipng" dvipng)
4015 (const :tag "imagemagick" imagemagick)))
4017 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
4018 "Path to store latex preview images.
4019 A relative path here creates many directories relative to the
4020 processed org files paths. An absolute path puts all preview
4021 images at the same place."
4022 :group 'org-latex
4023 :version "24.3"
4024 :type 'string)
4026 (defun org-format-latex-mathml-available-p ()
4027 "Return t if `org-latex-to-mathml-convert-command' is usable."
4028 (save-match-data
4029 (when (and (boundp 'org-latex-to-mathml-convert-command)
4030 org-latex-to-mathml-convert-command)
4031 (let ((executable (car (split-string
4032 org-latex-to-mathml-convert-command))))
4033 (when (executable-find executable)
4034 (if (string-match
4035 "%j" org-latex-to-mathml-convert-command)
4036 (file-readable-p org-latex-to-mathml-jar-file)
4037 t))))))
4039 (defcustom org-format-latex-header "\\documentclass{article}
4040 \\usepackage[usenames]{color}
4041 \[PACKAGES]
4042 \[DEFAULT-PACKAGES]
4043 \\pagestyle{empty} % do not remove
4044 % The settings below are copied from fullpage.sty
4045 \\setlength{\\textwidth}{\\paperwidth}
4046 \\addtolength{\\textwidth}{-3cm}
4047 \\setlength{\\oddsidemargin}{1.5cm}
4048 \\addtolength{\\oddsidemargin}{-2.54cm}
4049 \\setlength{\\evensidemargin}{\\oddsidemargin}
4050 \\setlength{\\textheight}{\\paperheight}
4051 \\addtolength{\\textheight}{-\\headheight}
4052 \\addtolength{\\textheight}{-\\headsep}
4053 \\addtolength{\\textheight}{-\\footskip}
4054 \\addtolength{\\textheight}{-3cm}
4055 \\setlength{\\topmargin}{1.5cm}
4056 \\addtolength{\\topmargin}{-2.54cm}"
4057 "The document header used for processing LaTeX fragments.
4058 It is imperative that this header make sure that no page number
4059 appears on the page. The package defined in the variables
4060 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4061 will either replace the placeholder \"[PACKAGES]\" in this
4062 header, or they will be appended."
4063 :group 'org-latex
4064 :type 'string)
4066 (defun org-set-packages-alist (var val)
4067 "Set the packages alist and make sure it has 3 elements per entry."
4068 (set var (mapcar (lambda (x)
4069 (if (and (consp x) (= (length x) 2))
4070 (list (car x) (nth 1 x) t)
4072 val)))
4074 (defun org-get-packages-alist (var)
4075 "Get the packages alist and make sure it has 3 elements per entry."
4076 (mapcar (lambda (x)
4077 (if (and (consp x) (= (length x) 2))
4078 (list (car x) (nth 1 x) t)
4080 (default-value var)))
4082 (defcustom org-latex-default-packages-alist
4083 '(("AUTO" "inputenc" t ("pdflatex"))
4084 ("T1" "fontenc" t ("pdflatex"))
4085 ("" "graphicx" t)
4086 ("" "grffile" t)
4087 ("" "longtable" nil)
4088 ("" "wrapfig" nil)
4089 ("" "rotating" nil)
4090 ("normalem" "ulem" t)
4091 ("" "amsmath" t)
4092 ("" "textcomp" t)
4093 ("" "amssymb" t)
4094 ("" "capt-of" nil)
4095 ("" "hyperref" nil))
4096 "Alist of default packages to be inserted in the header.
4098 Change this only if one of the packages here causes an
4099 incompatibility with another package you are using.
4101 The packages in this list are needed by one part or another of
4102 Org mode to function properly:
4104 - inputenc, fontenc: for basic font and character selection
4105 - graphicx: for including images
4106 - grffile: allow periods and spaces in graphics file names
4107 - longtable: For multipage tables
4108 - wrapfig: for figure placement
4109 - rotating: for sideways figures and tables
4110 - ulem: for underline and strike-through
4111 - amsmath: for subscript and superscript and math environments
4112 - textcomp, amssymb: for various symbols used
4113 for interpreting the entities in `org-entities'. You can skip
4114 some of these packages if you don't use any of their symbols.
4115 - capt-of: for captions outside of floats
4116 - hyperref: for cross references
4118 Therefore you should not modify this variable unless you know
4119 what you are doing. The one reason to change it anyway is that
4120 you might be loading some other package that conflicts with one
4121 of the default packages. Each element is either a cell or
4122 a string.
4124 A cell is of the format
4126 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4128 If SNIPPET-FLAG is non-nil, the package also needs to be included
4129 when compiling LaTeX snippets into images for inclusion into
4130 non-LaTeX output. COMPILERS is a list of compilers that should
4131 include the package, see `org-latex-compiler'. If the document
4132 compiler is not in the list, and the list is non-nil, the package
4133 will not be inserted in the final document.
4135 A string will be inserted as-is in the header of the document."
4136 :group 'org-latex
4137 :group 'org-export-latex
4138 :set 'org-set-packages-alist
4139 :get 'org-get-packages-alist
4140 :version "25.1"
4141 :package-version '(Org . "8.3")
4142 :type '(repeat
4143 (choice
4144 (list :tag "options/package pair"
4145 (string :tag "options")
4146 (string :tag "package")
4147 (boolean :tag "Snippet"))
4148 (string :tag "A line of LaTeX"))))
4150 (defcustom org-latex-packages-alist nil
4151 "Alist of packages to be inserted in every LaTeX header.
4153 These will be inserted after `org-latex-default-packages-alist'.
4154 Each element is either a cell or a string.
4156 A cell is of the format:
4158 (\"options\" \"package\" SNIPPET-FLAG)
4160 SNIPPET-FLAG, when non-nil, indicates that this package is also
4161 needed when turning LaTeX snippets into images for inclusion into
4162 non-LaTeX output.
4164 A string will be inserted as-is in the header of the document.
4166 Make sure that you only list packages here which:
4168 - you want in every file;
4169 - do not conflict with the setup in `org-format-latex-header';
4170 - do not conflict with the default packages in
4171 `org-latex-default-packages-alist'."
4172 :group 'org-latex
4173 :group 'org-export-latex
4174 :set 'org-set-packages-alist
4175 :get 'org-get-packages-alist
4176 :type '(repeat
4177 (choice
4178 (list :tag "options/package pair"
4179 (string :tag "options")
4180 (string :tag "package")
4181 (boolean :tag "Snippet"))
4182 (string :tag "A line of LaTeX"))))
4184 (defgroup org-appearance nil
4185 "Settings for Org-mode appearance."
4186 :tag "Org Appearance"
4187 :group 'org)
4189 (defcustom org-level-color-stars-only nil
4190 "Non-nil means fontify only the stars in each headline.
4191 When nil, the entire headline is fontified.
4192 Changing it requires restart of `font-lock-mode' to become effective
4193 also in regions already fontified."
4194 :group 'org-appearance
4195 :type 'boolean)
4197 (defcustom org-hide-leading-stars nil
4198 "Non-nil means hide the first N-1 stars in a headline.
4199 This works by using the face `org-hide' for these stars. This
4200 face is white for a light background, and black for a dark
4201 background. You may have to customize the face `org-hide' to
4202 make this work.
4203 Changing it requires restart of `font-lock-mode' to become effective
4204 also in regions already fontified.
4205 You may also set this on a per-file basis by adding one of the following
4206 lines to the buffer:
4208 #+STARTUP: hidestars
4209 #+STARTUP: showstars"
4210 :group 'org-appearance
4211 :type 'boolean)
4213 (defcustom org-hidden-keywords nil
4214 "List of symbols corresponding to keywords to be hidden the org buffer.
4215 For example, a value \\='(title) for this list will make the document's title
4216 appear in the buffer without the initial #+TITLE: keyword."
4217 :group 'org-appearance
4218 :version "24.1"
4219 :type '(set (const :tag "#+AUTHOR" author)
4220 (const :tag "#+DATE" date)
4221 (const :tag "#+EMAIL" email)
4222 (const :tag "#+TITLE" title)))
4224 (defcustom org-custom-properties nil
4225 "List of properties (as strings) with a special meaning.
4226 The default use of these custom properties is to let the user
4227 hide them with `org-toggle-custom-properties-visibility'."
4228 :group 'org-properties
4229 :group 'org-appearance
4230 :version "24.3"
4231 :type '(repeat (string :tag "Property Name")))
4233 (defcustom org-fontify-done-headline nil
4234 "Non-nil means change the face of a headline if it is marked DONE.
4235 Normally, only the TODO/DONE keyword indicates the state of a headline.
4236 When this is non-nil, the headline after the keyword is set to the
4237 `org-headline-done' as an additional indication."
4238 :group 'org-appearance
4239 :type 'boolean)
4241 (defcustom org-fontify-emphasized-text t
4242 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4243 Changing this variable requires a restart of Emacs to take effect."
4244 :group 'org-appearance
4245 :type 'boolean)
4247 (defcustom org-fontify-whole-heading-line nil
4248 "Non-nil means fontify the whole line for headings.
4249 This is useful when setting a background color for the
4250 org-level-* faces."
4251 :group 'org-appearance
4252 :type 'boolean)
4254 (defcustom org-highlight-latex-and-related nil
4255 "Non-nil means highlight LaTeX related syntax in the buffer.
4256 When non nil, the value should be a list containing any of the
4257 following symbols:
4258 `latex' Highlight LaTeX snippets and environments.
4259 `script' Highlight subscript and superscript.
4260 `entities' Highlight entities."
4261 :group 'org-appearance
4262 :version "24.4"
4263 :package-version '(Org . "8.0")
4264 :type '(choice
4265 (const :tag "No highlighting" nil)
4266 (set :greedy t :tag "Highlight"
4267 (const :tag "LaTeX snippets and environments" latex)
4268 (const :tag "Subscript and superscript" script)
4269 (const :tag "Entities" entities))))
4271 (defcustom org-hide-emphasis-markers nil
4272 "Non-nil mean font-lock should hide the emphasis marker characters."
4273 :group 'org-appearance
4274 :type 'boolean)
4276 (defcustom org-hide-macro-markers nil
4277 "Non-nil mean font-lock should hide the brackets marking macro calls."
4278 :group 'org-appearance
4279 :type 'boolean)
4281 (defcustom org-pretty-entities nil
4282 "Non-nil means show entities as UTF8 characters.
4283 When nil, the \\name form remains in the buffer."
4284 :group 'org-appearance
4285 :version "24.1"
4286 :type 'boolean)
4288 (defcustom org-pretty-entities-include-sub-superscripts t
4289 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4290 :group 'org-appearance
4291 :version "24.1"
4292 :type 'boolean)
4294 (defvar org-emph-re nil
4295 "Regular expression for matching emphasis.
4296 After a match, the match groups contain these elements:
4297 0 The match of the full regular expression, including the characters
4298 before and after the proper match
4299 1 The character before the proper match, or empty at beginning of line
4300 2 The proper match, including the leading and trailing markers
4301 3 The leading marker like * or /, indicating the type of highlighting
4302 4 The text between the emphasis markers, not including the markers
4303 5 The character after the match, empty at the end of a line")
4304 (defvar org-verbatim-re nil
4305 "Regular expression for matching verbatim text.")
4306 (defvar org-emphasis-regexp-components) ; defined just below
4307 (defvar org-emphasis-alist) ; defined just below
4308 (defun org-set-emph-re (var val)
4309 "Set variable and compute the emphasis regular expression."
4310 (set var val)
4311 (when (and (boundp 'org-emphasis-alist)
4312 (boundp 'org-emphasis-regexp-components)
4313 org-emphasis-alist org-emphasis-regexp-components)
4314 (let* ((e org-emphasis-regexp-components)
4315 (pre (car e))
4316 (post (nth 1 e))
4317 (border (nth 2 e))
4318 (body (nth 3 e))
4319 (nl (nth 4 e))
4320 (body1 (concat body "*?"))
4321 (markers (mapconcat 'car org-emphasis-alist ""))
4322 (vmarkers (mapconcat
4323 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4324 org-emphasis-alist "")))
4325 ;; make sure special characters appear at the right position in the class
4326 (if (string-match "\\^" markers)
4327 (setq markers (concat (replace-match "" t t markers) "^")))
4328 (if (string-match "-" markers)
4329 (setq markers (concat (replace-match "" t t markers) "-")))
4330 (if (string-match "\\^" vmarkers)
4331 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4332 (if (string-match "-" vmarkers)
4333 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4334 (if (> nl 0)
4335 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4336 (int-to-string nl) "\\}")))
4337 ;; Make the regexp
4338 (setq org-emph-re
4339 (concat "\\([" pre "]\\|^\\)"
4340 "\\("
4341 "\\([" markers "]\\)"
4342 "\\("
4343 "[^" border "]\\|"
4344 "[^" border "]"
4345 body1
4346 "[^" border "]"
4347 "\\)"
4348 "\\3\\)"
4349 "\\([" post "]\\|$\\)"))
4350 (setq org-verbatim-re
4351 (concat "\\([" pre "]\\|^\\)"
4352 "\\("
4353 "\\([" vmarkers "]\\)"
4354 "\\("
4355 "[^" border "]\\|"
4356 "[^" border "]"
4357 body1
4358 "[^" border "]"
4359 "\\)"
4360 "\\3\\)"
4361 "\\([" post "]\\|$\\)")))))
4363 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4364 ;; set this option proved cumbersome. See this message/thread:
4365 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4366 (defvar org-emphasis-regexp-components
4367 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n,\"'" "." 1)
4368 "Components used to build the regular expression for emphasis.
4369 This is a list with five entries. Terminology: In an emphasis string
4370 like \" *strong word* \", we call the initial space PREMATCH, the final
4371 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4372 and \"trong wor\" is the body. The different components in this variable
4373 specify what is allowed/forbidden in each part:
4375 pre Chars allowed as prematch. Beginning of line will be allowed too.
4376 post Chars allowed as postmatch. End of line will be allowed too.
4377 border The chars *forbidden* as border characters.
4378 body-regexp A regexp like \".\" to match a body character. Don't use
4379 non-shy groups here, and don't allow newline here.
4380 newline The maximum number of newlines allowed in an emphasis exp.
4382 You need to reload Org or to restart Emacs after customizing this.")
4384 (defcustom org-emphasis-alist
4385 `(("*" bold)
4386 ("/" italic)
4387 ("_" underline)
4388 ("=" org-verbatim verbatim)
4389 ("~" org-code verbatim)
4390 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4391 "Alist of characters and faces to emphasize text.
4392 Text starting and ending with a special character will be emphasized,
4393 for example *bold*, _underlined_ and /italic/. This variable sets the
4394 marker characters and the face to be used by font-lock for highlighting
4395 in Org-mode Emacs buffers.
4397 You need to reload Org or to restart Emacs after customizing this."
4398 :group 'org-appearance
4399 :set 'org-set-emph-re
4400 :version "24.4"
4401 :package-version '(Org . "8.0")
4402 :type '(repeat
4403 (list
4404 (string :tag "Marker character")
4405 (choice
4406 (face :tag "Font-lock-face")
4407 (plist :tag "Face property list"))
4408 (option (const verbatim)))))
4410 (defvar org-protecting-blocks
4411 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4412 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4413 This is needed for font-lock setup.")
4415 ;;; Miscellaneous options
4417 (defgroup org-completion nil
4418 "Completion in Org-mode."
4419 :tag "Org Completion"
4420 :group 'org)
4422 (defcustom org-completion-use-ido nil
4423 "Non-nil means use ido completion wherever possible.
4424 Note that `ido-mode' must be active for this variable to be relevant.
4425 If you decide to turn this variable on, you might well want to turn off
4426 `org-outline-path-complete-in-steps'.
4427 See also `org-completion-use-iswitchb'."
4428 :group 'org-completion
4429 :type 'boolean)
4431 (defcustom org-completion-use-iswitchb nil
4432 "Non-nil means use iswitchb completion wherever possible.
4433 Note that `iswitchb-mode' must be active for this variable to be relevant.
4434 If you decide to turn this variable on, you might well want to turn off
4435 `org-outline-path-complete-in-steps'.
4436 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4437 :group 'org-completion
4438 :type 'boolean)
4440 (defcustom org-completion-fallback-command 'hippie-expand
4441 "The expansion command called by \\[pcomplete] in normal context.
4442 Normal means, no org-mode-specific context."
4443 :group 'org-completion
4444 :type 'function)
4446 ;;; Functions and variables from their packages
4447 ;; Declared here to avoid compiler warnings
4449 ;; XEmacs only
4450 (defvar outline-mode-menu-heading)
4451 (defvar outline-mode-menu-show)
4452 (defvar outline-mode-menu-hide)
4453 (defvar zmacs-regions) ; XEmacs regions
4455 ;; Emacs only
4456 (defvar mark-active)
4458 ;; Various packages
4459 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4460 (declare-function calendar-forward-day "cal-move" (arg))
4461 (declare-function calendar-goto-date "cal-move" (date))
4462 (declare-function calendar-goto-today "cal-move" ())
4463 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4464 (defvar calc-embedded-close-formula)
4465 (defvar calc-embedded-open-formula)
4466 (declare-function cdlatex-tab "ext:cdlatex" ())
4467 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4468 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4469 (defvar font-lock-unfontify-region-function)
4470 (declare-function iswitchb-read-buffer "iswitchb"
4471 (prompt &optional default require-match start matches-set))
4472 (defvar iswitchb-temp-buflist)
4473 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4474 (defvar org-agenda-tags-todo-honor-ignore-options)
4475 (declare-function org-agenda-skip "org-agenda" ())
4476 (declare-function
4477 org-agenda-format-item "org-agenda"
4478 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4479 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4480 (declare-function org-agenda-change-all-lines "org-agenda"
4481 (newhead hdmarker &optional fixface just-this))
4482 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4483 (declare-function org-agenda-maybe-redo "org-agenda" ())
4484 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4485 (beg end))
4486 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4487 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4488 "org-agenda" (&optional end))
4489 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4490 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4491 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4492 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4493 (declare-function org-indent-mode "org-indent" (&optional arg))
4494 (declare-function parse-time-string "parse-time" (string))
4495 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4496 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4497 (defvar remember-data-file)
4498 (defvar texmathp-why)
4499 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4500 (declare-function table--at-cell-p "table" (position &optional object at-column))
4501 (declare-function calc-eval "calc" (str &optional separator &rest args))
4503 ;;;###autoload
4504 (defun turn-on-orgtbl ()
4505 "Unconditionally turn on `orgtbl-mode'."
4506 (require 'org-table)
4507 (orgtbl-mode 1))
4509 (defun org-at-table-p (&optional table-type)
4510 "Non-nil if the cursor is inside an Org table.
4511 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4512 If `org-enable-table-editor' is nil, return nil unconditionally."
4513 (and
4514 org-enable-table-editor
4515 (save-excursion
4516 (beginning-of-line)
4517 (org-looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4518 (or (not (derived-mode-p 'org-mode))
4519 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4520 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4521 (defsubst org-table-p () (org-at-table-p))
4523 (defun org-at-table.el-p ()
4524 "Non-nil when point is at a table.el table."
4525 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4526 (let ((element (org-element-at-point)))
4527 (and (eq (org-element-type element) 'table)
4528 (eq (org-element-property :type element) 'table.el)))))
4530 (defun org-table-recognize-table.el ()
4531 "If there is a table.el table nearby, recognize it and move into it."
4532 (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
4533 (beginning-of-line)
4534 (unless (or (looking-at org-table-dataline-regexp)
4535 (not (looking-at org-table1-hline-regexp)))
4536 (forward-line)
4537 (when (looking-at org-table-any-border-regexp)
4538 (forward-line -2)))
4539 (if (re-search-forward "|" (org-table-end t) t)
4540 (progn
4541 (require 'table)
4542 (if (table--at-cell-p (point)) t
4543 (message "recognizing table.el table...")
4544 (table-recognize-table)
4545 (message "recognizing table.el table...done")))
4546 (error "This should not happen"))))
4548 (defun org-at-table-hline-p ()
4549 "Non-nil when point is inside a hline in a table.
4550 Assume point is already in a table. If `org-enable-table-editor'
4551 is nil, return nil unconditionally."
4552 (and org-enable-table-editor
4553 (save-excursion
4554 (beginning-of-line)
4555 (looking-at org-table-hline-regexp))))
4557 (defun org-table-map-tables (function &optional quietly)
4558 "Apply FUNCTION to the start of all tables in the buffer."
4559 (save-excursion
4560 (save-restriction
4561 (widen)
4562 (goto-char (point-min))
4563 (while (re-search-forward org-table-any-line-regexp nil t)
4564 (unless quietly
4565 (message "Mapping tables: %d%%"
4566 (floor (* 100.0 (point)) (buffer-size))))
4567 (beginning-of-line 1)
4568 (when (and (looking-at org-table-line-regexp)
4569 ;; Exclude tables in src/example/verbatim/clocktable blocks
4570 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4571 (save-excursion (funcall function))
4572 (or (looking-at org-table-line-regexp)
4573 (forward-char 1)))
4574 (re-search-forward org-table-any-border-regexp nil 1))))
4575 (unless quietly (message "Mapping tables: done")))
4577 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4578 (declare-function org-clock-update-mode-line "org-clock" ())
4579 (declare-function org-resolve-clocks "org-clock"
4580 (&optional also-non-dangling-p prompt last-valid))
4582 (defun org-at-TBLFM-p (&optional pos)
4583 "Non-nil when point (or POS) is in #+TBLFM line."
4584 (save-excursion
4585 (goto-char (or pos (point)))
4586 (beginning-of-line)
4587 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4588 (eq (org-element-type (org-element-at-point)) 'table))))
4590 (defvar org-clock-start-time)
4591 (defvar org-clock-marker (make-marker)
4592 "Marker recording the last clock-in.")
4593 (defvar org-clock-hd-marker (make-marker)
4594 "Marker recording the last clock-in, but the headline position.")
4595 (defvar org-clock-heading ""
4596 "The heading of the current clock entry.")
4597 (defun org-clock-is-active ()
4598 "Return the buffer where the clock is currently running.
4599 Return nil if no clock is running."
4600 (marker-buffer org-clock-marker))
4602 (defun org-check-running-clock ()
4603 "Check if the current buffer contains the running clock.
4604 If yes, offer to stop it and to save the buffer with the changes."
4605 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4606 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4607 (buffer-name))))
4608 (org-clock-out)
4609 (when (y-or-n-p "Save changed buffer?")
4610 (save-buffer))))
4612 (defun org-clocktable-try-shift (dir n)
4613 "Check if this line starts a clock table, if yes, shift the time block."
4614 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4615 (org-clocktable-shift dir n)))
4617 ;;;###autoload
4618 (defun org-clock-persistence-insinuate ()
4619 "Set up hooks for clock persistence."
4620 (require 'org-clock)
4621 (add-hook 'org-mode-hook 'org-clock-load)
4622 (add-hook 'kill-emacs-hook 'org-clock-save))
4624 (defgroup org-archive nil
4625 "Options concerning archiving in Org-mode."
4626 :tag "Org Archive"
4627 :group 'org-structure)
4629 (defcustom org-archive-location "%s_archive::"
4630 "The location where subtrees should be archived.
4632 The value of this variable is a string, consisting of two parts,
4633 separated by a double-colon. The first part is a filename and
4634 the second part is a headline.
4636 When the filename is omitted, archiving happens in the same file.
4637 %s in the filename will be replaced by the current file
4638 name (without the directory part). Archiving to a different file
4639 is useful to keep archived entries from contributing to the
4640 Org-mode Agenda.
4642 The archived entries will be filed as subtrees of the specified
4643 headline. When the headline is omitted, the subtrees are simply
4644 filed away at the end of the file, as top-level entries. Also in
4645 the heading you can use %s to represent the file name, this can be
4646 useful when using the same archive for a number of different files.
4648 Here are a few examples:
4649 \"%s_archive::\"
4650 If the current file is Projects.org, archive in file
4651 Projects.org_archive, as top-level trees. This is the default.
4653 \"::* Archived Tasks\"
4654 Archive in the current file, under the top-level headline
4655 \"* Archived Tasks\".
4657 \"~/org/archive.org::\"
4658 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4660 \"~/org/archive.org::* From %s\"
4661 Archive in file ~/org/archive.org (absolute path), under headlines
4662 \"From FILENAME\" where file name is the current file name.
4664 \"~/org/datetree.org::datetree/* Finished Tasks\"
4665 The \"datetree/\" string is special, signifying to archive
4666 items to the datetree. Items are placed in either the CLOSED
4667 date of the item, or the current date if there is no CLOSED date.
4668 The heading will be a subentry to the current date. There doesn't
4669 need to be a heading, but there always needs to be a slash after
4670 datetree. For example, to store archived items directly in the
4671 datetree, use \"~/org/datetree.org::datetree/\".
4673 \"basement::** Finished Tasks\"
4674 Archive in file ./basement (relative path), as level 3 trees
4675 below the level 2 heading \"** Finished Tasks\".
4677 You may set this option on a per-file basis by adding to the buffer a
4678 line like
4680 #+ARCHIVE: basement::** Finished Tasks
4682 You may also define it locally for a subtree by setting an ARCHIVE property
4683 in the entry. If such a property is found in an entry, or anywhere up
4684 the hierarchy, it will be used."
4685 :group 'org-archive
4686 :type 'string)
4688 (defcustom org-agenda-skip-archived-trees t
4689 "Non-nil means the agenda will skip any items located in archived trees.
4690 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4691 variable is no longer recommended, you should leave it at the value t.
4692 Instead, use the key `v' to cycle the archives-mode in the agenda."
4693 :group 'org-archive
4694 :group 'org-agenda-skip
4695 :type 'boolean)
4697 (defcustom org-columns-skip-archived-trees t
4698 "Non-nil means ignore archived trees when creating column view."
4699 :group 'org-archive
4700 :group 'org-properties
4701 :type 'boolean)
4703 (defcustom org-cycle-open-archived-trees nil
4704 "Non-nil means `org-cycle' will open archived trees.
4705 An archived tree is a tree marked with the tag ARCHIVE.
4706 When nil, archived trees will stay folded. You can still open them with
4707 normal outline commands like `show-all', but not with the cycling commands."
4708 :group 'org-archive
4709 :group 'org-cycle
4710 :type 'boolean)
4712 (defcustom org-sparse-tree-open-archived-trees nil
4713 "Non-nil means sparse tree construction shows matches in archived trees.
4714 When nil, matches in these trees are highlighted, but the trees are kept in
4715 collapsed state."
4716 :group 'org-archive
4717 :group 'org-sparse-trees
4718 :type 'boolean)
4720 (defcustom org-sparse-tree-default-date-type nil
4721 "The default date type when building a sparse tree.
4722 When this is nil, a date is a scheduled or a deadline timestamp.
4723 Otherwise, these types are allowed:
4725 all: all timestamps
4726 active: only active timestamps (<...>)
4727 inactive: only inactive timestamps ([...])
4728 scheduled: only scheduled timestamps
4729 deadline: only deadline timestamps"
4730 :type '(choice (const :tag "Scheduled or deadline" nil)
4731 (const :tag "All timestamps" all)
4732 (const :tag "Only active timestamps" active)
4733 (const :tag "Only inactive timestamps" inactive)
4734 (const :tag "Only scheduled timestamps" scheduled)
4735 (const :tag "Only deadline timestamps" deadline)
4736 (const :tag "Only closed timestamps" closed))
4737 :version "25.1"
4738 :package-version '(Org . "8.3")
4739 :group 'org-sparse-trees)
4741 (defun org-cycle-hide-archived-subtrees (state)
4742 "Re-hide all archived subtrees after a visibility state change."
4743 (when (and (not org-cycle-open-archived-trees)
4744 (not (memq state '(overview folded))))
4745 (save-excursion
4746 (let* ((globalp (memq state '(contents all)))
4747 (beg (if globalp (point-min) (point)))
4748 (end (if globalp (point-max) (org-end-of-subtree t))))
4749 (org-hide-archived-subtrees beg end)
4750 (goto-char beg)
4751 (if (looking-at (concat ".*:" org-archive-tag ":"))
4752 (message "%s" (substitute-command-keys
4753 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4755 (defun org-force-cycle-archived ()
4756 "Cycle subtree even if it is archived."
4757 (interactive)
4758 (setq this-command 'org-cycle)
4759 (let ((org-cycle-open-archived-trees t))
4760 (call-interactively 'org-cycle)))
4762 (defun org-hide-archived-subtrees (beg end)
4763 "Re-hide all archived subtrees after a visibility state change."
4764 (org-with-wide-buffer
4765 (let ((case-fold-search nil)
4766 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4767 (goto-char beg)
4768 ;; Include headline point is currently on.
4769 (beginning-of-line)
4770 (while (and (< (point) end) (re-search-forward re end t))
4771 (when (member org-archive-tag (org-get-tags))
4772 (org-flag-subtree t)
4773 (org-end-of-subtree t))))))
4775 (declare-function outline-end-of-heading "outline" ())
4776 (declare-function outline-flag-region "outline" (from to flag))
4777 (defun org-flag-subtree (flag)
4778 (save-excursion
4779 (org-back-to-heading t)
4780 (outline-end-of-heading)
4781 (outline-flag-region (point)
4782 (progn (org-end-of-subtree t) (point))
4783 flag)))
4785 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4787 ;; Declare Column View Code
4789 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4790 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4791 (declare-function org-columns-compute "org-colview" (property))
4793 ;; Declare ID code
4795 (declare-function org-id-store-link "org-id")
4796 (declare-function org-id-locations-load "org-id")
4797 (declare-function org-id-locations-save "org-id")
4798 (defvar org-id-track-globally)
4800 ;;; Variables for pre-computed regular expressions, all buffer local
4802 (defvar org-todo-regexp nil
4803 "Matches any of the TODO state keywords.")
4804 (make-variable-buffer-local 'org-todo-regexp)
4805 (defvar org-not-done-regexp nil
4806 "Matches any of the TODO state keywords except the last one.")
4807 (make-variable-buffer-local 'org-not-done-regexp)
4808 (defvar org-not-done-heading-regexp nil
4809 "Matches a TODO headline that is not done.")
4810 (make-variable-buffer-local 'org-not-done-heading-regexp)
4811 (defvar org-todo-line-regexp nil
4812 "Matches a headline and puts TODO state into group 2 if present.")
4813 (make-variable-buffer-local 'org-todo-line-regexp)
4814 (defvar org-complex-heading-regexp nil
4815 "Matches a headline and puts everything into groups:
4816 group 1: the stars
4817 group 2: The todo keyword, maybe
4818 group 3: Priority cookie
4819 group 4: True headline
4820 group 5: Tags")
4821 (make-variable-buffer-local 'org-complex-heading-regexp)
4822 (defvar org-complex-heading-regexp-format nil
4823 "Printf format to make regexp to match an exact headline.
4824 This regexp will match the headline of any node which has the
4825 exact headline text that is put into the format, but may have any
4826 TODO state, priority and tags.")
4827 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4828 (defvar org-todo-line-tags-regexp nil
4829 "Matches a headline and puts TODO state into group 2 if present.
4830 Also put tags into group 4 if tags are present.")
4831 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4833 (defconst org-plain-time-of-day-regexp
4834 (concat
4835 "\\(\\<[012]?[0-9]"
4836 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4837 "\\(--?"
4838 "\\(\\<[012]?[0-9]"
4839 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4840 "\\)?")
4841 "Regular expression to match a plain time or time range.
4842 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4843 groups carry important information:
4844 0 the full match
4845 1 the first time, range or not
4846 8 the second time, if it is a range.")
4848 (defconst org-plain-time-extension-regexp
4849 (concat
4850 "\\(\\<[012]?[0-9]"
4851 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4852 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4853 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4854 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4855 groups carry important information:
4856 0 the full match
4857 7 hours of duration
4858 9 minutes of duration")
4860 (defconst org-stamp-time-of-day-regexp
4861 (concat
4862 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4863 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4864 "\\(--?"
4865 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4866 "Regular expression to match a timestamp time or time range.
4867 After a match, the following groups carry important information:
4868 0 the full match
4869 1 date plus weekday, for back referencing to make sure both times are on the same day
4870 2 the first time, range or not
4871 4 the second time, if it is a range.")
4873 (defconst org-startup-options
4874 '(("fold" org-startup-folded t)
4875 ("overview" org-startup-folded t)
4876 ("nofold" org-startup-folded nil)
4877 ("showall" org-startup-folded nil)
4878 ("showeverything" org-startup-folded showeverything)
4879 ("content" org-startup-folded content)
4880 ("indent" org-startup-indented t)
4881 ("noindent" org-startup-indented nil)
4882 ("hidestars" org-hide-leading-stars t)
4883 ("showstars" org-hide-leading-stars nil)
4884 ("odd" org-odd-levels-only t)
4885 ("oddeven" org-odd-levels-only nil)
4886 ("align" org-startup-align-all-tables t)
4887 ("noalign" org-startup-align-all-tables nil)
4888 ("inlineimages" org-startup-with-inline-images t)
4889 ("noinlineimages" org-startup-with-inline-images nil)
4890 ("latexpreview" org-startup-with-latex-preview t)
4891 ("nolatexpreview" org-startup-with-latex-preview nil)
4892 ("customtime" org-display-custom-times t)
4893 ("logdone" org-log-done time)
4894 ("lognotedone" org-log-done note)
4895 ("nologdone" org-log-done nil)
4896 ("lognoteclock-out" org-log-note-clock-out t)
4897 ("nolognoteclock-out" org-log-note-clock-out nil)
4898 ("logrepeat" org-log-repeat state)
4899 ("lognoterepeat" org-log-repeat note)
4900 ("logdrawer" org-log-into-drawer t)
4901 ("nologdrawer" org-log-into-drawer nil)
4902 ("logstatesreversed" org-log-states-order-reversed t)
4903 ("nologstatesreversed" org-log-states-order-reversed nil)
4904 ("nologrepeat" org-log-repeat nil)
4905 ("logreschedule" org-log-reschedule time)
4906 ("lognotereschedule" org-log-reschedule note)
4907 ("nologreschedule" org-log-reschedule nil)
4908 ("logredeadline" org-log-redeadline time)
4909 ("lognoteredeadline" org-log-redeadline note)
4910 ("nologredeadline" org-log-redeadline nil)
4911 ("logrefile" org-log-refile time)
4912 ("lognoterefile" org-log-refile note)
4913 ("nologrefile" org-log-refile nil)
4914 ("fninline" org-footnote-define-inline t)
4915 ("nofninline" org-footnote-define-inline nil)
4916 ("fnlocal" org-footnote-section nil)
4917 ("fnauto" org-footnote-auto-label t)
4918 ("fnprompt" org-footnote-auto-label nil)
4919 ("fnconfirm" org-footnote-auto-label confirm)
4920 ("fnplain" org-footnote-auto-label plain)
4921 ("fnadjust" org-footnote-auto-adjust t)
4922 ("nofnadjust" org-footnote-auto-adjust nil)
4923 ("constcgs" constants-unit-system cgs)
4924 ("constSI" constants-unit-system SI)
4925 ("noptag" org-tag-persistent-alist nil)
4926 ("hideblocks" org-hide-block-startup t)
4927 ("nohideblocks" org-hide-block-startup nil)
4928 ("beamer" org-startup-with-beamer-mode t)
4929 ("entitiespretty" org-pretty-entities t)
4930 ("entitiesplain" org-pretty-entities nil))
4931 "Variable associated with STARTUP options for org-mode.
4932 Each element is a list of three items: the startup options (as written
4933 in the #+STARTUP line), the corresponding variable, and the value to set
4934 this variable to if the option is found. An optional forth element PUSH
4935 means to push this value onto the list in the variable.")
4937 (defcustom org-group-tags t
4938 "When non-nil (the default), use group tags.
4939 This can be turned on/off through `org-toggle-tags-groups'."
4940 :group 'org-tags
4941 :group 'org-startup
4942 :type 'boolean)
4944 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4946 (defun org-toggle-tags-groups ()
4947 "Toggle support for group tags.
4948 Support for group tags is controlled by the option
4949 `org-group-tags', which is non-nil by default."
4950 (interactive)
4951 (setq org-group-tags (not org-group-tags))
4952 (cond ((and (derived-mode-p 'org-agenda-mode)
4953 org-group-tags)
4954 (org-agenda-redo))
4955 ((derived-mode-p 'org-mode)
4956 (let ((org-inhibit-startup t)) (org-mode))))
4957 (message "Groups tags support has been turned %s"
4958 (if org-group-tags "on" "off")))
4960 (defun org-set-regexps-and-options (&optional tags-only)
4961 "Precompute regular expressions used in the current buffer.
4962 When optional argument TAGS-ONLY is non-nil, only compute tags
4963 related expressions."
4964 (when (derived-mode-p 'org-mode)
4965 (let ((alist (org--setup-collect-keywords
4966 (org-make-options-regexp
4967 (append '("FILETAGS" "TAGS" "SETUPFILE")
4968 (and (not tags-only)
4969 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4970 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4971 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4972 (org--setup-process-tags
4973 (cdr (assq 'tags alist)) (cdr (assq 'filetags alist)))
4974 (unless tags-only
4975 ;; File properties.
4976 (org-set-local 'org-file-properties (cdr (assq 'property alist)))
4977 ;; Archive location.
4978 (let ((archive (cdr (assq 'archive alist))))
4979 (when archive (org-set-local 'org-archive-location archive)))
4980 ;; Category.
4981 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4982 (when cat
4983 (org-set-local 'org-category (intern cat))
4984 (org-set-local 'org-file-properties
4985 (org--update-property-plist
4986 "CATEGORY" cat org-file-properties))))
4987 ;; Columns.
4988 (let ((column (cdr (assq 'columns alist))))
4989 (when column (org-set-local 'org-columns-default-format column)))
4990 ;; Constants.
4991 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4992 ;; Link abbreviations.
4993 (let ((links (cdr (assq 'link alist))))
4994 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4995 ;; Priorities.
4996 (let ((priorities (cdr (assq 'priorities alist))))
4997 (when priorities
4998 (org-set-local 'org-highest-priority (nth 0 priorities))
4999 (org-set-local 'org-lowest-priority (nth 1 priorities))
5000 (org-set-local 'org-default-priority (nth 2 priorities))))
5001 ;; Scripts.
5002 (let ((scripts (assq 'scripts alist)))
5003 (when scripts
5004 (org-set-local 'org-use-sub-superscripts (cdr scripts))))
5005 ;; Startup options.
5006 (let ((startup (cdr (assq 'startup alist))))
5007 (dolist (option startup)
5008 (let ((entry (assoc-string option org-startup-options t)))
5009 (when entry
5010 (let ((var (nth 1 entry))
5011 (val (nth 2 entry)))
5012 (if (not (nth 3 entry)) (org-set-local var val)
5013 (unless (listp (symbol-value var))
5014 (org-set-local var nil))
5015 (add-to-list var val)))))))
5016 ;; TODO keywords.
5017 (org-set-local 'org-todo-kwd-alist nil)
5018 (org-set-local 'org-todo-key-alist nil)
5019 (org-set-local 'org-todo-key-trigger nil)
5020 (org-set-local 'org-todo-keywords-1 nil)
5021 (org-set-local 'org-done-keywords nil)
5022 (org-set-local 'org-todo-heads nil)
5023 (org-set-local 'org-todo-sets nil)
5024 (org-set-local 'org-todo-log-states nil)
5025 (let ((todo-sequences
5026 (or (nreverse (cdr (assq 'todo alist)))
5027 (let ((d (default-value 'org-todo-keywords)))
5028 (if (not (stringp (car d))) d
5029 ;; XXX: Backward compatibility code.
5030 (list (cons org-todo-interpretation d)))))))
5031 (dolist (sequence todo-sequences)
5032 (let* ((sequence (or (run-hook-with-args-until-success
5033 'org-todo-setup-filter-hook sequence)
5034 sequence))
5035 (sequence-type (car sequence))
5036 (keywords (cdr sequence))
5037 (sep (member "|" keywords))
5038 names alist)
5039 (dolist (k (remove "|" keywords))
5040 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5042 (error "Invalid TODO keyword %s" k))
5043 (let ((name (match-string 1 k))
5044 (key (match-string 2 k))
5045 (log (org-extract-log-state-settings k)))
5046 (push name names)
5047 (push (cons name (and key (string-to-char key))) alist)
5048 (when log (push log org-todo-log-states))))
5049 (let* ((names (nreverse names))
5050 (done (if sep (org-remove-keyword-keys (cdr sep))
5051 (last names)))
5052 (head (car names))
5053 (tail (list sequence-type head (car done) (org-last done))))
5054 (add-to-list 'org-todo-heads head 'append)
5055 (push names org-todo-sets)
5056 (setq org-done-keywords (append org-done-keywords done nil))
5057 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5058 (setq org-todo-key-alist
5059 (append org-todo-key-alist
5060 (and alist
5061 (append '((:startgroup))
5062 (nreverse alist)
5063 '((:endgroup))))))
5064 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5065 (setq org-todo-sets (nreverse org-todo-sets)
5066 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5067 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5068 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5069 ;; Compute the regular expressions and other local variables.
5070 ;; Using `org-outline-regexp-bol' would complicate them much,
5071 ;; because of the fixed white space at the end of that string.
5072 (if (not org-done-keywords)
5073 (setq org-done-keywords
5074 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5075 (setq org-not-done-keywords
5076 (org-delete-all org-done-keywords
5077 (copy-sequence org-todo-keywords-1))
5078 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5079 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5080 org-not-done-heading-regexp
5081 (format org-heading-keyword-regexp-format org-not-done-regexp)
5082 org-todo-line-regexp
5083 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5084 org-complex-heading-regexp
5085 (concat "^\\(\\*+\\)"
5086 "\\(?: +" org-todo-regexp "\\)?"
5087 "\\(?: +\\(\\[#.\\]\\)\\)?"
5088 "\\(?: +\\(.*?\\)\\)??"
5089 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5090 "[ \t]*$")
5091 org-complex-heading-regexp-format
5092 (concat "^\\(\\*+\\)"
5093 "\\(?: +" org-todo-regexp "\\)?"
5094 "\\(?: +\\(\\[#.\\]\\)\\)?"
5095 "\\(?: +"
5096 ;; Stats cookies can be stuck to body.
5097 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5098 "\\(%s\\)"
5099 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5100 "\\)"
5101 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5102 "[ \t]*$")
5103 org-todo-line-tags-regexp
5104 (concat "^\\(\\*+\\)"
5105 "\\(?: +" org-todo-regexp "\\)?"
5106 "\\(?: +\\(.*?\\)\\)??"
5107 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5108 "[ \t]*$"))
5109 (org-compute-latex-and-related-regexp)))))
5111 (defun org--setup-collect-keywords (regexp &optional files alist)
5112 "Return setup keywords values as an alist.
5114 REGEXP matches a subset of setup keywords. FILES is a list of
5115 file names already visited. It is used to avoid circular setup
5116 files. ALIST, when non-nil, is the alist computed so far.
5118 Return value contains the following keys: `archive', `category',
5119 `columns', `constants', `filetags', `link', `priorities',
5120 `property', `scripts', `startup', `tags' and `todo'."
5121 (org-with-wide-buffer
5122 (goto-char (point-min))
5123 (let ((case-fold-search t))
5124 (while (re-search-forward regexp nil t)
5125 (let ((element (org-element-at-point)))
5126 (when (eq (org-element-type element) 'keyword)
5127 (let ((key (org-element-property :key element))
5128 (value (org-element-property :value element)))
5129 (cond
5130 ((equal key "ARCHIVE")
5131 (when (org-string-nw-p value)
5132 (push (cons 'archive value) alist)))
5133 ((equal key "CATEGORY") (push (cons 'category value) alist))
5134 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5135 ((equal key "CONSTANTS")
5136 (let* ((constants (assq 'constants alist))
5137 (store (cdr constants)))
5138 (dolist (pair (org-split-string value))
5139 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5140 pair)
5141 (let* ((name (match-string 1 pair))
5142 (value (match-string 2 pair))
5143 (old (assoc name store)))
5144 (if old (setcdr old value)
5145 (push (cons name value) store)))))
5146 (if constants (setcdr constants store)
5147 (push (cons 'constants store) alist))))
5148 ((equal key "FILETAGS")
5149 (when (org-string-nw-p value)
5150 (let ((old (assq 'filetags alist))
5151 (new (apply #'nconc
5152 (mapcar (lambda (x) (org-split-string x ":"))
5153 (org-split-string value)))))
5154 (if old (setcdr old (append new (cdr old)))
5155 (push (cons 'filetags new) alist)))))
5156 ((equal key "LINK")
5157 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5158 (let ((links (assq 'link alist))
5159 (pair (cons (org-match-string-no-properties 1 value)
5160 (org-match-string-no-properties 2 value))))
5161 (if links (push pair (cdr links))
5162 (push (list 'link pair) alist)))))
5163 ((equal key "OPTIONS")
5164 (when (and (org-string-nw-p value)
5165 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5166 (push (cons 'scripts (read (match-string 1 value))) alist)))
5167 ((equal key "PRIORITIES")
5168 (push (cons 'priorities
5169 (let ((prio (org-split-string value)))
5170 (if (< (length prio) 3) '(?A ?C ?B)
5171 (mapcar #'string-to-char prio))))
5172 alist))
5173 ((equal key "PROPERTY")
5174 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5175 (let* ((property (assq 'property alist))
5176 (value (org--update-property-plist
5177 (org-match-string-no-properties 1 value)
5178 (org-match-string-no-properties 2 value)
5179 (cdr property))))
5180 (if property (setcdr property value)
5181 (push (cons 'property value) alist)))))
5182 ((equal key "STARTUP")
5183 (let ((startup (assq 'startup alist)))
5184 (if startup
5185 (setcdr startup
5186 (append (cdr startup) (org-split-string value)))
5187 (push (cons 'startup (org-split-string value)) alist))))
5188 ((equal key "TAGS")
5189 (let ((tag-cell (assq 'tags alist)))
5190 (if tag-cell
5191 (setcdr tag-cell
5192 (append (cdr tag-cell)
5193 '("\\n")
5194 (org-split-string value)))
5195 (push (cons 'tags (org-split-string value)) alist))))
5196 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5197 (let ((todo (assq 'todo alist))
5198 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5199 (org-split-string value))))
5200 (if todo (push value (cdr todo))
5201 (push (list 'todo value) alist))))
5202 ((equal key "SETUPFILE")
5203 (unless buffer-read-only ; Do not check in Gnus messages.
5204 (let ((f (and (org-string-nw-p value)
5205 (expand-file-name
5206 (org-remove-double-quotes value)))))
5207 (when (and f (file-readable-p f) (not (member f files)))
5208 (with-temp-buffer
5209 (setq default-directory (file-name-directory f))
5210 (insert-file-contents f)
5211 (setq alist
5212 ;; Fake Org mode to benefit from cache
5213 ;; without recurring needlessly.
5214 (let ((major-mode 'org-mode))
5215 (org--setup-collect-keywords
5216 regexp (cons f files) alist)))))))))))))))
5217 alist)
5219 (defun org--setup-process-tags (tags filetags)
5220 "Precompute variables used for tags.
5221 TAGS is a list of tags and tag group symbols, as strings.
5222 FILETAGS is a list of tags, as strings."
5223 ;; Process the file tags.
5224 (org-set-local 'org-file-tags
5225 (mapcar #'org-add-prop-inherited filetags))
5226 ;; Provide default tags if no local tags are found.
5227 (when (and (not tags) org-tag-alist)
5228 (setq tags
5229 (mapcar (lambda (tag)
5230 (case (car tag)
5231 (:startgroup "{")
5232 (:endgroup "}")
5233 (:startgrouptag "[")
5234 (:endgrouptag "]")
5235 (:grouptags ":")
5236 (:newline "\\n")
5237 (otherwise (concat (car tag)
5238 (and (characterp (cdr tag))
5239 (format "(%c)" (cdr tag)))))))
5240 org-tag-alist)))
5241 ;; Process the tags.
5242 (org-set-local 'org-tag-groups-alist nil)
5243 (org-set-local 'org-tag-alist nil)
5244 (let (group-flag)
5245 (while tags
5246 (let ((e (car tags)))
5247 (setq tags (cdr tags))
5248 (cond
5249 ((equal e "{")
5250 (push '(:startgroup) org-tag-alist)
5251 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5252 ((equal e "}")
5253 (push '(:endgroup) org-tag-alist)
5254 (setq group-flag nil))
5255 ((equal e "[")
5256 (push '(:startgrouptag) org-tag-alist)
5257 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5258 ((equal e "]")
5259 (push '(:endgrouptag) org-tag-alist)
5260 (setq group-flag nil))
5261 ((equal e ":")
5262 (push '(:grouptags) org-tag-alist)
5263 (setq group-flag 'append))
5264 ((equal e "\\n") (push '(:newline) org-tag-alist))
5265 ((string-match
5266 (org-re (concat "\\`\\([[:alnum:]_@#%]+"
5267 "\\|{.+?}\\)" ; regular expression
5268 "\\(?:(\\(.\\))\\)?\\'")) e)
5269 (let ((tag (match-string 1 e))
5270 (key (and (match-beginning 2)
5271 (string-to-char (match-string 2 e)))))
5272 (cond ((eq group-flag 'append)
5273 (setcar org-tag-groups-alist
5274 (append (car org-tag-groups-alist) (list tag))))
5275 (group-flag (push (list tag) org-tag-groups-alist)))
5276 ;; Push all tags in groups, no matter if they already exist.
5277 (unless (and (not group-flag) (assoc tag org-tag-alist))
5278 (push (cons tag key) org-tag-alist))))))))
5279 (setq org-tag-alist (nreverse org-tag-alist)))
5281 (defun org-file-contents (file &optional noerror)
5282 "Return the contents of FILE, as a string."
5283 (if (and file (file-readable-p file))
5284 (with-temp-buffer
5285 (insert-file-contents file)
5286 (buffer-string))
5287 (funcall (if noerror 'message 'error)
5288 "Cannot read file \"%s\"%s"
5289 file
5290 (let ((from (buffer-file-name (buffer-base-buffer))))
5291 (if from (concat " (referenced in file \"" from "\")") "")))))
5293 (defun org-extract-log-state-settings (x)
5294 "Extract the log state setting from a TODO keyword string.
5295 This will extract info from a string like \"WAIT(w@/!)\"."
5296 (let (kw key log1 log2)
5297 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5298 (setq kw (match-string 1 x)
5299 key (and (match-end 2) (match-string 2 x))
5300 log1 (and (match-end 3) (match-string 3 x))
5301 log2 (and (match-end 4) (match-string 4 x)))
5302 (and (or log1 log2)
5303 (list kw
5304 (and log1 (if (equal log1 "!") 'time 'note))
5305 (and log2 (if (equal log2 "!") 'time 'note)))))))
5307 (defun org-remove-keyword-keys (list)
5308 "Remove a pair of parenthesis at the end of each string in LIST."
5309 (mapcar (lambda (x)
5310 (if (string-match "(.*)$" x)
5311 (substring x 0 (match-beginning 0))
5313 list))
5315 (defun org-assign-fast-keys (alist)
5316 "Assign fast keys to a keyword-key alist.
5317 Respect keys that are already there."
5318 (let (new e (alt ?0))
5319 (while (setq e (pop alist))
5320 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5321 (cdr e)) ;; Key already assigned.
5322 (push e new)
5323 (let ((clist (string-to-list (downcase (car e))))
5324 (used (append new alist)))
5325 (when (= (car clist) ?@)
5326 (pop clist))
5327 (while (and clist (rassoc (car clist) used))
5328 (pop clist))
5329 (unless clist
5330 (while (rassoc alt used)
5331 (incf alt)))
5332 (push (cons (car e) (or (car clist) alt)) new))))
5333 (nreverse new)))
5335 ;;; Some variables used in various places
5337 (defvar org-window-configuration nil
5338 "Used in various places to store a window configuration.")
5339 (defvar org-selected-window nil
5340 "Used in various places to store a window configuration.")
5341 (defvar org-finish-function nil
5342 "Function to be called when `C-c C-c' is used.
5343 This is for getting out of special buffers like capture.")
5346 ;; FIXME: Occasionally check by commenting these, to make sure
5347 ;; no other functions uses these, forgetting to let-bind them.
5348 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5349 (defvar org-last-state)
5350 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5352 ;; Defined somewhere in this file, but used before definition.
5353 (defvar org-entities) ;; defined in org-entities.el
5354 (defvar org-struct-menu)
5355 (defvar org-org-menu)
5356 (defvar org-tbl-menu)
5358 ;;;; Define the Org-mode
5360 ;; We use a before-change function to check if a table might need
5361 ;; an update.
5362 (defvar org-table-may-need-update t
5363 "Indicates that a table might need an update.
5364 This variable is set by `org-before-change-function'.
5365 `org-table-align' sets it back to nil.")
5366 (defun org-before-change-function (beg end)
5367 "Every change indicates that a table might need an update."
5368 (setq org-table-may-need-update t))
5369 (defvar org-mode-map)
5370 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5371 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5372 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5373 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5374 (defvar org-table-buffer-is-an nil)
5376 (defvar bidi-paragraph-direction)
5377 (defvar buffer-face-mode-face)
5379 (require 'outline)
5380 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5381 (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"))
5382 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5384 ;; Other stuff we need.
5385 (require 'time-date)
5386 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5387 (require 'easymenu)
5388 (autoload 'easy-menu-add "easymenu")
5389 (require 'overlay)
5391 ;; (require 'org-macs) moved higher up in the file before it is first used
5392 (require 'org-entities)
5393 ;; (require 'org-compat) moved higher up in the file before it is first used
5394 (require 'org-faces)
5395 (require 'org-list)
5396 (require 'org-pcomplete)
5397 (require 'org-src)
5398 (require 'org-footnote)
5399 (require 'org-macro)
5401 ;; babel
5402 (require 'ob)
5404 ;;;###autoload
5405 (define-derived-mode org-mode outline-mode "Org"
5406 "Outline-based notes management and organizer, alias
5407 \"Carsten's outline-mode for keeping track of everything.\"
5409 Org-mode develops organizational tasks around a NOTES file which
5410 contains information about projects as plain text. Org-mode is
5411 implemented on top of outline-mode, which is ideal to keep the content
5412 of large files well structured. It supports ToDo items, deadlines and
5413 time stamps, which magically appear in the diary listing of the Emacs
5414 calendar. Tables are easily created with a built-in table editor.
5415 Plain text URL-like links connect to websites, emails (VM), Usenet
5416 messages (Gnus), BBDB entries, and any files related to the project.
5417 For printing and sharing of notes, an Org-mode file (or a part of it)
5418 can be exported as a structured ASCII or HTML file.
5420 The following commands are available:
5422 \\{org-mode-map}"
5424 ;; Get rid of Outline menus, they are not needed
5425 ;; Need to do this here because define-derived-mode sets up
5426 ;; the keymap so late. Still, it is a waste to call this each time
5427 ;; we switch another buffer into org-mode.
5428 (if (featurep 'xemacs)
5429 (when (boundp 'outline-mode-menu-heading)
5430 ;; Assume this is Greg's port, it uses easymenu
5431 (easy-menu-remove outline-mode-menu-heading)
5432 (easy-menu-remove outline-mode-menu-show)
5433 (easy-menu-remove outline-mode-menu-hide))
5434 (define-key org-mode-map [menu-bar headings] 'undefined)
5435 (define-key org-mode-map [menu-bar hide] 'undefined)
5436 (define-key org-mode-map [menu-bar show] 'undefined))
5438 (org-load-modules-maybe)
5439 (when (featurep 'xemacs)
5440 (easy-menu-add org-org-menu)
5441 (easy-menu-add org-tbl-menu))
5442 (org-install-agenda-files-menu)
5443 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5444 (add-to-invisibility-spec '(org-cwidth))
5445 (add-to-invisibility-spec '(org-hide-block . t))
5446 (when (featurep 'xemacs)
5447 (org-set-local 'line-move-ignore-invisible t))
5448 (org-set-local 'outline-regexp org-outline-regexp)
5449 (org-set-local 'outline-level 'org-outline-level)
5450 (setq bidi-paragraph-direction 'left-to-right)
5451 (when (and org-ellipsis
5452 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5453 (fboundp 'make-glyph-code))
5454 (unless org-display-table
5455 (setq org-display-table (make-display-table)))
5456 (set-display-table-slot
5457 org-display-table 4
5458 (vconcat (mapcar
5459 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5460 org-ellipsis)))
5461 (if (stringp org-ellipsis) org-ellipsis "..."))))
5462 (setq buffer-display-table org-display-table))
5463 (org-set-regexps-and-options)
5464 (org-set-font-lock-defaults)
5465 (when (and org-tag-faces (not org-tags-special-faces-re))
5466 ;; tag faces set outside customize.... force initialization.
5467 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5468 ;; Calc embedded
5469 (org-set-local 'calc-embedded-open-mode "# ")
5470 ;; Modify a few syntax entries
5471 (modify-syntax-entry ?@ "w")
5472 (modify-syntax-entry ?\" "\"")
5473 (modify-syntax-entry ?\\ "_")
5474 (modify-syntax-entry ?~ "_")
5475 (if org-startup-truncated (setq truncate-lines t))
5476 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5477 (org-set-local 'font-lock-unfontify-region-function
5478 'org-unfontify-region)
5479 ;; Activate before-change-function
5480 (org-set-local 'org-table-may-need-update t)
5481 (org-add-hook 'before-change-functions 'org-before-change-function nil
5482 'local)
5483 ;; Check for running clock before killing a buffer
5484 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5485 ;; Initialize macros templates.
5486 (org-macro-initialize-templates)
5487 ;; Initialize radio targets.
5488 (org-update-radio-target-regexp)
5489 ;; Indentation.
5490 (org-set-local 'indent-line-function 'org-indent-line)
5491 (org-set-local 'indent-region-function 'org-indent-region)
5492 ;; Filling and auto-filling.
5493 (org-setup-filling)
5494 ;; Comments.
5495 (org-setup-comments-handling)
5496 ;; Initialize cache.
5497 (org-element-cache-reset)
5498 ;; Beginning/end of defun
5499 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5500 (org-set-local 'end-of-defun-function
5501 (lambda ()
5502 (if (not (org-at-heading-p))
5503 (org-forward-element)
5504 (org-forward-element)
5505 (forward-char -1))))
5506 ;; Next error for sparse trees
5507 (org-set-local 'next-error-function 'org-occur-next-match)
5508 ;; Make sure dependence stuff works reliably, even for users who set it
5509 ;; too late :-(
5510 (if org-enforce-todo-dependencies
5511 (add-hook 'org-blocker-hook
5512 'org-block-todo-from-children-or-siblings-or-parent)
5513 (remove-hook 'org-blocker-hook
5514 'org-block-todo-from-children-or-siblings-or-parent))
5515 (if org-enforce-todo-checkbox-dependencies
5516 (add-hook 'org-blocker-hook
5517 'org-block-todo-from-checkboxes)
5518 (remove-hook 'org-blocker-hook
5519 'org-block-todo-from-checkboxes))
5521 ;; Align options lines
5522 (org-set-local
5523 'align-mode-rules-list
5524 '((org-in-buffer-settings
5525 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5526 (modes . '(org-mode)))))
5528 ;; Imenu
5529 (org-set-local 'imenu-create-index-function
5530 'org-imenu-get-tree)
5532 ;; Make isearch reveal context
5533 (if (or (featurep 'xemacs)
5534 (not (boundp 'outline-isearch-open-invisible-function)))
5535 ;; Emacs 21 and XEmacs make use of the hook
5536 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5537 ;; Emacs 22 deals with this through a special variable
5538 (org-set-local 'outline-isearch-open-invisible-function
5539 (lambda (&rest ignore) (org-show-context 'isearch))))
5541 ;; Setup the pcomplete hooks
5542 (set (make-local-variable 'pcomplete-command-completion-function)
5543 'org-pcomplete-initial)
5544 (set (make-local-variable 'pcomplete-command-name-function)
5545 'org-command-at-point)
5546 (set (make-local-variable 'pcomplete-default-completion-function)
5547 'ignore)
5548 (set (make-local-variable 'pcomplete-parse-arguments-function)
5549 'org-parse-arguments)
5550 (set (make-local-variable 'pcomplete-termination-string) "")
5551 (when (>= emacs-major-version 23)
5552 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5554 ;; If empty file that did not turn on org-mode automatically, make it to.
5555 (if (and org-insert-mode-line-in-empty-file
5556 (org-called-interactively-p 'any)
5557 (= (point-min) (point-max)))
5558 (insert "# -*- mode: org -*-\n\n"))
5559 (unless org-inhibit-startup
5560 (org-unmodified
5561 (and org-startup-with-beamer-mode (org-beamer-mode))
5562 (when org-startup-align-all-tables
5563 (org-table-map-tables 'org-table-align 'quietly))
5564 (when org-startup-with-inline-images
5565 (org-display-inline-images))
5566 (when org-startup-with-latex-preview
5567 (org-toggle-latex-fragment))
5568 (unless org-inhibit-startup-visibility-stuff
5569 (org-set-startup-visibility))
5570 (org-refresh-effort-properties)))
5571 ;; Try to set org-hide correctly
5572 (let ((foreground (org-find-invisible-foreground)))
5573 (if foreground
5574 (set-face-foreground 'org-hide foreground))))
5576 ;; Update `customize-package-emacs-version-alist'
5577 (add-to-list 'customize-package-emacs-version-alist
5578 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5579 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5580 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5582 (defvar org-mode-transpose-word-syntax-table
5583 (let ((st (make-syntax-table text-mode-syntax-table)))
5584 (mapc (lambda(c) (modify-syntax-entry
5585 (string-to-char (car c)) "w p" st))
5586 org-emphasis-alist)
5587 st))
5589 (when (fboundp 'abbrev-table-put)
5590 (abbrev-table-put org-mode-abbrev-table
5591 :parents (list text-mode-abbrev-table)))
5593 (defun org-find-invisible-foreground ()
5594 (let ((candidates (remove
5595 "unspecified-bg"
5596 (nconc
5597 (list (face-background 'default)
5598 (face-background 'org-default))
5599 (mapcar
5600 (lambda (alist)
5601 (when (boundp alist)
5602 (cdr (assoc 'background-color (symbol-value alist)))))
5603 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5604 (list (face-foreground 'org-hide))))))
5605 (car (remove nil candidates))))
5607 (defun org-current-time (&optional rounding-minutes past)
5608 "Current time, possibly rounded to ROUNDING-MINUTES.
5609 When ROUNDING-MINUTES is not an integer, fall back on the car of
5610 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5611 the rounding returns a past time."
5612 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5613 (car org-time-stamp-rounding-minutes)))
5614 (time (decode-time)) res)
5615 (if (< r 1)
5616 (current-time)
5617 (setq res
5618 (apply 'encode-time
5619 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5620 (nthcdr 2 time))))
5621 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5622 (seconds-to-time (- (org-float-time res) (* r 60)))
5623 res))))
5625 (defun org-today ()
5626 "Return today date, considering `org-extend-today-until'."
5627 (time-to-days
5628 (time-subtract (current-time)
5629 (list 0 (* 3600 org-extend-today-until) 0))))
5631 ;;;; Font-Lock stuff, including the activators
5633 (defvar org-mouse-map (make-sparse-keymap))
5634 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5635 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5636 (when org-mouse-1-follows-link
5637 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5638 (when org-tab-follows-link
5639 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5640 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5642 (require 'font-lock)
5644 (defconst org-non-link-chars "]\t\n\r<>")
5645 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5646 "file+sys" "news" "shell" "elisp" "doi" "message"
5647 "help"))
5648 (defvar org-link-types-re nil
5649 "Matches a link that has a url-like prefix like \"http:\"")
5650 (defvar org-link-re-with-space nil
5651 "Matches a link with spaces, optional angular brackets around it.")
5652 (defvar org-link-re-with-space2 nil
5653 "Matches a link with spaces, optional angular brackets around it.")
5654 (defvar org-link-re-with-space3 nil
5655 "Matches a link with spaces, only for internal part in bracket links.")
5656 (defvar org-angle-link-re nil
5657 "Matches link with angular brackets, spaces are allowed.")
5658 (defvar org-plain-link-re nil
5659 "Matches plain link, without spaces.")
5660 (defvar org-bracket-link-regexp nil
5661 "Matches a link in double brackets.")
5662 (defvar org-bracket-link-analytic-regexp nil
5663 "Regular expression used to analyze links.
5664 Here is what the match groups contain after a match:
5665 1: http:
5666 2: http
5667 3: path
5668 4: [desc]
5669 5: desc")
5670 (defvar org-bracket-link-analytic-regexp++ nil
5671 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5672 (defvar org-any-link-re nil
5673 "Regular expression matching any link.")
5675 (defconst org-match-sexp-depth 3
5676 "Number of stacked braces for sub/superscript matching.")
5678 (defun org-create-multibrace-regexp (left right n)
5679 "Create a regular expression which will match a balanced sexp.
5680 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5681 as single character strings.
5682 The regexp returned will match the entire expression including the
5683 delimiters. It will also define a single group which contains the
5684 match except for the outermost delimiters. The maximum depth of
5685 stacked delimiters is N. Escaping delimiters is not possible."
5686 (let* ((nothing (concat "[^" left right "]*?"))
5687 (or "\\|")
5688 (re nothing)
5689 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5690 (while (> n 1)
5691 (setq n (1- n)
5692 re (concat re or next)
5693 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5694 (concat left "\\(" re "\\)" right)))
5696 (defconst org-match-substring-regexp
5697 (concat
5698 "\\(\\S-\\)\\([_^]\\)\\("
5699 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5700 "\\|"
5701 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5702 "\\|"
5703 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5704 "The regular expression matching a sub- or superscript.")
5706 (defconst org-match-substring-with-braces-regexp
5707 (concat
5708 "\\(\\S-\\)\\([_^]\\)"
5709 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5710 "The regular expression matching a sub- or superscript, forcing braces.")
5712 (defun org-make-link-regexps ()
5713 "Update the link regular expressions.
5714 This should be called after the variable `org-link-types' has changed."
5715 (let ((types-re (regexp-opt org-link-types t)))
5716 (setq org-link-types-re
5717 (concat "\\`" types-re ":")
5718 org-link-re-with-space
5719 (concat "<?" types-re ":"
5720 "\\([^" org-non-link-chars " ]"
5721 "[^" org-non-link-chars "]*"
5722 "[^" org-non-link-chars " ]\\)>?")
5723 org-link-re-with-space2
5724 (concat "<?" types-re ":"
5725 "\\([^" org-non-link-chars " ]"
5726 "[^\t\n\r]*"
5727 "[^" org-non-link-chars " ]\\)>?")
5728 org-link-re-with-space3
5729 (concat "<?" types-re ":"
5730 "\\([^" org-non-link-chars " ]"
5731 "[^\t\n\r]*\\)")
5732 org-angle-link-re
5733 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5734 types-re)
5735 org-plain-link-re
5736 (concat
5737 "\\<" types-re ":"
5738 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5739 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5740 org-bracket-link-regexp
5741 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5742 org-bracket-link-analytic-regexp
5743 (concat
5744 "\\[\\["
5745 "\\(" types-re ":\\)?"
5746 "\\([^]]+\\)"
5747 "\\]"
5748 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5749 "\\]")
5750 org-bracket-link-analytic-regexp++
5751 (concat
5752 "\\[\\["
5753 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5754 "\\([^]]+\\)"
5755 "\\]"
5756 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5757 "\\]")
5758 org-any-link-re
5759 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5760 org-angle-link-re "\\)\\|\\("
5761 org-plain-link-re "\\)"))))
5763 (org-make-link-regexps)
5765 (defvar org-emph-face nil)
5767 (defun org-do-emphasis-faces (limit)
5768 "Run through the buffer and emphasize strings."
5769 (let (rtn a)
5770 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5771 (let* ((border (char-after (match-beginning 3)))
5772 (bre (regexp-quote (char-to-string border))))
5773 (if (and (not (= border (char-after (match-beginning 4))))
5774 (not (save-match-data
5775 (string-match (concat bre ".*" bre)
5776 (replace-regexp-in-string
5777 "\n" " "
5778 (substring (match-string 2) 1 -1))))))
5779 (progn
5780 (setq rtn t)
5781 (setq a (assoc (match-string 3) org-emphasis-alist))
5782 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5783 'face
5784 (nth 1 a))
5785 (and (nth 2 a)
5786 (org-remove-flyspell-overlays-in
5787 (match-beginning 0) (match-end 0)))
5788 (add-text-properties (match-beginning 2) (match-end 2)
5789 '(font-lock-multiline t org-emphasis t))
5790 (when org-hide-emphasis-markers
5791 (add-text-properties (match-end 4) (match-beginning 5)
5792 '(invisible org-link))
5793 (add-text-properties (match-beginning 3) (match-end 3)
5794 '(invisible org-link))))))
5795 (goto-char (1+ (match-beginning 0))))
5796 rtn))
5798 (defun org-emphasize (&optional char)
5799 "Insert or change an emphasis, i.e. a font like bold or italic.
5800 If there is an active region, change that region to a new emphasis.
5801 If there is no region, just insert the marker characters and position
5802 the cursor between them.
5803 CHAR should be the marker character. If it is a space, it means to
5804 remove the emphasis of the selected region.
5805 If CHAR is not given (for example in an interactive call) it will be
5806 prompted for."
5807 (interactive)
5808 (let ((erc org-emphasis-regexp-components)
5809 (prompt "")
5810 (string "") beg end move c s)
5811 (if (org-region-active-p)
5812 (setq beg (region-beginning) end (region-end)
5813 string (buffer-substring beg end))
5814 (setq move t))
5816 (unless char
5817 (message "Emphasis marker or tag: [%s]"
5818 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5819 (setq char (read-char-exclusive)))
5820 (if (equal char ?\ )
5821 (setq s "" move nil)
5822 (unless (assoc (char-to-string char) org-emphasis-alist)
5823 (user-error "No such emphasis marker: \"%c\"" char))
5824 (setq s (char-to-string char)))
5825 (while (and (> (length string) 1)
5826 (equal (substring string 0 1) (substring string -1))
5827 (assoc (substring string 0 1) org-emphasis-alist))
5828 (setq string (substring string 1 -1)))
5829 (setq string (concat s string s))
5830 (if beg (delete-region beg end))
5831 (unless (or (bolp)
5832 (string-match (concat "[" (nth 0 erc) "\n]")
5833 (char-to-string (char-before (point)))))
5834 (insert " "))
5835 (unless (or (eobp)
5836 (string-match (concat "[" (nth 1 erc) "\n]")
5837 (char-to-string (char-after (point)))))
5838 (insert " ") (backward-char 1))
5839 (insert string)
5840 (and move (backward-char 1))))
5842 (defconst org-nonsticky-props
5843 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5845 (defsubst org-rear-nonsticky-at (pos)
5846 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5848 (defun org-activate-plain-links (limit)
5849 "Add link properties for plain links."
5850 (let (f hl)
5851 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5852 (not (member 'org-tag
5853 (get-text-property (1- (match-beginning 0)) 'face)))
5854 (not (org-in-src-block-p)))
5855 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5856 (setq f (get-text-property (match-beginning 0) 'face))
5857 (setq hl (org-match-string-no-properties 0))
5858 (if (or (eq f 'org-tag)
5859 (and (listp f) (memq 'org-tag f)))
5861 (add-text-properties (match-beginning 0) (match-end 0)
5862 (list 'mouse-face 'highlight
5863 'face 'org-link
5864 'htmlize-link `(:uri ,hl)
5865 'keymap org-mouse-map))
5866 (org-rear-nonsticky-at (match-end 0)))
5867 t)))
5869 (defun org-activate-code (limit)
5870 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5871 (progn
5872 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5873 (remove-text-properties (match-beginning 0) (match-end 0)
5874 '(display t invisible t intangible t))
5875 t)))
5877 (defcustom org-src-fontify-natively t
5878 "When non-nil, fontify code in code blocks."
5879 :type 'boolean
5880 :version "24.4"
5881 :package-version '(Org . "8.3")
5882 :group 'org-appearance
5883 :group 'org-babel)
5885 (defcustom org-allow-promoting-top-level-subtree nil
5886 "When non-nil, allow promoting a top level subtree.
5887 The leading star of the top level headline will be replaced
5888 by a #."
5889 :type 'boolean
5890 :version "24.1"
5891 :group 'org-appearance)
5893 (defun org-fontify-meta-lines-and-blocks (limit)
5894 (condition-case nil
5895 (org-fontify-meta-lines-and-blocks-1 limit)
5896 (error (message "org-mode fontification error"))))
5898 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5899 "Fontify #+ lines and blocks."
5900 (let ((case-fold-search t))
5901 (if (re-search-forward
5902 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5903 limit t)
5904 (let ((beg (match-beginning 0))
5905 (block-start (match-end 0))
5906 (block-end nil)
5907 (lang (match-string 7))
5908 (beg1 (line-beginning-position 2))
5909 (dc1 (downcase (match-string 2)))
5910 (dc3 (downcase (match-string 3)))
5911 end end1 quoting block-type ovl)
5912 (cond
5913 ((and (match-end 4) (equal dc3 "+begin"))
5914 ;; Truly a block
5915 (setq block-type (downcase (match-string 5))
5916 quoting (member block-type org-protecting-blocks))
5917 (when (re-search-forward
5918 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5919 nil t) ;; on purpose, we look further than LIMIT
5920 (setq end (min (point-max) (match-end 0))
5921 end1 (min (point-max) (1- (match-beginning 0))))
5922 (setq block-end (match-beginning 0))
5923 (when quoting
5924 (org-remove-flyspell-overlays-in beg1 end1)
5925 (remove-text-properties beg end
5926 '(display t invisible t intangible t)))
5927 (add-text-properties
5928 beg end '(font-lock-fontified t font-lock-multiline t))
5929 (add-text-properties beg beg1 '(face org-meta-line))
5930 (org-remove-flyspell-overlays-in beg beg1)
5931 (add-text-properties ; For end_src
5932 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5933 (org-remove-flyspell-overlays-in end1 end)
5934 (cond
5935 ((and lang (not (string= lang "")) org-src-fontify-natively)
5936 (org-src-font-lock-fontify-block lang block-start block-end)
5937 (add-text-properties beg1 block-end '(src-block t)))
5938 (quoting
5939 (add-text-properties beg1 (min (point-max) (1+ end1))
5940 '(face org-block))) ; end of source block
5941 ((not org-fontify-quote-and-verse-blocks))
5942 ((string= block-type "quote")
5943 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5944 ((string= block-type "verse")
5945 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5946 (add-text-properties beg beg1 '(face org-block-begin-line))
5947 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5948 '(face org-block-end-line))
5950 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5951 (org-remove-flyspell-overlays-in
5952 (match-beginning 0)
5953 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5954 (add-text-properties
5955 beg (match-end 3)
5956 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5957 '(font-lock-fontified t invisible t)
5958 '(font-lock-fontified t face org-document-info-keyword)))
5959 (add-text-properties
5960 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5961 (if (string-equal dc1 "+title:")
5962 '(font-lock-fontified t face org-document-title)
5963 '(font-lock-fontified t face org-document-info))))
5964 ((equal dc1 "+caption:")
5965 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5966 (remove-text-properties (match-beginning 0) (match-end 0)
5967 '(display t invisible t intangible t))
5968 (add-text-properties (match-beginning 1) (match-end 3)
5969 '(font-lock-fontified t face org-meta-line))
5970 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5971 '(font-lock-fontified t face org-block))
5973 ((member dc3 '(" " ""))
5974 (org-remove-flyspell-overlays-in beg (match-end 0))
5975 (add-text-properties
5976 beg (match-end 0)
5977 '(font-lock-fontified t face font-lock-comment-face)))
5978 (t ;; just any other in-buffer setting, but not indented
5979 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5980 (remove-text-properties (match-beginning 0) (match-end 0)
5981 '(display t invisible t intangible t))
5982 (add-text-properties beg (match-end 0)
5983 '(font-lock-fontified t face org-meta-line))
5984 t))))))
5986 (defun org-fontify-drawers (limit)
5987 "Fontify drawers."
5988 (when (re-search-forward org-drawer-regexp limit t)
5989 (add-text-properties
5990 (match-beginning 0) (match-end 0)
5991 '(font-lock-fontified t face org-special-keyword))
5992 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5995 (defun org-fontify-macros (limit)
5996 "Fontify macros."
5997 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5998 (add-text-properties
5999 (match-beginning 0) (match-end 0)
6000 '(font-lock-fontified t face org-macro))
6001 (when org-hide-macro-markers
6002 (add-text-properties (match-end 2) (match-beginning 2)
6003 '(invisible t))
6004 (add-text-properties (match-beginning 1) (match-end 1)
6005 '(invisible t)))
6006 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6009 (defun org-activate-angle-links (limit)
6010 "Add text properties for angle links."
6011 (if (and (re-search-forward org-angle-link-re limit t)
6012 (not (org-in-src-block-p)))
6013 (progn
6014 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6015 (add-text-properties (match-beginning 0) (match-end 0)
6016 (list 'mouse-face 'highlight
6017 'keymap org-mouse-map
6018 'font-lock-multiline t))
6019 (org-rear-nonsticky-at (match-end 0))
6020 t)))
6022 (defun org-activate-footnote-links (limit)
6023 "Add text properties for footnotes."
6024 (let ((fn (org-footnote-next-reference-or-definition limit)))
6025 (when fn
6026 (let* ((beg (nth 1 fn))
6027 (end (nth 2 fn))
6028 (label (car fn))
6029 (referencep (/= (line-beginning-position) beg)))
6030 (when (and referencep (nth 3 fn))
6031 (save-excursion
6032 (goto-char beg)
6033 (search-forward (or label "fn:"))
6034 (org-remove-flyspell-overlays-in beg (match-end 0))))
6035 (add-text-properties beg end
6036 (list 'mouse-face 'highlight
6037 'keymap org-mouse-map
6038 'help-echo
6039 (if referencep "Footnote reference"
6040 "Footnote definition")
6041 'font-lock-fontified t
6042 'font-lock-multiline t
6043 'face 'org-footnote))))))
6045 (defun org-activate-bracket-links (limit)
6046 "Add text properties for bracketed links."
6047 (if (and (re-search-forward org-bracket-link-regexp limit t)
6048 (not (org-in-src-block-p)))
6049 (let* ((hl (org-match-string-no-properties 1))
6050 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6051 (ip (org-maybe-intangible
6052 (list 'invisible 'org-link
6053 'keymap org-mouse-map 'mouse-face 'highlight
6054 'font-lock-multiline t 'help-echo help
6055 'htmlize-link `(:uri ,hl))))
6056 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6057 'font-lock-multiline t 'help-echo help
6058 'htmlize-link `(:uri ,hl))))
6059 ;; We need to remove the invisible property here. Table narrowing
6060 ;; may have made some of this invisible.
6061 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6062 (remove-text-properties (match-beginning 0) (match-end 0)
6063 '(invisible nil))
6064 (if (match-end 3)
6065 (progn
6066 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6067 (org-rear-nonsticky-at (match-beginning 3))
6068 (add-text-properties (match-beginning 3) (match-end 3) vp)
6069 (org-rear-nonsticky-at (match-end 3))
6070 (add-text-properties (match-end 3) (match-end 0) ip)
6071 (org-rear-nonsticky-at (match-end 0)))
6072 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6073 (org-rear-nonsticky-at (match-beginning 1))
6074 (add-text-properties (match-beginning 1) (match-end 1) vp)
6075 (org-rear-nonsticky-at (match-end 1))
6076 (add-text-properties (match-end 1) (match-end 0) ip)
6077 (org-rear-nonsticky-at (match-end 0)))
6078 t)))
6080 (defun org-activate-dates (limit)
6081 "Add text properties for dates."
6082 (if (and (re-search-forward org-tsr-regexp-both limit t)
6083 (not (equal (char-before (match-beginning 0)) 91)))
6084 (progn
6085 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6086 (add-text-properties (match-beginning 0) (match-end 0)
6087 (list 'mouse-face 'highlight
6088 'keymap org-mouse-map))
6089 (org-rear-nonsticky-at (match-end 0))
6090 (when org-display-custom-times
6091 (if (match-end 3)
6092 (org-display-custom-time (match-beginning 3) (match-end 3)))
6093 (org-display-custom-time (match-beginning 1) (match-end 1)))
6094 t)))
6096 (defvar org-target-link-regexp nil
6097 "Regular expression matching radio targets in plain text.")
6098 (make-variable-buffer-local 'org-target-link-regexp)
6100 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6101 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6102 border border border))
6103 "Regular expression matching a link target.")
6105 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6106 "Regular expression matching a radio target.")
6108 (defconst org-any-target-regexp
6109 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6110 "Regular expression matching any target.")
6112 (defun org-activate-target-links (limit)
6113 "Add text properties for target matches."
6114 (when org-target-link-regexp
6115 (let ((case-fold-search t))
6116 (if (re-search-forward org-target-link-regexp limit t)
6117 (progn
6118 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6119 (add-text-properties (match-beginning 1) (match-end 1)
6120 (list 'mouse-face 'highlight
6121 'keymap org-mouse-map
6122 'help-echo "Radio target link"
6123 'org-linked-text t))
6124 (org-rear-nonsticky-at (match-end 1))
6125 t)))))
6127 (defun org-update-radio-target-regexp ()
6128 "Find all radio targets in this file and update the regular expression.
6129 Also refresh fontification if needed."
6130 (interactive)
6131 (let ((old-regexp org-target-link-regexp)
6132 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6133 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6134 (targets
6135 (org-with-wide-buffer
6136 (goto-char (point-min))
6137 (let (rtn)
6138 (while (re-search-forward org-radio-target-regexp nil t)
6139 ;; Make sure point is really within the object.
6140 (backward-char)
6141 (let ((obj (org-element-context)))
6142 (when (eq (org-element-type obj) 'radio-target)
6143 (add-to-list 'rtn (org-element-property :value obj)))))
6144 rtn))))
6145 (setq org-target-link-regexp
6146 (and targets
6147 (concat before-re
6148 (mapconcat
6149 (lambda (x)
6150 (replace-regexp-in-string
6151 " +" "\\s-+" (regexp-quote x) t t))
6152 targets
6153 "\\|")
6154 after-re)))
6155 (unless (equal old-regexp org-target-link-regexp)
6156 ;; Clean-up cache.
6157 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6158 ((not org-target-link-regexp) old-regexp)
6160 (concat before-re
6161 (mapconcat
6162 (lambda (re)
6163 (substring re (length before-re)
6164 (- (length after-re))))
6165 (list old-regexp org-target-link-regexp)
6166 "\\|")
6167 after-re)))))
6168 (org-with-wide-buffer
6169 (goto-char (point-min))
6170 (while (re-search-forward regexp nil t)
6171 (org-element-cache-refresh (match-beginning 1)))))
6172 ;; Re fontify buffer.
6173 (when (memq 'radio org-highlight-links)
6174 (org-restart-font-lock)))))
6176 (defun org-hide-wide-columns (limit)
6177 (let (s e)
6178 (setq s (text-property-any (point) (or limit (point-max))
6179 'org-cwidth t))
6180 (when s
6181 (setq e (next-single-property-change s 'org-cwidth))
6182 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6183 (goto-char e)
6184 t)))
6186 (defvar org-latex-and-related-regexp nil
6187 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6189 (defun org-compute-latex-and-related-regexp ()
6190 "Compute regular expression for LaTeX, entities and sub/superscript.
6191 Result depends on variable `org-highlight-latex-and-related'."
6192 (org-set-local
6193 'org-latex-and-related-regexp
6194 (let* ((re-sub
6195 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6196 ((eq org-use-sub-superscripts '{})
6197 (list org-match-substring-with-braces-regexp))
6198 (org-use-sub-superscripts (list org-match-substring-regexp))))
6199 (re-latex
6200 (when (memq 'latex org-highlight-latex-and-related)
6201 (let ((matchers (plist-get org-format-latex-options :matchers)))
6202 (delq nil
6203 (mapcar (lambda (x)
6204 (and (member (car x) matchers) (nth 1 x)))
6205 org-latex-regexps)))))
6206 (re-entities
6207 (when (memq 'entities org-highlight-latex-and-related)
6208 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6209 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6211 (defun org-do-latex-and-related (limit)
6212 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6213 LIMIT bounds the search for syntax to highlight. Stop at first
6214 highlighted object, if any. Return t if some highlighting was
6215 done, nil otherwise."
6216 (when (org-string-nw-p org-latex-and-related-regexp)
6217 (catch 'found
6218 (while (re-search-forward org-latex-and-related-regexp limit t)
6219 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6220 'face))
6221 '(org-code org-verbatim underline))
6222 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6223 '(?_ ?^))
6225 0)))
6226 (font-lock-prepend-text-property
6227 (+ offset (match-beginning 0)) (match-end 0)
6228 'face 'org-latex-and-related)
6229 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6230 '(font-lock-multiline t)))
6231 (throw 'found t)))
6232 nil)))
6234 (defun org-restart-font-lock ()
6235 "Restart `font-lock-mode', to force refontification."
6236 (when (and (boundp 'font-lock-mode) font-lock-mode)
6237 (font-lock-mode -1)
6238 (font-lock-mode 1)))
6240 (defun org-activate-tags (limit)
6241 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6242 (progn
6243 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6244 (add-text-properties (match-beginning 1) (match-end 1)
6245 (list 'mouse-face 'highlight
6246 'keymap org-mouse-map))
6247 (org-rear-nonsticky-at (match-end 1))
6248 t)))
6250 (defun org-outline-level ()
6251 "Compute the outline level of the heading at point.
6253 If this is called at a normal headline, the level is the number
6254 of stars. Use `org-reduced-level' to remove the effect of
6255 `org-odd-levels'. Unlike to `org-current-level', this function
6256 takes into consideration inlinetasks."
6257 (org-with-wide-buffer
6258 (end-of-line)
6259 (if (re-search-backward org-outline-regexp-bol nil t)
6260 (1- (- (match-end 0) (match-beginning 0)))
6261 0)))
6263 (defvar org-font-lock-keywords nil)
6265 (defsubst org-re-property (property &optional literal allow-null value)
6266 "Return a regexp matching a PROPERTY line.
6268 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6269 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6270 non-nil, match properties even without a value.
6272 Match group 3 is set to the value when it exists. If there is no
6273 value and ALLOW-NULL is non-nil, it is set to the empty string.
6275 With optional argument VALUE, match only property lines with
6276 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6277 unless LITERAL is non-nil."
6278 (concat
6279 "^\\(?4:[ \t]*\\)"
6280 (format "\\(?1::\\(?2:%s\\):\\)"
6281 (if literal property (regexp-quote property)))
6282 (cond (value
6283 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6284 (if literal value (regexp-quote value))))
6285 (allow-null
6286 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6288 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6290 (defconst org-property-re
6291 (org-re-property "\\S-+" 'literal t)
6292 "Regular expression matching a property line.
6293 There are four matching groups:
6294 1: :PROPKEY: including the leading and trailing colon,
6295 2: PROPKEY without the leading and trailing colon,
6296 3: PROPVAL without leading or trailing spaces,
6297 4: the indentation of the current line,
6298 5: trailing whitespace.")
6300 (defvar org-font-lock-hook nil
6301 "Functions to be called for special font lock stuff.")
6303 (defvar org-font-lock-set-keywords-hook nil
6304 "Functions that can manipulate `org-font-lock-extra-keywords'.
6305 This is called after `org-font-lock-extra-keywords' is defined, but before
6306 it is installed to be used by font lock. This can be useful if something
6307 needs to be inserted at a specific position in the font-lock sequence.")
6309 (defun org-font-lock-hook (limit)
6310 "Run `org-font-lock-hook' within LIMIT."
6311 (run-hook-with-args 'org-font-lock-hook limit))
6313 (defun org-set-font-lock-defaults ()
6314 "Set font lock defaults for the current buffer."
6315 (let* ((em org-fontify-emphasized-text)
6316 (lk org-highlight-links)
6317 (org-font-lock-extra-keywords
6318 (list
6319 ;; Call the hook
6320 '(org-font-lock-hook)
6321 ;; Headlines
6322 `(,(if org-fontify-whole-heading-line
6323 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6324 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6325 (1 (org-get-level-face 1))
6326 (2 (org-get-level-face 2))
6327 (3 (org-get-level-face 3)))
6328 ;; Table lines
6329 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6330 (1 'org-table t))
6331 ;; Table internals
6332 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6333 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6334 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6335 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6336 ;; Drawers
6337 '(org-fontify-drawers)
6338 ;; Properties
6339 (list org-property-re
6340 '(1 'org-special-keyword t)
6341 '(3 'org-property-value t))
6342 ;; Links
6343 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6344 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6345 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6346 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6347 (if (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6348 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6349 (if (memq 'footnote lk) '(org-activate-footnote-links))
6350 ;; Targets.
6351 (list org-any-target-regexp '(0 'org-target t))
6352 ;; Diary sexps.
6353 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6354 ;; Macro
6355 '(org-fontify-macros)
6356 '(org-hide-wide-columns (0 nil append))
6357 ;; TODO keyword
6358 (list (format org-heading-keyword-regexp-format
6359 org-todo-regexp)
6360 '(2 (org-get-todo-face 2) t))
6361 ;; DONE
6362 (if org-fontify-done-headline
6363 (list (format org-heading-keyword-regexp-format
6364 (concat
6365 "\\(?:"
6366 (mapconcat 'regexp-quote org-done-keywords "\\|")
6367 "\\)"))
6368 '(2 'org-headline-done t))
6369 nil)
6370 ;; Priorities
6371 '(org-font-lock-add-priority-faces)
6372 ;; Tags
6373 '(org-font-lock-add-tag-faces)
6374 ;; Tags groups
6375 (if (and org-group-tags org-tag-groups-alist)
6376 (list (concat org-outline-regexp-bol ".+\\(:"
6377 (regexp-opt (mapcar 'car org-tag-groups-alist))
6378 ":\\).*$")
6379 '(1 'org-tag-group prepend)))
6380 ;; Special keywords
6381 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6382 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6383 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6384 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6385 ;; Emphasis
6386 (if em
6387 (if (featurep 'xemacs)
6388 '(org-do-emphasis-faces (0 nil append))
6389 '(org-do-emphasis-faces)))
6390 ;; Checkboxes
6391 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6392 1 'org-checkbox prepend)
6393 (if (cdr (assq 'checkbox org-list-automatic-rules))
6394 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6395 (0 (org-get-checkbox-statistics-face) t)))
6396 ;; Description list items
6397 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6398 1 'org-list-dt prepend)
6399 ;; ARCHIVEd headings
6400 (list (concat
6401 org-outline-regexp-bol
6402 "\\(.*:" org-archive-tag ":.*\\)")
6403 '(1 'org-archived prepend))
6404 ;; Specials
6405 '(org-do-latex-and-related)
6406 '(org-fontify-entities)
6407 '(org-raise-scripts)
6408 ;; Code
6409 '(org-activate-code (1 'org-code t))
6410 ;; COMMENT
6411 (list (format
6412 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6413 org-todo-regexp
6414 org-comment-string)
6415 '(9 'org-special-keyword t))
6416 ;; Blocks and meta lines
6417 '(org-fontify-meta-lines-and-blocks))))
6418 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6419 (run-hooks 'org-font-lock-set-keywords-hook)
6420 ;; Now set the full font-lock-keywords
6421 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6422 (org-set-local 'font-lock-defaults
6423 '(org-font-lock-keywords t nil nil backward-paragraph))
6424 (kill-local-variable 'font-lock-keywords) nil))
6426 (defun org-toggle-pretty-entities ()
6427 "Toggle the composition display of entities as UTF8 characters."
6428 (interactive)
6429 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6430 (org-restart-font-lock)
6431 (if org-pretty-entities
6432 (message "Entities are now displayed as UTF8 characters")
6433 (save-restriction
6434 (widen)
6435 (org-decompose-region (point-min) (point-max))
6436 (message "Entities are now displayed as plain text"))))
6438 (defvar org-custom-properties-overlays nil
6439 "List of overlays used for custom properties.")
6440 (make-variable-buffer-local 'org-custom-properties-overlays)
6442 (defun org-toggle-custom-properties-visibility ()
6443 "Display or hide properties in `org-custom-properties'."
6444 (interactive)
6445 (if org-custom-properties-overlays
6446 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6447 (setq org-custom-properties-overlays nil))
6448 (when org-custom-properties
6449 (org-with-wide-buffer
6450 (goto-char (point-min))
6451 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6452 (while (re-search-forward regexp nil t)
6453 (let ((end (cdr (save-match-data (org-get-property-block)))))
6454 (when (and end (< (point) end))
6455 ;; Hide first custom property in current drawer.
6456 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6457 (overlay-put o 'invisible t)
6458 (overlay-put o 'org-custom-property t)
6459 (push o org-custom-properties-overlays))
6460 ;; Hide additional custom properties in the same drawer.
6461 (while (re-search-forward regexp end t)
6462 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6463 (overlay-put o 'invisible t)
6464 (overlay-put o 'org-custom-property t)
6465 (push o org-custom-properties-overlays)))))
6466 ;; Each entry is limited to a single property drawer.
6467 (outline-next-heading)))))))
6469 (defun org-fontify-entities (limit)
6470 "Find an entity to fontify."
6471 (let (ee)
6472 (when org-pretty-entities
6473 (catch 'match
6474 ;; "\_ "-family is left out on purpose. Only the first one,
6475 ;; i.e., "\_ ", could be fontified anyway, and it would be
6476 ;; confusing when adding a second white space character.
6477 (while (re-search-forward
6478 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6479 limit t)
6480 (if (and (not (org-at-comment-p))
6481 (setq ee (org-entity-get (match-string 1)))
6482 (= (length (nth 6 ee)) 1))
6483 (let*
6484 ((end (if (equal (match-string 2) "{}")
6485 (match-end 2)
6486 (match-end 1))))
6487 (add-text-properties
6488 (match-beginning 0) end
6489 (list 'font-lock-fontified t))
6490 (compose-region (match-beginning 0) end
6491 (nth 6 ee) nil)
6492 (backward-char 1)
6493 (throw 'match t))))
6494 nil))))
6496 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6497 "Fontify string S like in Org-mode."
6498 (with-temp-buffer
6499 (insert s)
6500 (let ((org-odd-levels-only odd-levels))
6501 (org-mode)
6502 (font-lock-ensure)
6503 (buffer-string))))
6505 (defvar org-m nil)
6506 (defvar org-l nil)
6507 (defvar org-f nil)
6508 (defun org-get-level-face (n)
6509 "Get the right face for match N in font-lock matching of headlines."
6510 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6511 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6512 (if org-cycle-level-faces
6513 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6514 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6515 (cond
6516 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6517 ((eq n 2) org-f)
6518 (t (if org-level-color-stars-only nil org-f))))
6520 (defun org-face-from-face-or-color (context inherit face-or-color)
6521 "Create a face list that inherits INHERIT, but sets the foreground color.
6522 When FACE-OR-COLOR is not a string, just return it."
6523 (if (stringp face-or-color)
6524 (list :inherit inherit
6525 (cdr (assoc context org-faces-easy-properties))
6526 face-or-color)
6527 face-or-color))
6529 (defun org-get-todo-face (kwd)
6530 "Get the right face for a TODO keyword KWD.
6531 If KWD is a number, get the corresponding match group."
6532 (if (numberp kwd) (setq kwd (match-string kwd)))
6533 (or (org-face-from-face-or-color
6534 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6535 (and (member kwd org-done-keywords) 'org-done)
6536 'org-todo))
6538 (defun org-get-priority-face (priority)
6539 "Get the right face for PRIORITY.
6540 PRIORITY is a character."
6541 (or (org-face-from-face-or-color
6542 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6543 'org-priority))
6545 (defun org-get-tag-face (tag)
6546 "Get the right face for TAG.
6547 If TAG is a number, get the corresponding match group."
6548 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6549 (or (org-face-from-face-or-color
6550 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6551 'org-tag)))
6553 (defun org-font-lock-add-priority-faces (limit)
6554 "Add the special priority faces."
6555 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6556 (add-text-properties
6557 (match-beginning 1) (match-end 1)
6558 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6559 'font-lock-fontified t))))
6561 (defun org-font-lock-add-tag-faces (limit)
6562 "Add the special tag faces."
6563 (when (and org-tag-faces org-tags-special-faces-re)
6564 (while (re-search-forward org-tags-special-faces-re limit t)
6565 (add-text-properties (match-beginning 1) (match-end 1)
6566 (list 'face (org-get-tag-face 1)
6567 'font-lock-fontified t))
6568 (backward-char 1))))
6570 (defun org-unfontify-region (beg end &optional maybe_loudly)
6571 "Remove fontification and activation overlays from links."
6572 (font-lock-default-unfontify-region beg end)
6573 (let* ((buffer-undo-list t)
6574 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6575 (inhibit-modification-hooks t)
6576 deactivate-mark buffer-file-name buffer-file-truename)
6577 (org-decompose-region beg end)
6578 (remove-text-properties beg end
6579 '(mouse-face t keymap t org-linked-text t
6580 invisible t intangible t
6581 org-emphasis t))
6582 (org-remove-font-lock-display-properties beg end)))
6584 (defconst org-script-display '(((raise -0.3) (height 0.7))
6585 ((raise 0.3) (height 0.7))
6586 ((raise -0.5))
6587 ((raise 0.5)))
6588 "Display properties for showing superscripts and subscripts.")
6590 (defun org-remove-font-lock-display-properties (beg end)
6591 "Remove specific display properties that have been added by font lock.
6592 The will remove the raise properties that are used to show superscripts
6593 and subscripts."
6594 (let (next prop)
6595 (while (< beg end)
6596 (setq next (next-single-property-change beg 'display nil end)
6597 prop (get-text-property beg 'display))
6598 (if (member prop org-script-display)
6599 (put-text-property beg next 'display nil))
6600 (setq beg next))))
6602 (defun org-raise-scripts (limit)
6603 "Add raise properties to sub/superscripts."
6604 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6605 (if (re-search-forward
6606 (if (eq org-use-sub-superscripts t)
6607 org-match-substring-regexp
6608 org-match-substring-with-braces-regexp)
6609 limit t)
6610 (let* ((pos (point)) table-p comment-p
6611 (mpos (match-beginning 3))
6612 (emph-p (get-text-property mpos 'org-emphasis))
6613 (link-p (get-text-property mpos 'mouse-face))
6614 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6615 (goto-char (point-at-bol))
6616 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6617 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6618 (goto-char pos)
6619 ;; Handle a_b^c
6620 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6621 (if (or comment-p emph-p link-p keyw-p)
6623 (put-text-property (match-beginning 3) (match-end 0)
6624 'display
6625 (if (equal (char-after (match-beginning 2)) ?^)
6626 (nth (if table-p 3 1) org-script-display)
6627 (nth (if table-p 2 0) org-script-display)))
6628 (add-text-properties (match-beginning 2) (match-end 2)
6629 (list 'invisible t
6630 'org-dwidth t 'org-dwidth-n 1))
6631 (if (and (eq (char-after (match-beginning 3)) ?{)
6632 (eq (char-before (match-end 3)) ?}))
6633 (progn
6634 (add-text-properties
6635 (match-beginning 3) (1+ (match-beginning 3))
6636 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6637 (add-text-properties
6638 (1- (match-end 3)) (match-end 3)
6639 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6640 t)))))
6642 ;;;; Visibility cycling, including org-goto and indirect buffer
6644 ;;; Cycling
6646 (defvar org-cycle-global-status nil)
6647 (make-variable-buffer-local 'org-cycle-global-status)
6648 (put 'org-cycle-global-status 'org-state t)
6649 (defvar org-cycle-subtree-status nil)
6650 (make-variable-buffer-local 'org-cycle-subtree-status)
6651 (put 'org-cycle-subtree-status 'org-state t)
6653 (defvar org-inlinetask-min-level)
6655 (defun org-unlogged-message (&rest args)
6656 "Display a message, but avoid logging it in the *Messages* buffer."
6657 (let ((message-log-max nil))
6658 (apply 'message args)))
6660 ;;;###autoload
6661 (defun org-cycle (&optional arg)
6662 "TAB-action and visibility cycling for Org-mode.
6664 This is the command invoked in Org-mode by the TAB key. Its main purpose
6665 is outline visibility cycling, but it also invokes other actions
6666 in special contexts.
6668 - When this function is called with a prefix argument, rotate the entire
6669 buffer through 3 states (global cycling)
6670 1. OVERVIEW: Show only top-level headlines.
6671 2. CONTENTS: Show all headlines of all levels, but no body text.
6672 3. SHOW ALL: Show everything.
6673 With a double \\[universal-argument] prefix argument, \
6674 switch to the startup visibility,
6675 determined by the variable `org-startup-folded', and by any VISIBILITY
6676 properties in the buffer.
6677 With a triple \\[universal-argument] prefix argument, \
6678 show the entire buffer, including any drawers.
6680 - When inside a table, re-align the table and move to the next field.
6682 - When point is at the beginning of a headline, rotate the subtree started
6683 by this line through 3 different states (local cycling)
6684 1. FOLDED: Only the main headline is shown.
6685 2. CHILDREN: The main headline and the direct children are shown.
6686 From this state, you can move to one of the children
6687 and zoom in further.
6688 3. SUBTREE: Show the entire subtree, including body text.
6689 If there is no subtree, switch directly from CHILDREN to FOLDED.
6691 - When point is at the beginning of an empty headline and the variable
6692 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6693 of the headline by demoting and promoting it to likely levels. This
6694 speeds up creation document structure by pressing TAB once or several
6695 times right after creating a new headline.
6697 - When there is a numeric prefix, go up to a heading with level ARG, do
6698 a `show-subtree' and return to the previous cursor position. If ARG
6699 is negative, go up that many levels.
6701 - When point is not at the beginning of a headline, execute the global
6702 binding for TAB, which is re-indenting the line. See the option
6703 `org-cycle-emulate-tab' for details.
6705 - Special case: if point is at the beginning of the buffer and there is
6706 no headline in line 1, this function will act as if called with prefix arg
6707 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6708 But only if also the variable `org-cycle-global-at-bob' is t."
6709 (interactive "P")
6710 (org-load-modules-maybe)
6711 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6712 (and org-cycle-level-after-item/entry-creation
6713 (or (org-cycle-level)
6714 (org-cycle-item-indentation))))
6715 (let* ((limit-level
6716 (or org-cycle-max-level
6717 (and (boundp 'org-inlinetask-min-level)
6718 org-inlinetask-min-level
6719 (1- org-inlinetask-min-level))))
6720 (nstars (and limit-level
6721 (if org-odd-levels-only
6722 (and limit-level (1- (* limit-level 2)))
6723 limit-level)))
6724 (org-outline-regexp
6725 (if (not (derived-mode-p 'org-mode))
6726 outline-regexp
6727 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6728 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6729 (not (looking-at org-outline-regexp))))
6730 (org-cycle-hook
6731 (if bob-special
6732 (delq 'org-optimize-window-after-visibility-change
6733 (copy-sequence org-cycle-hook))
6734 org-cycle-hook))
6735 (pos (point)))
6737 (if (or bob-special (equal arg '(4)))
6738 ;; special case: use global cycling
6739 (setq arg t))
6741 (cond
6743 ((equal arg '(16))
6744 (setq last-command 'dummy)
6745 (org-set-startup-visibility)
6746 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6748 ((equal arg '(64))
6749 (outline-show-all)
6750 (org-unlogged-message "Entire buffer visible, including drawers"))
6752 ;; Try cdlatex TAB completion
6753 ((org-try-cdlatex-tab))
6755 ;; Table: enter it or move to the next field.
6756 ((org-at-table-p 'any)
6757 (if (org-at-table.el-p)
6758 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6759 Use \\[org-edit-special] to edit table.el tables"))
6760 (if arg (org-table-edit-field t)
6761 (org-table-justify-field-maybe)
6762 (call-interactively 'org-table-next-field))))
6764 ((run-hook-with-args-until-success
6765 'org-tab-after-check-for-table-hook))
6767 ;; Global cycling: delegate to `org-cycle-internal-global'.
6768 ((eq arg t) (org-cycle-internal-global))
6770 ;; Drawers: delegate to `org-flag-drawer'.
6771 ((save-excursion
6772 (beginning-of-line 1)
6773 (looking-at org-drawer-regexp))
6774 (org-flag-drawer ; toggle block visibility
6775 (not (get-char-property (match-end 0) 'invisible))))
6777 ;; Show-subtree, ARG levels up from here.
6778 ((integerp arg)
6779 (save-excursion
6780 (org-back-to-heading)
6781 (outline-up-heading (if (< arg 0) (- arg)
6782 (- (funcall outline-level) arg)))
6783 (org-show-subtree)))
6785 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6786 ((and (featurep 'org-inlinetask)
6787 (org-inlinetask-at-task-p)
6788 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6789 (org-inlinetask-toggle-visibility))
6791 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6792 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6793 (save-excursion (move-beginning-of-line 1)
6794 (looking-at org-outline-regexp)))
6795 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6796 (org-cycle-internal-local))
6798 ;; From there: TAB emulation and template completion.
6799 (buffer-read-only (org-back-to-heading))
6801 ((run-hook-with-args-until-success
6802 'org-tab-after-check-for-cycling-hook))
6804 ((org-try-structure-completion))
6806 ((run-hook-with-args-until-success
6807 'org-tab-before-tab-emulation-hook))
6809 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6810 (or (not (bolp))
6811 (not (looking-at org-outline-regexp))))
6812 (call-interactively (global-key-binding "\t")))
6814 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6815 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6816 (or (and (eq org-cycle-emulate-tab 'white)
6817 (= (match-end 0) (point-at-eol)))
6818 (and (eq org-cycle-emulate-tab 'whitestart)
6819 (>= (match-end 0) pos))))
6821 (eq org-cycle-emulate-tab t))
6822 (call-interactively (global-key-binding "\t")))
6824 (t (save-excursion
6825 (org-back-to-heading)
6826 (org-cycle)))))))
6828 (defun org-cycle-internal-global ()
6829 "Do the global cycling action."
6830 ;; Hack to avoid display of messages for .org attachments in Gnus
6831 (let ((ga (string-match "\\*fontification" (buffer-name))))
6832 (cond
6833 ((and (eq last-command this-command)
6834 (eq org-cycle-global-status 'overview))
6835 ;; We just created the overview - now do table of contents
6836 ;; This can be slow in very large buffers, so indicate action
6837 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6838 (unless ga (org-unlogged-message "CONTENTS..."))
6839 (org-content)
6840 (unless ga (org-unlogged-message "CONTENTS...done"))
6841 (setq org-cycle-global-status 'contents)
6842 (run-hook-with-args 'org-cycle-hook 'contents))
6844 ((and (eq last-command this-command)
6845 (eq org-cycle-global-status 'contents))
6846 ;; We just showed the table of contents - now show everything
6847 (run-hook-with-args 'org-pre-cycle-hook 'all)
6848 (outline-show-all)
6849 (unless ga (org-unlogged-message "SHOW ALL"))
6850 (setq org-cycle-global-status 'all)
6851 (run-hook-with-args 'org-cycle-hook 'all))
6854 ;; Default action: go to overview
6855 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6856 (org-overview)
6857 (unless ga (org-unlogged-message "OVERVIEW"))
6858 (setq org-cycle-global-status 'overview)
6859 (run-hook-with-args 'org-cycle-hook 'overview)))))
6861 (defvar org-called-with-limited-levels nil
6862 "Non-nil when `org-with-limited-levels' is currently active.")
6864 (defun org-cycle-internal-local ()
6865 "Do the local cycling action."
6866 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6867 ;; First, determine end of headline (EOH), end of subtree or item
6868 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6869 (save-excursion
6870 (if (org-at-item-p)
6871 (progn
6872 (beginning-of-line)
6873 (setq struct (org-list-struct))
6874 (setq eoh (point-at-eol))
6875 (setq eos (org-list-get-item-end-before-blank (point) struct))
6876 (setq has-children (org-list-has-child-p (point) struct)))
6877 (org-back-to-heading)
6878 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6879 (setq eos (save-excursion (org-end-of-subtree t t)
6880 (when (bolp) (backward-char)) (point)))
6881 (setq has-children
6882 (or (save-excursion
6883 (let ((level (funcall outline-level)))
6884 (outline-next-heading)
6885 (and (org-at-heading-p t)
6886 (> (funcall outline-level) level))))
6887 (save-excursion
6888 (org-list-search-forward (org-item-beginning-re) eos t)))))
6889 ;; Determine end invisible part of buffer (EOL)
6890 (beginning-of-line 2)
6891 ;; XEmacs doesn't have `next-single-char-property-change'
6892 (if (featurep 'xemacs)
6893 (while (and (not (eobp)) ;; this is like `next-line'
6894 (get-char-property (1- (point)) 'invisible))
6895 (beginning-of-line 2))
6896 (while (and (not (eobp)) ;; this is like `next-line'
6897 (get-char-property (1- (point)) 'invisible))
6898 (goto-char (next-single-char-property-change (point) 'invisible))
6899 (and (eolp) (beginning-of-line 2))))
6900 (setq eol (point)))
6901 ;; Find out what to do next and set `this-command'
6902 (cond
6903 ((= eos eoh)
6904 ;; Nothing is hidden behind this heading
6905 (unless (org-before-first-heading-p)
6906 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6907 (org-unlogged-message "EMPTY ENTRY")
6908 (setq org-cycle-subtree-status nil)
6909 (save-excursion
6910 (goto-char eos)
6911 (outline-next-heading)
6912 (if (outline-invisible-p) (org-flag-heading nil))))
6913 ((and (or (>= eol eos)
6914 (not (string-match "\\S-" (buffer-substring eol eos))))
6915 (or has-children
6916 (not (setq children-skipped
6917 org-cycle-skip-children-state-if-no-children))))
6918 ;; Entire subtree is hidden in one line: children view
6919 (unless (org-before-first-heading-p)
6920 (run-hook-with-args 'org-pre-cycle-hook 'children))
6921 (if (org-at-item-p)
6922 (org-list-set-item-visibility (point-at-bol) struct 'children)
6923 (org-show-entry)
6924 (org-with-limited-levels (org-show-children))
6925 ;; FIXME: This slows down the func way too much.
6926 ;; How keep drawers hidden in subtree anyway?
6927 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6928 ;; (org-cycle-hide-drawers 'subtree))
6930 ;; Fold every list in subtree to top-level items.
6931 (when (eq org-cycle-include-plain-lists 'integrate)
6932 (save-excursion
6933 (org-back-to-heading)
6934 (while (org-list-search-forward (org-item-beginning-re) eos t)
6935 (beginning-of-line 1)
6936 (let* ((struct (org-list-struct))
6937 (prevs (org-list-prevs-alist struct))
6938 (end (org-list-get-bottom-point struct)))
6939 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6940 (org-list-get-all-items (point) struct prevs))
6941 (goto-char (if (< end eos) end eos)))))))
6942 (org-unlogged-message "CHILDREN")
6943 (save-excursion
6944 (goto-char eos)
6945 (outline-next-heading)
6946 (if (outline-invisible-p) (org-flag-heading nil)))
6947 (setq org-cycle-subtree-status 'children)
6948 (unless (org-before-first-heading-p)
6949 (run-hook-with-args 'org-cycle-hook 'children)))
6950 ((or children-skipped
6951 (and (eq last-command this-command)
6952 (eq org-cycle-subtree-status 'children)))
6953 ;; We just showed the children, or no children are there,
6954 ;; now show everything.
6955 (unless (org-before-first-heading-p)
6956 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6957 (outline-flag-region eoh eos nil)
6958 (org-unlogged-message
6959 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6960 (setq org-cycle-subtree-status 'subtree)
6961 (unless (org-before-first-heading-p)
6962 (run-hook-with-args 'org-cycle-hook 'subtree)))
6964 ;; Default action: hide the subtree.
6965 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6966 (outline-flag-region eoh eos t)
6967 (org-unlogged-message "FOLDED")
6968 (setq org-cycle-subtree-status 'folded)
6969 (unless (org-before-first-heading-p)
6970 (run-hook-with-args 'org-cycle-hook 'folded))))))
6972 ;;;###autoload
6973 (defun org-global-cycle (&optional arg)
6974 "Cycle the global visibility. For details see `org-cycle'.
6975 With \\[universal-argument] prefix arg, switch to startup visibility.
6976 With a numeric prefix, show all headlines up to that level."
6977 (interactive "P")
6978 (let ((org-cycle-include-plain-lists
6979 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6980 (cond
6981 ((integerp arg)
6982 (outline-show-all)
6983 (outline-hide-sublevels arg)
6984 (setq org-cycle-global-status 'contents))
6985 ((equal arg '(4))
6986 (org-set-startup-visibility)
6987 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6989 (org-cycle '(4))))))
6991 (defun org-set-startup-visibility ()
6992 "Set the visibility required by startup options and properties."
6993 (cond
6994 ((eq org-startup-folded t)
6995 (org-overview))
6996 ((eq org-startup-folded 'content)
6997 (org-content))
6998 ((or (eq org-startup-folded 'showeverything)
6999 (eq org-startup-folded nil))
7000 (outline-show-all)))
7001 (unless (eq org-startup-folded 'showeverything)
7002 (if org-hide-block-startup (org-hide-block-all))
7003 (org-set-visibility-according-to-property 'no-cleanup)
7004 (org-cycle-hide-archived-subtrees 'all)
7005 (org-cycle-hide-drawers 'all)
7006 (org-cycle-show-empty-lines t)))
7008 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7009 "Switch subtree visibilities according to :VISIBILITY: property."
7010 (interactive)
7011 (let (org-show-entry-below)
7012 (org-with-wide-buffer
7013 (goto-char (point-min))
7014 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7015 (if (not (org-at-property-p)) (outline-next-heading)
7016 (let ((state (match-string 3)))
7017 (save-excursion
7018 (org-back-to-heading t)
7019 (outline-hide-subtree)
7020 (org-reveal)
7021 (cond
7022 ((equal state "folded")
7023 (outline-hide-subtree))
7024 ((equal state "children")
7025 (org-show-hidden-entry)
7026 (org-show-children))
7027 ((equal state "content")
7028 (save-excursion
7029 (save-restriction
7030 (org-narrow-to-subtree)
7031 (org-content))))
7032 ((member state '("all" "showall"))
7033 (outline-show-subtree)))))))
7034 (unless no-cleanup
7035 (org-cycle-hide-archived-subtrees 'all)
7036 (org-cycle-hide-drawers 'all)
7037 (org-cycle-show-empty-lines 'all)))))
7039 ;; This function uses outline-regexp instead of the more fundamental
7040 ;; org-outline-regexp so that org-cycle-global works outside of Org
7041 ;; buffers, where outline-regexp is needed.
7042 (defun org-overview ()
7043 "Switch to overview mode, showing only top-level headlines.
7044 This shows all headlines with a level equal or greater than the level
7045 of the first headline in the buffer. This is important, because if the
7046 first headline is not level one, then (hide-sublevels 1) gives confusing
7047 results."
7048 (interactive)
7049 (save-excursion
7050 (let ((level
7051 (save-excursion
7052 (goto-char (point-min))
7053 (if (re-search-forward (concat "^" outline-regexp) nil t)
7054 (progn
7055 (goto-char (match-beginning 0))
7056 (funcall outline-level))))))
7057 (and level (outline-hide-sublevels level)))))
7059 (defun org-content (&optional arg)
7060 "Show all headlines in the buffer, like a table of contents.
7061 With numerical argument N, show content up to level N."
7062 (interactive "P")
7063 (org-overview)
7064 (save-excursion
7065 ;; Visit all headings and show their offspring
7066 (and (integerp arg) (org-overview))
7067 (goto-char (point-max))
7068 (catch 'exit
7069 (while (and (progn (condition-case nil
7070 (outline-previous-visible-heading 1)
7071 (error (goto-char (point-min))))
7073 (looking-at org-outline-regexp))
7074 (if (integerp arg)
7075 (org-show-children (1- arg))
7076 (outline-show-branches))
7077 (if (bobp) (throw 'exit nil))))))
7079 (defun org-optimize-window-after-visibility-change (state)
7080 "Adjust the window after a change in outline visibility.
7081 This function is the default value of the hook `org-cycle-hook'."
7082 (when (get-buffer-window (current-buffer))
7083 (cond
7084 ((eq state 'content) nil)
7085 ((eq state 'all) nil)
7086 ((eq state 'folded) nil)
7087 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7088 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7090 (defun org-remove-empty-overlays-at (pos)
7091 "Remove outline overlays that do not contain non-white stuff."
7092 (mapc
7093 (lambda (o)
7094 (and (eq 'outline (overlay-get o 'invisible))
7095 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7096 (overlay-end o))))
7097 (delete-overlay o)))
7098 (overlays-at pos)))
7100 (defun org-clean-visibility-after-subtree-move ()
7101 "Fix visibility issues after moving a subtree."
7102 ;; First, find a reasonable region to look at:
7103 ;; Start two siblings above, end three below
7104 (let* ((beg (save-excursion
7105 (and (org-get-last-sibling)
7106 (org-get-last-sibling))
7107 (point)))
7108 (end (save-excursion
7109 (and (org-get-next-sibling)
7110 (org-get-next-sibling)
7111 (org-get-next-sibling))
7112 (if (org-at-heading-p)
7113 (point-at-eol)
7114 (point))))
7115 (level (looking-at "\\*+"))
7116 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7117 (save-excursion
7118 (save-restriction
7119 (narrow-to-region beg end)
7120 (when re
7121 ;; Properly fold already folded siblings
7122 (goto-char (point-min))
7123 (while (re-search-forward re nil t)
7124 (if (and (not (outline-invisible-p))
7125 (save-excursion
7126 (goto-char (point-at-eol)) (outline-invisible-p)))
7127 (outline-hide-entry))))
7128 (org-cycle-show-empty-lines 'overview)
7129 (org-cycle-hide-drawers 'overview)))))
7131 (defun org-cycle-show-empty-lines (state)
7132 "Show empty lines above all visible headlines.
7133 The region to be covered depends on STATE when called through
7134 `org-cycle-hook'. Lisp program can use t for STATE to get the
7135 entire buffer covered. Note that an empty line is only shown if there
7136 are at least `org-cycle-separator-lines' empty lines before the headline."
7137 (when (/= org-cycle-separator-lines 0)
7138 (save-excursion
7139 (let* ((n (abs org-cycle-separator-lines))
7140 (re (cond
7141 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7142 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7143 (t (let ((ns (number-to-string (- n 2))))
7144 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7145 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7146 beg end)
7147 (cond
7148 ((memq state '(overview contents t))
7149 (setq beg (point-min) end (point-max)))
7150 ((memq state '(children folded))
7151 (setq beg (point)
7152 end (progn (org-end-of-subtree t t)
7153 (line-beginning-position 2)))))
7154 (when beg
7155 (goto-char beg)
7156 (while (re-search-forward re end t)
7157 (unless (get-char-property (match-end 1) 'invisible)
7158 (let ((e (match-end 1))
7159 (b (if (>= org-cycle-separator-lines 0)
7160 (match-beginning 1)
7161 (save-excursion
7162 (goto-char (match-beginning 0))
7163 (skip-chars-backward " \t\n")
7164 (line-end-position)))))
7165 (outline-flag-region b e nil))))))))
7166 ;; Never hide empty lines at the end of the file.
7167 (save-excursion
7168 (goto-char (point-max))
7169 (outline-previous-heading)
7170 (outline-end-of-heading)
7171 (if (and (looking-at "[ \t\n]+")
7172 (= (match-end 0) (point-max)))
7173 (outline-flag-region (point) (match-end 0) nil))))
7175 (defun org-show-empty-lines-in-parent ()
7176 "Move to the parent and re-show empty lines before visible headlines."
7177 (save-excursion
7178 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7179 (org-cycle-show-empty-lines context))))
7181 (defun org-files-list ()
7182 "Return `org-agenda-files' list, plus all open org-mode files.
7183 This is useful for operations that need to scan all of a user's
7184 open and agenda-wise Org files."
7185 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7186 (dolist (buf (buffer-list))
7187 (with-current-buffer buf
7188 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7189 (let ((file (expand-file-name (buffer-file-name))))
7190 (unless (member file files)
7191 (push file files))))))
7192 files))
7194 (defsubst org-entry-beginning-position ()
7195 "Return the beginning position of the current entry."
7196 (save-excursion (outline-back-to-heading t) (point)))
7198 (defsubst org-entry-end-position ()
7199 "Return the end position of the current entry."
7200 (save-excursion (outline-next-heading) (point)))
7202 (defun org-cycle-hide-drawers (state &optional exceptions)
7203 "Re-hide all drawers after a visibility state change.
7204 When non-nil, optional argument EXCEPTIONS is a list of strings
7205 specifying which drawers should not be hidden."
7206 (when (and (derived-mode-p 'org-mode)
7207 (not (memq state '(overview folded contents))))
7208 (save-excursion
7209 (let* ((globalp (memq state '(contents all)))
7210 (beg (if globalp (point-min) (point)))
7211 (end (if globalp (point-max)
7212 (if (eq state 'children)
7213 (save-excursion (outline-next-heading) (point))
7214 (org-end-of-subtree t)))))
7215 (goto-char beg)
7216 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7217 (unless (member-ignore-case (match-string 1) exceptions)
7218 (let ((drawer (org-element-at-point)))
7219 (when (memq (org-element-type drawer) '(drawer property-drawer))
7220 (org-flag-drawer t drawer)
7221 ;; Make sure to skip drawer entirely or we might flag
7222 ;; it another time when matching its ending line with
7223 ;; `org-drawer-regexp'.
7224 (goto-char (org-element-property :end drawer))))))))))
7226 (defun org-flag-drawer (flag &optional element)
7227 "When FLAG is non-nil, hide the drawer we are at.
7228 Otherwise make it visible. When optional argument ELEMENT is
7229 a parsed drawer, as returned by `org-element-at-point', hide or
7230 show that drawer instead."
7231 (when (save-excursion
7232 (beginning-of-line)
7233 (org-looking-at-p org-drawer-regexp))
7234 (let ((drawer (or element (org-element-at-point))))
7235 (when (memq (org-element-type drawer) '(drawer property-drawer))
7236 (let ((post (org-element-property :post-affiliated drawer)))
7237 (save-excursion
7238 (outline-flag-region
7239 (progn (goto-char post) (line-end-position))
7240 (progn (goto-char (org-element-property :end drawer))
7241 (skip-chars-backward " \r\t\n")
7242 (line-end-position))
7243 flag))
7244 ;; When the drawer is hidden away, make sure point lies in
7245 ;; a visible part of the buffer.
7246 (when (and flag (> (line-beginning-position) post))
7247 (goto-char post)))))))
7249 (defun org-subtree-end-visible-p ()
7250 "Is the end of the current subtree visible?"
7251 (pos-visible-in-window-p
7252 (save-excursion (org-end-of-subtree t) (point))))
7254 (defun org-first-headline-recenter ()
7255 "Move cursor to the first headline and recenter the headline."
7256 (goto-char (point-min))
7257 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7258 (set-window-start (selected-window) (point-at-bol))))
7260 ;;; Saving and restoring visibility
7262 (defun org-outline-overlay-data (&optional use-markers)
7263 "Return a list of the locations of all outline overlays.
7264 These are overlays with the `invisible' property value `outline'.
7265 The return value is a list of cons cells, with start and stop
7266 positions for each overlay.
7267 If USE-MARKERS is set, return the positions as markers."
7268 (let (beg end)
7269 (save-excursion
7270 (save-restriction
7271 (widen)
7272 (delq nil
7273 (mapcar (lambda (o)
7274 (when (eq (overlay-get o 'invisible) 'outline)
7275 (setq beg (overlay-start o)
7276 end (overlay-end o))
7277 (and beg end (> end beg)
7278 (if use-markers
7279 (cons (copy-marker beg)
7280 (copy-marker end t))
7281 (cons beg end)))))
7282 (overlays-in (point-min) (point-max))))))))
7284 (defun org-set-outline-overlay-data (data)
7285 "Create visibility overlays for all positions in DATA.
7286 DATA should have been made by `org-outline-overlay-data'."
7287 (let (o)
7288 (save-excursion
7289 (save-restriction
7290 (widen)
7291 (outline-show-all)
7292 (mapc (lambda (c)
7293 (outline-flag-region (car c) (cdr c) t))
7294 data)))))
7296 ;;; Folding of blocks
7298 (defvar org-hide-block-overlays nil
7299 "Overlays hiding blocks.")
7300 (make-variable-buffer-local 'org-hide-block-overlays)
7302 (defun org-block-map (function &optional start end)
7303 "Call FUNCTION at the head of all source blocks in the current buffer.
7304 Optional arguments START and END can be used to limit the range."
7305 (let ((start (or start (point-min)))
7306 (end (or end (point-max))))
7307 (save-excursion
7308 (goto-char start)
7309 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7310 (save-excursion
7311 (save-match-data
7312 (goto-char (match-beginning 0))
7313 (funcall function)))))))
7315 (defun org-hide-block-toggle-all ()
7316 "Toggle the visibility of all blocks in the current buffer."
7317 (org-block-map 'org-hide-block-toggle))
7319 (defun org-hide-block-all ()
7320 "Fold all blocks in the current buffer."
7321 (interactive)
7322 (org-show-block-all)
7323 (org-block-map 'org-hide-block-toggle-maybe))
7325 (defun org-show-block-all ()
7326 "Unfold all blocks in the current buffer."
7327 (interactive)
7328 (mapc 'delete-overlay org-hide-block-overlays)
7329 (setq org-hide-block-overlays nil))
7331 (defun org-hide-block-toggle-maybe ()
7332 "Toggle visibility of block at point.
7333 Unlike to `org-hide-block-toggle', this function does not throw
7334 an error. Return a non-nil value when toggling is successful."
7335 (interactive)
7336 (ignore-errors (org-hide-block-toggle)))
7338 (defun org-hide-block-toggle (&optional force)
7339 "Toggle the visibility of the current block.
7340 When optional argument FORCE is `off', make block visible. If it
7341 is non-nil, hide it unconditionally. Throw an error when not at
7342 a block. Return a non-nil value when toggling is successful."
7343 (interactive)
7344 (let ((element (org-element-at-point)))
7345 (unless (memq (org-element-type element)
7346 '(center-block comment-block dynamic-block example-block
7347 export-block quote-block special-block
7348 src-block verse-block))
7349 (user-error "Not at a block"))
7350 (let* ((start (save-excursion
7351 (goto-char (org-element-property :post-affiliated element))
7352 (line-end-position)))
7353 (end (save-excursion
7354 (goto-char (org-element-property :end element))
7355 (skip-chars-backward " \r\t\n")
7356 (line-end-position)))
7357 (overlays (overlays-at start)))
7358 (cond
7359 ;; Do nothing when not before or at the block opening line or
7360 ;; at the block closing line.
7361 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7362 ((and (not (eq force 'off))
7363 (not (memq t (mapcar
7364 (lambda (o)
7365 (eq (overlay-get o 'invisible) 'org-hide-block))
7366 overlays))))
7367 (let ((ov (make-overlay start end)))
7368 (overlay-put ov 'invisible 'org-hide-block)
7369 ;; Make the block accessible to `isearch'.
7370 (overlay-put
7371 ov 'isearch-open-invisible
7372 (lambda (ov)
7373 (when (memq ov org-hide-block-overlays)
7374 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7375 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7376 (delete-overlay ov))))
7377 (push ov org-hide-block-overlays)
7378 ;; When the block is hidden away, make sure point is left in
7379 ;; a visible part of the buffer.
7380 (when (> (line-beginning-position) start)
7381 (goto-char start)
7382 (beginning-of-line))
7383 ;; Signal successful toggling.
7385 ((or (not force) (eq force 'off))
7386 (dolist (ov overlays t)
7387 (when (memq ov org-hide-block-overlays)
7388 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7389 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7390 (delete-overlay ov))))))))
7392 ;; org-tab-after-check-for-cycling-hook
7393 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7394 ;; Remove overlays when changing major mode
7395 (add-hook 'org-mode-hook
7396 (lambda () (org-add-hook 'change-major-mode-hook
7397 'org-show-block-all 'append 'local)))
7399 ;;; Org-goto
7401 (defvar org-goto-window-configuration nil)
7402 (defvar org-goto-marker nil)
7403 (defvar org-goto-map)
7404 (defun org-goto-map ()
7405 "Set the keymap `org-goto'."
7406 (setq org-goto-map
7407 (let ((map (make-sparse-keymap)))
7408 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7409 mouse-drag-region universal-argument org-occur)))
7410 (dolist (cmd cmds)
7411 (substitute-key-definition cmd cmd map global-map)))
7412 (suppress-keymap map)
7413 (org-defkey map "\C-m" 'org-goto-ret)
7414 (org-defkey map [(return)] 'org-goto-ret)
7415 (org-defkey map [(left)] 'org-goto-left)
7416 (org-defkey map [(right)] 'org-goto-right)
7417 (org-defkey map [(control ?g)] 'org-goto-quit)
7418 (org-defkey map "\C-i" 'org-cycle)
7419 (org-defkey map [(tab)] 'org-cycle)
7420 (org-defkey map [(down)] 'outline-next-visible-heading)
7421 (org-defkey map [(up)] 'outline-previous-visible-heading)
7422 (if org-goto-auto-isearch
7423 (if (fboundp 'define-key-after)
7424 (define-key-after map [t] 'org-goto-local-auto-isearch)
7425 nil)
7426 (org-defkey map "q" 'org-goto-quit)
7427 (org-defkey map "n" 'outline-next-visible-heading)
7428 (org-defkey map "p" 'outline-previous-visible-heading)
7429 (org-defkey map "f" 'outline-forward-same-level)
7430 (org-defkey map "b" 'outline-backward-same-level)
7431 (org-defkey map "u" 'outline-up-heading))
7432 (org-defkey map "/" 'org-occur)
7433 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7434 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7435 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7436 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7437 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7438 map)))
7440 (defconst org-goto-help
7441 "Browse buffer copy, to find location or copy text.%s
7442 RET=jump to location C-g=quit and return to previous location
7443 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7445 (defvar org-goto-start-pos) ; dynamically scoped parameter
7447 (defun org-goto (&optional alternative-interface)
7448 "Look up a different location in the current file, keeping current visibility.
7450 When you want look-up or go to a different location in a
7451 document, the fastest way is often to fold the entire buffer and
7452 then dive into the tree. This method has the disadvantage, that
7453 the previous location will be folded, which may not be what you
7454 want.
7456 This command works around this by showing a copy of the current
7457 buffer in an indirect buffer, in overview mode. You can dive
7458 into the tree in that copy, use org-occur and incremental search
7459 to find a location. When pressing RET or `Q', the command
7460 returns to the original buffer in which the visibility is still
7461 unchanged. After RET it will also jump to the location selected
7462 in the indirect buffer and expose the headline hierarchy above.
7464 With a prefix argument, use the alternative interface: e.g. if
7465 `org-goto-interface' is 'outline use 'outline-path-completion."
7466 (interactive "P")
7467 (org-goto-map)
7468 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7469 (org-refile-use-outline-path t)
7470 (org-refile-target-verify-function nil)
7471 (interface
7472 (if (not alternative-interface)
7473 org-goto-interface
7474 (if (eq org-goto-interface 'outline)
7475 'outline-path-completion
7476 'outline)))
7477 (org-goto-start-pos (point))
7478 (selected-point
7479 (if (eq interface 'outline)
7480 (car (org-get-location (current-buffer) org-goto-help))
7481 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7482 (org-refile-check-position pa)
7483 (nth 3 pa)))))
7484 (if selected-point
7485 (progn
7486 (org-mark-ring-push org-goto-start-pos)
7487 (goto-char selected-point)
7488 (if (or (outline-invisible-p) (org-invisible-p2))
7489 (org-show-context 'org-goto)))
7490 (message "Quit"))))
7492 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7493 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7494 (defvar org-goto-local-auto-isearch-map) ; defined below
7496 (defun org-get-location (buf help)
7497 "Let the user select a location in the Org-mode buffer BUF.
7498 This function uses a recursive edit. It returns the selected position
7499 or nil."
7500 (org-no-popups
7501 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7502 (isearch-hide-immediately nil)
7503 (isearch-search-fun-function
7504 (lambda () 'org-goto-local-search-headings))
7505 (org-goto-selected-point org-goto-exit-command))
7506 (save-excursion
7507 (save-window-excursion
7508 (delete-other-windows)
7509 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7510 (org-pop-to-buffer-same-window
7511 (condition-case nil
7512 (make-indirect-buffer (current-buffer) "*org-goto*")
7513 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7514 (with-output-to-temp-buffer "*Org Help*"
7515 (princ (format help (if org-goto-auto-isearch
7516 " Just type for auto-isearch."
7517 " n/p/f/b/u to navigate, q to quit."))))
7518 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7519 (setq buffer-read-only nil)
7520 (let ((org-startup-truncated t)
7521 (org-startup-folded nil)
7522 (org-startup-align-all-tables nil))
7523 (org-mode)
7524 (org-overview))
7525 (setq buffer-read-only t)
7526 (if (and (boundp 'org-goto-start-pos)
7527 (integer-or-marker-p org-goto-start-pos))
7528 (progn (goto-char org-goto-start-pos)
7529 (when (outline-invisible-p)
7530 (org-show-set-visibility 'lineage)))
7531 (goto-char (point-min)))
7532 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7533 (message "Select location and press RET")
7534 (use-local-map org-goto-map)
7535 (recursive-edit)))
7536 (kill-buffer "*org-goto*")
7537 (cons org-goto-selected-point org-goto-exit-command))))
7539 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7540 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7541 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7542 (if (fboundp 'isearch-other-control-char)
7543 (progn
7544 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7545 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7546 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7547 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7548 (define-key org-goto-local-auto-isearch-map [return] nil))
7550 (defun org-goto-local-search-headings (string bound noerror)
7551 "Search and make sure that any matches are in headlines."
7552 (catch 'return
7553 (while (if isearch-forward
7554 (search-forward string bound noerror)
7555 (search-backward string bound noerror))
7556 (when (save-match-data
7557 (and (save-excursion
7558 (beginning-of-line)
7559 (looking-at org-complex-heading-regexp))
7560 (or (not (match-beginning 5))
7561 (< (point) (match-beginning 5)))))
7562 (throw 'return (point))))))
7564 (defun org-goto-local-auto-isearch ()
7565 "Start isearch."
7566 (interactive)
7567 (goto-char (point-min))
7568 (let ((keys (this-command-keys)))
7569 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7570 (isearch-mode t)
7571 (isearch-process-search-char (string-to-char keys)))))
7573 (defun org-goto-ret (&optional arg)
7574 "Finish `org-goto' by going to the new location."
7575 (interactive "P")
7576 (setq org-goto-selected-point (point)
7577 org-goto-exit-command 'return)
7578 (throw 'exit nil))
7580 (defun org-goto-left ()
7581 "Finish `org-goto' by going to the new location."
7582 (interactive)
7583 (if (org-at-heading-p)
7584 (progn
7585 (beginning-of-line 1)
7586 (setq org-goto-selected-point (point)
7587 org-goto-exit-command 'left)
7588 (throw 'exit nil))
7589 (user-error "Not on a heading")))
7591 (defun org-goto-right ()
7592 "Finish `org-goto' by going to the new location."
7593 (interactive)
7594 (if (org-at-heading-p)
7595 (progn
7596 (setq org-goto-selected-point (point)
7597 org-goto-exit-command 'right)
7598 (throw 'exit nil))
7599 (user-error "Not on a heading")))
7601 (defun org-goto-quit ()
7602 "Finish `org-goto' without cursor motion."
7603 (interactive)
7604 (setq org-goto-selected-point nil)
7605 (setq org-goto-exit-command 'quit)
7606 (throw 'exit nil))
7608 ;;; Indirect buffer display of subtrees
7610 (defvar org-indirect-dedicated-frame nil
7611 "This is the frame being used for indirect tree display.")
7612 (defvar org-last-indirect-buffer nil)
7614 (defun org-tree-to-indirect-buffer (&optional arg)
7615 "Create indirect buffer and narrow it to current subtree.
7616 With a numerical prefix ARG, go up to this level and then take that tree.
7617 If ARG is negative, go up that many levels.
7619 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7620 indirect buffer previously made with this command, to avoid proliferation of
7621 indirect buffers. However, when you call the command with a \
7622 \\[universal-argument] prefix, or
7623 when `org-indirect-buffer-display' is `new-frame', the last buffer
7624 is kept so that you can work with several indirect buffers at the same time.
7625 If `org-indirect-buffer-display' is `dedicated-frame', the \
7626 \\[universal-argument] prefix also
7627 requests that a new frame be made for the new buffer, so that the dedicated
7628 frame is not changed."
7629 (interactive "P")
7630 (let ((cbuf (current-buffer))
7631 (cwin (selected-window))
7632 (pos (point))
7633 beg end level heading ibuf)
7634 (save-excursion
7635 (org-back-to-heading t)
7636 (when (numberp arg)
7637 (setq level (org-outline-level))
7638 (if (< arg 0) (setq arg (+ level arg)))
7639 (while (> (setq level (org-outline-level)) arg)
7640 (org-up-heading-safe)))
7641 (setq beg (point)
7642 heading (org-get-heading))
7643 (org-end-of-subtree t t)
7644 (if (org-at-heading-p) (backward-char 1))
7645 (setq end (point)))
7646 (if (and (buffer-live-p org-last-indirect-buffer)
7647 (not (eq org-indirect-buffer-display 'new-frame))
7648 (not arg))
7649 (kill-buffer org-last-indirect-buffer))
7650 (setq ibuf (org-get-indirect-buffer cbuf heading)
7651 org-last-indirect-buffer ibuf)
7652 (cond
7653 ((or (eq org-indirect-buffer-display 'new-frame)
7654 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7655 (select-frame (make-frame))
7656 (delete-other-windows)
7657 (org-pop-to-buffer-same-window ibuf)
7658 (org-set-frame-title heading))
7659 ((eq org-indirect-buffer-display 'dedicated-frame)
7660 (raise-frame
7661 (select-frame (or (and org-indirect-dedicated-frame
7662 (frame-live-p org-indirect-dedicated-frame)
7663 org-indirect-dedicated-frame)
7664 (setq org-indirect-dedicated-frame (make-frame)))))
7665 (delete-other-windows)
7666 (org-pop-to-buffer-same-window ibuf)
7667 (org-set-frame-title (concat "Indirect: " heading)))
7668 ((eq org-indirect-buffer-display 'current-window)
7669 (org-pop-to-buffer-same-window ibuf))
7670 ((eq org-indirect-buffer-display 'other-window)
7671 (pop-to-buffer ibuf))
7672 (t (error "Invalid value")))
7673 (if (featurep 'xemacs)
7674 (save-excursion (org-mode) (turn-on-font-lock)))
7675 (narrow-to-region beg end)
7676 (outline-show-all)
7677 (goto-char pos)
7678 (run-hook-with-args 'org-cycle-hook 'all)
7679 (and (window-live-p cwin) (select-window cwin))))
7681 (defun org-get-indirect-buffer (&optional buffer heading)
7682 (setq buffer (or buffer (current-buffer)))
7683 (let ((n 1) (base (buffer-name buffer)) bname)
7684 (while (buffer-live-p
7685 (get-buffer
7686 (setq bname
7687 (concat base "-"
7688 (if heading (concat heading "-" (number-to-string n))
7689 (number-to-string n))))))
7690 (setq n (1+ n)))
7691 (condition-case nil
7692 (make-indirect-buffer buffer bname 'clone)
7693 (error (make-indirect-buffer buffer bname)))))
7695 (defun org-set-frame-title (title)
7696 "Set the title of the current frame to the string TITLE."
7697 ;; FIXME: how to name a single frame in XEmacs???
7698 (unless (featurep 'xemacs)
7699 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7701 ;;;; Structure editing
7703 ;;; Inserting headlines
7705 (defun org-previous-line-empty-p (&optional next)
7706 "Is the previous line a blank line?
7707 When NEXT is non-nil, check the next line instead."
7708 (save-excursion
7709 (and (not (bobp))
7710 (or (beginning-of-line (if next 2 0)) t)
7711 (save-match-data
7712 (looking-at "[ \t]*$")))))
7714 (defun org-insert-heading (&optional arg invisible-ok top-level)
7715 "Insert a new heading or an item with the same depth at point.
7717 If point is at the beginning of a heading or a list item, insert
7718 a new heading or a new item above the current one. If point is
7719 at the beginning of a normal line, turn the line into a heading.
7721 If point is in the middle of a headline or a list item, split the
7722 headline or the item and create a new headline/item with the text
7723 in the current line after point \(see `org-M-RET-may-split-line'
7724 on how to modify this behavior).
7726 With one universal prefix argument, set the user option
7727 `org-insert-heading-respect-content' to t for the duration of
7728 the command. This modifies the behavior described above in this
7729 ways: on list items and at the beginning of normal lines, force
7730 the insertion of a heading after the current subtree.
7732 With two universal prefix arguments, insert the heading at the
7733 end of the grandparent subtree. For example, if point is within
7734 a 2nd-level heading, then it will insert a 2nd-level heading at
7735 the end of the 1st-level parent heading.
7737 If point is at the beginning of a headline, insert a sibling
7738 before the current headline. If point is not at the beginning,
7739 split the line and create a new headline with the text in the
7740 current line after point \(see `org-M-RET-may-split-line' on how
7741 to modify this behavior).
7743 If point is at the beginning of a normal line, turn this line
7744 into a heading.
7746 When INVISIBLE-OK is set, stop at invisible headlines when going
7747 back. This is important for non-interactive uses of the
7748 command.
7750 When optional argument TOP-LEVEL is non-nil, insert a level 1
7751 heading, unconditionally."
7752 (interactive "P")
7753 (if (org-called-interactively-p 'any) (org-reveal))
7754 (let ((itemp (and (not top-level) (org-in-item-p)))
7755 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7756 (respect-content (or org-insert-heading-respect-content
7757 (equal arg '(4))))
7758 (initial-content ""))
7760 (cond
7762 ((or (= (buffer-size) 0)
7763 (and (not (save-excursion
7764 (and (ignore-errors (org-back-to-heading invisible-ok))
7765 (org-at-heading-p))))
7766 (or arg (not itemp))))
7767 ;; At beginning of buffer or so high up that only a heading
7768 ;; makes sense.
7769 (cond ((and (bolp) (not respect-content)) (insert "* "))
7770 ((not respect-content)
7771 (unless may-split (end-of-line))
7772 (insert "\n* "))
7773 ((re-search-forward org-outline-regexp-bol nil t)
7774 (beginning-of-line)
7775 (insert "* \n")
7776 (backward-char))
7777 (t (goto-char (point-max))
7778 (insert "\n* ")))
7779 (run-hooks 'org-insert-heading-hook))
7781 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7784 ;; Maybe move at the end of the subtree
7785 (when (equal arg '(16))
7786 (org-up-heading-safe)
7787 (org-end-of-subtree t))
7788 ;; Insert a heading
7789 (save-restriction
7790 (widen)
7791 (let* ((level nil)
7792 (on-heading (org-at-heading-p))
7793 (empty-line-p (if on-heading
7794 (org-previous-line-empty-p)
7795 ;; We will decide later
7796 nil))
7797 ;; Get a level string to fall back on.
7798 (fix-level
7799 (if (org-before-first-heading-p) "*"
7800 (save-excursion
7801 (org-back-to-heading t)
7802 (if (org-previous-line-empty-p) (setq empty-line-p t))
7803 (looking-at org-outline-regexp)
7804 (make-string (1- (length (match-string 0))) ?*))))
7805 (stars
7806 (save-excursion
7807 (condition-case nil
7808 (if top-level "* "
7809 (org-back-to-heading invisible-ok)
7810 (when (and (not on-heading)
7811 (featurep 'org-inlinetask)
7812 (integerp org-inlinetask-min-level)
7813 (>= (length (match-string 0))
7814 org-inlinetask-min-level))
7815 ;; Find a heading level before the inline
7816 ;; task.
7817 (while (and (setq level (org-up-heading-safe))
7818 (>= level org-inlinetask-min-level)))
7819 (if (org-at-heading-p)
7820 (org-back-to-heading invisible-ok)
7821 (error "This should not happen")))
7822 (unless (and (save-excursion
7823 (save-match-data
7824 (org-backward-heading-same-level
7825 1 invisible-ok))
7826 (= (point) (match-beginning 0)))
7827 (not (org-previous-line-empty-p t)))
7828 (setq empty-line-p (or empty-line-p
7829 (org-previous-line-empty-p))))
7830 (match-string 0))
7831 (error (or fix-level "* ")))))
7832 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7833 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7834 pos hide-previous previous-pos)
7836 ;; If we insert after content, move there and clean up
7837 ;; whitespace.
7838 (when (and respect-content
7839 (not (org-looking-at-p org-outline-regexp-bol)))
7840 (if (not (org-before-first-heading-p))
7841 (org-end-of-subtree nil t)
7842 (re-search-forward org-outline-regexp-bol)
7843 (beginning-of-line 0))
7844 (skip-chars-backward " \r\t\n")
7845 (and (not (org-looking-back "^\\*+" (line-beginning-position)))
7846 (looking-at "[ \t]+") (replace-match ""))
7847 (unless (eobp) (forward-char 1))
7848 (when (looking-at "^\\*")
7849 (unless (bobp) (backward-char 1))
7850 (insert "\n")))
7852 ;; If we are splitting, grab the text that should be moved
7853 ;; to the new headline.
7854 (when may-split
7855 (if (org-on-heading-p)
7856 ;; This is a heading: split intelligently (keeping
7857 ;; tags).
7858 (let ((pos (point)))
7859 (beginning-of-line)
7860 (unless (looking-at org-complex-heading-regexp)
7861 (error "This should not happen"))
7862 (when (and (match-beginning 4)
7863 (> pos (match-beginning 4))
7864 (< pos (match-end 4)))
7865 (setq initial-content (buffer-substring pos (match-end 4)))
7866 (goto-char pos)
7867 (delete-region (point) (match-end 4))
7868 (if (looking-at "[ \t]*$")
7869 (replace-match "")
7870 (insert (make-string (length initial-content) ?\s)))
7871 (setq initial-content (org-trim initial-content)))
7872 (goto-char pos))
7873 ;; A normal line.
7874 (setq initial-content
7875 (org-trim
7876 (delete-and-extract-region (point) (line-end-position))))))
7878 ;; If we are at the beginning of the line, insert before it.
7879 ;; Otherwise, after it.
7880 (cond
7881 ((and (bolp) (looking-at "[ \t]*$")))
7882 ((bolp) (save-excursion (insert "\n")))
7883 (t (end-of-line)
7884 (insert "\n")))
7886 ;; Insert the new heading
7887 (insert stars)
7888 (just-one-space)
7889 (insert initial-content)
7890 (unless (and blank (org-previous-line-empty-p))
7891 (org-N-empty-lines-before-current (if blank 1 0)))
7892 ;; Adjust visibility, which may be messed up if we removed
7893 ;; blank lines while previous entry was hidden.
7894 (let ((bol (line-beginning-position)))
7895 (dolist (o (overlays-at (1- bol)))
7896 (when (and (eq (overlay-get o 'invisible) 'outline)
7897 (eq (overlay-end o) bol))
7898 (move-overlay o (overlay-start o) (1- bol)))))
7899 (run-hooks 'org-insert-heading-hook)))))))
7901 (defun org-N-empty-lines-before-current (N)
7902 "Make the number of empty lines before current exactly N.
7903 So this will delete or add empty lines."
7904 (save-excursion
7905 (beginning-of-line)
7906 (let ((p (point)))
7907 (skip-chars-backward " \r\t\n")
7908 (unless (bolp) (forward-line))
7909 (delete-region (point) p))
7910 (when (> N 0) (insert (make-string N ?\n)))))
7912 (defun org-get-heading (&optional no-tags no-todo)
7913 "Return the heading of the current entry, without the stars.
7914 When NO-TAGS is non-nil, don't include tags.
7915 When NO-TODO is non-nil, don't include TODO keywords."
7916 (save-excursion
7917 (org-back-to-heading t)
7918 (cond
7919 ((and no-tags no-todo)
7920 (looking-at org-complex-heading-regexp)
7921 (match-string 4))
7922 (no-tags
7923 (looking-at (concat org-outline-regexp
7924 "\\(.*?\\)"
7925 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7926 (match-string 1))
7927 (no-todo
7928 (looking-at org-todo-line-regexp)
7929 (match-string 3))
7930 (t (looking-at org-heading-regexp)
7931 (match-string 2)))))
7933 (defvar orgstruct-mode) ; defined below
7935 (defun org-heading-components ()
7936 "Return the components of the current heading.
7937 This is a list with the following elements:
7938 - the level as an integer
7939 - the reduced level, different if `org-odd-levels-only' is set.
7940 - the TODO keyword, or nil
7941 - the priority character, like ?A, or nil if no priority is given
7942 - the headline text itself, or the tags string if no headline text
7943 - the tags string, or nil."
7944 (save-excursion
7945 (org-back-to-heading t)
7946 (if (let (case-fold-search)
7947 (looking-at
7948 (if orgstruct-mode
7949 org-heading-regexp
7950 org-complex-heading-regexp)))
7951 (if orgstruct-mode
7952 (list (length (match-string 1))
7953 (org-reduced-level (length (match-string 1)))
7956 (match-string 2)
7957 nil)
7958 (list (length (match-string 1))
7959 (org-reduced-level (length (match-string 1)))
7960 (org-match-string-no-properties 2)
7961 (and (match-end 3) (aref (match-string 3) 2))
7962 (org-match-string-no-properties 4)
7963 (org-match-string-no-properties 5))))))
7965 (defun org-get-entry ()
7966 "Get the entry text, after heading, entire subtree."
7967 (save-excursion
7968 (org-back-to-heading t)
7969 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7971 (defun org-insert-heading-after-current ()
7972 "Insert a new heading with same level as current, after current subtree."
7973 (interactive)
7974 (org-back-to-heading)
7975 (org-insert-heading)
7976 (org-move-subtree-down)
7977 (end-of-line 1))
7979 (defun org-insert-heading-respect-content (&optional invisible-ok)
7980 "Insert heading with `org-insert-heading-respect-content' set to t."
7981 (interactive)
7982 (org-insert-heading '(4) invisible-ok))
7984 (defun org-insert-todo-heading-respect-content (&optional force-state)
7985 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7986 (interactive)
7987 (org-insert-todo-heading force-state '(4)))
7989 (defun org-insert-todo-heading (arg &optional force-heading)
7990 "Insert a new heading with the same level and TODO state as current heading.
7991 If the heading has no TODO state, or if the state is DONE, use the first
7992 state (TODO by default). Also with one prefix arg, force first state. With
7993 two prefix args, force inserting at the end of the parent subtree."
7994 (interactive "P")
7995 (when (or force-heading (not (org-insert-item 'checkbox)))
7996 (org-insert-heading (or (and (equal arg '(16)) '(16))
7997 force-heading))
7998 (save-excursion
7999 (org-back-to-heading)
8000 (outline-previous-heading)
8001 (looking-at org-todo-line-regexp))
8002 (let*
8003 ((new-mark-x
8004 (if (or (equal arg '(4))
8005 (not (match-beginning 2))
8006 (member (match-string 2) org-done-keywords))
8007 (car org-todo-keywords-1)
8008 (match-string 2)))
8009 (new-mark
8011 (run-hook-with-args-until-success
8012 'org-todo-get-default-hook new-mark-x nil)
8013 new-mark-x)))
8014 (beginning-of-line 1)
8015 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8016 (if org-treat-insert-todo-heading-as-state-change
8017 (org-todo new-mark)
8018 (insert new-mark " "))))
8019 (when org-provide-todo-statistics
8020 (org-update-parent-todo-statistics))))
8022 (defun org-insert-subheading (arg)
8023 "Insert a new subheading and demote it.
8024 Works for outline headings and for plain lists alike."
8025 (interactive "P")
8026 (org-insert-heading arg)
8027 (cond
8028 ((org-at-heading-p) (org-do-demote))
8029 ((org-at-item-p) (org-indent-item))))
8031 (defun org-insert-todo-subheading (arg)
8032 "Insert a new subheading with TODO keyword or checkbox and demote it.
8033 Works for outline headings and for plain lists alike."
8034 (interactive "P")
8035 (org-insert-todo-heading arg)
8036 (cond
8037 ((org-at-heading-p) (org-do-demote))
8038 ((org-at-item-p) (org-indent-item))))
8040 ;;; Promotion and Demotion
8042 (defvar org-after-demote-entry-hook nil
8043 "Hook run after an entry has been demoted.
8044 The cursor will be at the beginning of the entry.
8045 When a subtree is being demoted, the hook will be called for each node.")
8047 (defvar org-after-promote-entry-hook nil
8048 "Hook run after an entry has been promoted.
8049 The cursor will be at the beginning of the entry.
8050 When a subtree is being promoted, the hook will be called for each node.")
8052 (defun org-promote-subtree ()
8053 "Promote the entire subtree.
8054 See also `org-promote'."
8055 (interactive)
8056 (save-excursion
8057 (org-with-limited-levels (org-map-tree 'org-promote)))
8058 (org-fix-position-after-promote))
8060 (defun org-demote-subtree ()
8061 "Demote the entire subtree.
8062 See `org-demote' and `org-promote'."
8063 (interactive)
8064 (save-excursion
8065 (org-with-limited-levels (org-map-tree 'org-demote)))
8066 (org-fix-position-after-promote))
8068 (defun org-do-promote ()
8069 "Promote the current heading higher up the tree.
8070 If the region is active in `transient-mark-mode', promote all
8071 headings in the region."
8072 (interactive)
8073 (save-excursion
8074 (if (org-region-active-p)
8075 (org-map-region 'org-promote (region-beginning) (region-end))
8076 (org-promote)))
8077 (org-fix-position-after-promote))
8079 (defun org-do-demote ()
8080 "Demote the current heading lower down the tree.
8081 If the region is active in `transient-mark-mode', demote all
8082 headings in the region."
8083 (interactive)
8084 (save-excursion
8085 (if (org-region-active-p)
8086 (org-map-region 'org-demote (region-beginning) (region-end))
8087 (org-demote)))
8088 (org-fix-position-after-promote))
8090 (defun org-fix-position-after-promote ()
8091 "Fix cursor position and indentation after demoting/promoting."
8092 (let ((pos (point)))
8093 (when (save-excursion
8094 (beginning-of-line 1)
8095 (looking-at org-todo-line-regexp)
8096 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8097 (cond ((eobp) (insert " "))
8098 ((eolp) (insert " "))
8099 ((equal (char-after) ?\ ) (forward-char 1))))))
8101 (defun org-current-level ()
8102 "Return the level of the current entry, or nil if before the first headline.
8103 The level is the number of stars at the beginning of the
8104 headline. Use `org-reduced-level' to remove the effect of
8105 `org-odd-levels'. Unlike to `org-outline-level', this function
8106 ignores inlinetasks."
8107 (let ((level (org-with-limited-levels (org-outline-level))))
8108 (and (> level 0) level)))
8110 (defun org-get-previous-line-level ()
8111 "Return the outline depth of the last headline before the current line.
8112 Returns 0 for the first headline in the buffer, and nil if before the
8113 first headline."
8114 (and (org-current-level)
8115 (or (and (/= (line-beginning-position) (point-min))
8116 (save-excursion (beginning-of-line 0) (org-current-level)))
8117 0)))
8119 (defun org-reduced-level (l)
8120 "Compute the effective level of a heading.
8121 This takes into account the setting of `org-odd-levels-only'."
8122 (cond
8123 ((zerop l) 0)
8124 (org-odd-levels-only (1+ (floor (/ l 2))))
8125 (t l)))
8127 (defun org-level-increment ()
8128 "Return the number of stars that will be added or removed at a
8129 time to headlines when structure editing, based on the value of
8130 `org-odd-levels-only'."
8131 (if org-odd-levels-only 2 1))
8133 (defun org-get-valid-level (level &optional change)
8134 "Rectify a level change under the influence of `org-odd-levels-only'
8135 LEVEL is a current level, CHANGE is by how much the level should be
8136 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8137 even level numbers will become the next higher odd number."
8138 (if org-odd-levels-only
8139 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8140 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8141 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8142 (max 1 (+ level (or change 0)))))
8144 (if (boundp 'define-obsolete-function-alias)
8145 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8146 (define-obsolete-function-alias 'org-get-legal-level
8147 'org-get-valid-level)
8148 (define-obsolete-function-alias 'org-get-legal-level
8149 'org-get-valid-level "23.1")))
8151 (defun org-promote ()
8152 "Promote the current heading higher up the tree."
8153 (org-with-wide-buffer
8154 (org-back-to-heading t)
8155 (let* ((after-change-functions (remq 'flyspell-after-change-function
8156 after-change-functions))
8157 (level (save-match-data (funcall outline-level)))
8158 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8159 (diff (abs (- level (length up-head) -1))))
8160 (cond
8161 ((and (= level 1) org-allow-promoting-top-level-subtree)
8162 (replace-match "# " nil t))
8163 ((= level 1)
8164 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8165 (t (replace-match up-head nil t)))
8166 (unless (= level 1)
8167 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8168 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8169 (run-hooks 'org-after-promote-entry-hook))))
8171 (defun org-demote ()
8172 "Demote the current heading lower down the tree."
8173 (org-with-wide-buffer
8174 (org-back-to-heading t)
8175 (let* ((after-change-functions (remq 'flyspell-after-change-function
8176 after-change-functions))
8177 (level (save-match-data (funcall outline-level)))
8178 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8179 (diff (abs (- level (length down-head) -1))))
8180 (replace-match down-head nil t)
8181 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8182 (when org-adapt-indentation (org-fixup-indentation diff))
8183 (run-hooks 'org-after-demote-entry-hook))))
8185 (defun org-cycle-level ()
8186 "Cycle the level of an empty headline through possible states.
8187 This goes first to child, then to parent, level, then up the hierarchy.
8188 After top level, it switches back to sibling level."
8189 (interactive)
8190 (let ((org-adapt-indentation nil))
8191 (when (org-point-at-end-of-empty-headline)
8192 (setq this-command 'org-cycle-level) ; Only needed for caching
8193 (let ((cur-level (org-current-level))
8194 (prev-level (org-get-previous-line-level)))
8195 (cond
8196 ;; If first headline in file, promote to top-level.
8197 ((= prev-level 0)
8198 (loop repeat (/ (- cur-level 1) (org-level-increment))
8199 do (org-do-promote)))
8200 ;; If same level as prev, demote one.
8201 ((= prev-level cur-level)
8202 (org-do-demote))
8203 ;; If parent is top-level, promote to top level if not already.
8204 ((= prev-level 1)
8205 (loop repeat (/ (- cur-level 1) (org-level-increment))
8206 do (org-do-promote)))
8207 ;; If top-level, return to prev-level.
8208 ((= cur-level 1)
8209 (loop repeat (/ (- prev-level 1) (org-level-increment))
8210 do (org-do-demote)))
8211 ;; If less than prev-level, promote one.
8212 ((< cur-level prev-level)
8213 (org-do-promote))
8214 ;; If deeper than prev-level, promote until higher than
8215 ;; prev-level.
8216 ((> cur-level prev-level)
8217 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8218 do (org-do-promote))))
8219 t))))
8221 (defun org-map-tree (fun)
8222 "Call FUN for every heading underneath the current one."
8223 (org-back-to-heading)
8224 (let ((level (funcall outline-level)))
8225 (save-excursion
8226 (funcall fun)
8227 (while (and (progn
8228 (outline-next-heading)
8229 (> (funcall outline-level) level))
8230 (not (eobp)))
8231 (funcall fun)))))
8233 (defun org-map-region (fun beg end)
8234 "Call FUN for every heading between BEG and END."
8235 (let ((org-ignore-region t))
8236 (save-excursion
8237 (setq end (copy-marker end))
8238 (goto-char beg)
8239 (if (and (re-search-forward org-outline-regexp-bol nil t)
8240 (< (point) end))
8241 (funcall fun))
8242 (while (and (progn
8243 (outline-next-heading)
8244 (< (point) end))
8245 (not (eobp)))
8246 (funcall fun)))))
8248 (defun org-fixup-indentation (diff)
8249 "Change the indentation in the current entry by DIFF.
8251 DIFF is an integer. Indentation is done according to the
8252 following rules:
8254 - Planning information and property drawers are always indented
8255 according to the new level of the headline;
8257 - Footnote definitions and their contents are ignored;
8259 - Inlinetasks' boundaries are not shifted;
8261 - Empty lines are ignored;
8263 - Other lines' indentation are shifted by DIFF columns, unless
8264 it would introduce a structural change in the document, in
8265 which case no shifting is done at all.
8267 Assume point is at a heading or an inlinetask beginning."
8268 (org-with-wide-buffer
8269 (narrow-to-region (line-beginning-position)
8270 (save-excursion
8271 (if (org-with-limited-levels (org-at-heading-p))
8272 (org-with-limited-levels (outline-next-heading))
8273 (org-inlinetask-goto-end))
8274 (point)))
8275 (forward-line)
8276 ;; Indent properly planning info and property drawer.
8277 (when (org-looking-at-p org-planning-line-re)
8278 (org-indent-line)
8279 (forward-line))
8280 (when (looking-at org-property-drawer-re)
8281 (goto-char (match-end 0))
8282 (forward-line)
8283 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8284 (catch 'no-shift
8285 (when (zerop diff) (throw 'no-shift nil))
8286 ;; If DIFF is negative, first check if a shift is possible at all
8287 ;; (e.g., it doesn't break structure). This can only happen if
8288 ;; some contents are not properly indented.
8289 (let ((case-fold-search t))
8290 (when (< diff 0)
8291 (let ((diff (- diff))
8292 (forbidden-re (concat org-outline-regexp
8293 "\\|"
8294 (substring org-footnote-definition-re 1))))
8295 (save-excursion
8296 (while (not (eobp))
8297 (cond
8298 ((org-looking-at-p "[ \t]*$") (forward-line))
8299 ((and (org-looking-at-p org-footnote-definition-re)
8300 (let ((e (org-element-at-point)))
8301 (and (eq (org-element-type e) 'footnote-definition)
8302 (goto-char (org-element-property :end e))))))
8303 ((org-looking-at-p org-outline-regexp) (forward-line))
8304 ;; Give up if shifting would move before column 0 or
8305 ;; if it would introduce a headline or a footnote
8306 ;; definition.
8308 (skip-chars-forward " \t")
8309 (let ((ind (current-column)))
8310 (when (or (< ind diff)
8311 (and (= ind diff) (org-looking-at-p forbidden-re)))
8312 (throw 'no-shift nil)))
8313 ;; Ignore contents of example blocks and source
8314 ;; blocks if their indentation is meant to be
8315 ;; preserved. Jump to block's closing line.
8316 (beginning-of-line)
8317 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8318 (let ((e (org-element-at-point)))
8319 (and (memq (org-element-type e)
8320 '(example-block src-block))
8321 (or org-src-preserve-indentation
8322 (org-element-property :preserve-indent e))
8323 (goto-char (org-element-property :end e))
8324 (progn (skip-chars-backward " \r\t\n")
8325 (beginning-of-line)
8326 t))))
8327 (forward-line))))))))
8328 ;; Shift lines but footnote definitions, inlinetasks boundaries
8329 ;; by DIFF. Also skip contents of source or example blocks
8330 ;; when indentation is meant to be preserved.
8331 (while (not (eobp))
8332 (cond
8333 ((and (org-looking-at-p org-footnote-definition-re)
8334 (let ((e (org-element-at-point)))
8335 (and (eq (org-element-type e) 'footnote-definition)
8336 (goto-char (org-element-property :end e))))))
8337 ((org-looking-at-p org-outline-regexp) (forward-line))
8338 ((org-looking-at-p "[ \t]*$") (forward-line))
8340 (org-indent-line-to (+ (org-get-indentation) diff))
8341 (beginning-of-line)
8342 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8343 (let ((e (org-element-at-point)))
8344 (and (memq (org-element-type e)
8345 '(example-block src-block))
8346 (or org-src-preserve-indentation
8347 (org-element-property :preserve-indent e))
8348 (goto-char (org-element-property :end e))
8349 (progn (skip-chars-backward " \r\t\n")
8350 (beginning-of-line)
8351 t))))
8352 (forward-line)))))))))
8354 (defun org-convert-to-odd-levels ()
8355 "Convert an org-mode file with all levels allowed to one with odd levels.
8356 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8357 level 5 etc."
8358 (interactive)
8359 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8360 (let ((outline-level 'org-outline-level)
8361 (org-odd-levels-only nil) n)
8362 (save-excursion
8363 (goto-char (point-min))
8364 (while (re-search-forward "^\\*\\*+ " nil t)
8365 (setq n (- (length (match-string 0)) 2))
8366 (while (>= (setq n (1- n)) 0)
8367 (org-demote))
8368 (end-of-line 1))))))
8370 (defun org-convert-to-oddeven-levels ()
8371 "Convert an org-mode file with only odd levels to one with odd/even levels.
8372 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8373 file contains a section with an even level, conversion would
8374 destroy the structure of the file. An error is signaled in this
8375 case."
8376 (interactive)
8377 (goto-char (point-min))
8378 ;; First check if there are no even levels
8379 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8380 (org-show-set-visibility 'canonical)
8381 (error "Not all levels are odd in this file. Conversion not possible"))
8382 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8383 (let ((outline-regexp org-outline-regexp)
8384 (outline-level 'org-outline-level)
8385 (org-odd-levels-only nil) n)
8386 (save-excursion
8387 (goto-char (point-min))
8388 (while (re-search-forward "^\\*\\*+ " nil t)
8389 (setq n (/ (1- (length (match-string 0))) 2))
8390 (while (>= (setq n (1- n)) 0)
8391 (org-promote))
8392 (end-of-line 1))))))
8394 (defun org-tr-level (n)
8395 "Make N odd if required."
8396 (if org-odd-levels-only (1+ (/ n 2)) n))
8398 ;;; Vertical tree motion, cutting and pasting of subtrees
8400 (defun org-move-subtree-up (&optional arg)
8401 "Move the current subtree up past ARG headlines of the same level."
8402 (interactive "p")
8403 (org-move-subtree-down (- (prefix-numeric-value arg))))
8405 (defun org-move-subtree-down (&optional arg)
8406 "Move the current subtree down past ARG headlines of the same level."
8407 (interactive "p")
8408 (setq arg (prefix-numeric-value arg))
8409 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8410 'org-get-last-sibling))
8411 (ins-point (make-marker))
8412 (cnt (abs arg))
8413 (col (current-column))
8414 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8415 ;; Select the tree
8416 (org-back-to-heading)
8417 (setq beg0 (point))
8418 (save-excursion
8419 (setq ne-beg (org-back-over-empty-lines))
8420 (setq beg (point)))
8421 (save-match-data
8422 (save-excursion (outline-end-of-heading)
8423 (setq folded (outline-invisible-p)))
8424 (progn (org-end-of-subtree nil t)
8425 (unless (eobp) (backward-char))))
8426 (outline-next-heading)
8427 (setq ne-end (org-back-over-empty-lines))
8428 (setq end (point))
8429 (goto-char beg0)
8430 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8431 ;; include less whitespace
8432 (save-excursion
8433 (goto-char beg)
8434 (forward-line (- ne-beg ne-end))
8435 (setq beg (point))))
8436 ;; Find insertion point, with error handling
8437 (while (> cnt 0)
8438 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8439 (progn (goto-char beg0)
8440 (user-error "Cannot move past superior level or buffer limit")))
8441 (setq cnt (1- cnt)))
8442 (if (> arg 0)
8443 ;; Moving forward - still need to move over subtree
8444 (progn (org-end-of-subtree t t)
8445 (save-excursion
8446 (org-back-over-empty-lines)
8447 (or (bolp) (newline)))))
8448 (setq ne-ins (org-back-over-empty-lines))
8449 (move-marker ins-point (point))
8450 (setq txt (buffer-substring beg end))
8451 (org-save-markers-in-region beg end)
8452 (delete-region beg end)
8453 (org-remove-empty-overlays-at beg)
8454 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8455 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8456 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8457 (let ((bbb (point)))
8458 (insert-before-markers txt)
8459 (org-reinstall-markers-in-region bbb)
8460 (move-marker ins-point bbb))
8461 (or (bolp) (insert "\n"))
8462 (setq ins-end (point))
8463 (goto-char ins-point)
8464 (org-skip-whitespace)
8465 (when (and (< arg 0)
8466 (org-first-sibling-p)
8467 (> ne-ins ne-beg))
8468 ;; Move whitespace back to beginning
8469 (save-excursion
8470 (goto-char ins-end)
8471 (let ((kill-whole-line t))
8472 (kill-line (- ne-ins ne-beg)) (point)))
8473 (insert (make-string (- ne-ins ne-beg) ?\n)))
8474 (move-marker ins-point nil)
8475 (if folded
8476 (outline-hide-subtree)
8477 (org-show-entry)
8478 (org-show-children)
8479 (org-cycle-hide-drawers 'children))
8480 (org-clean-visibility-after-subtree-move)
8481 ;; move back to the initial column we were at
8482 (move-to-column col)))
8484 (defvar org-subtree-clip ""
8485 "Clipboard for cut and paste of subtrees.
8486 This is actually only a copy of the kill, because we use the normal kill
8487 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8489 (defvar org-subtree-clip-folded nil
8490 "Was the last copied subtree folded?
8491 This is used to fold the tree back after pasting.")
8493 (defun org-cut-subtree (&optional n)
8494 "Cut the current subtree into the clipboard.
8495 With prefix arg N, cut this many sequential subtrees.
8496 This is a short-hand for marking the subtree and then cutting it."
8497 (interactive "p")
8498 (org-copy-subtree n 'cut))
8500 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8501 "Copy the current subtree it in the clipboard.
8502 With prefix arg N, copy this many sequential subtrees.
8503 This is a short-hand for marking the subtree and then copying it.
8504 If CUT is non-nil, actually cut the subtree.
8505 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8506 of some markers in the region, even if CUT is non-nil. This is
8507 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8508 (interactive "p")
8509 (let (beg end folded (beg0 (point)))
8510 (if (org-called-interactively-p 'any)
8511 (org-back-to-heading nil) ; take what looks like a subtree
8512 (org-back-to-heading t)) ; take what is really there
8513 (setq beg (point))
8514 (skip-chars-forward " \t\r\n")
8515 (save-match-data
8516 (if nosubtrees
8517 (outline-next-heading)
8518 (save-excursion (outline-end-of-heading)
8519 (setq folded (outline-invisible-p)))
8520 (ignore-errors (org-forward-heading-same-level (1- n) t))
8521 (org-end-of-subtree t t)))
8522 ;; Include the end of an inlinetask
8523 (when (and (featurep 'org-inlinetask)
8524 (looking-at-p (concat (org-inlinetask-outline-regexp)
8525 "END[ \t]*$")))
8526 (end-of-line))
8527 (setq end (point))
8528 (goto-char beg0)
8529 (when (> end beg)
8530 (setq org-subtree-clip-folded folded)
8531 (when (or cut force-store-markers)
8532 (org-save-markers-in-region beg end))
8533 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8534 (setq org-subtree-clip (current-kill 0))
8535 (message "%s: Subtree(s) with %d characters"
8536 (if cut "Cut" "Copied")
8537 (length org-subtree-clip)))))
8539 (defun org-paste-subtree (&optional level tree for-yank remove)
8540 "Paste the clipboard as a subtree, with modification of headline level.
8541 The entire subtree is promoted or demoted in order to match a new headline
8542 level.
8544 If the cursor is at the beginning of a headline, the same level as
8545 that headline is used to paste the tree.
8547 If not, the new level is derived from the *visible* headings
8548 before and after the insertion point, and taken to be the inferior headline
8549 level of the two. So if the previous visible heading is level 3 and the
8550 next is level 4 (or vice versa), level 4 will be used for insertion.
8551 This makes sure that the subtree remains an independent subtree and does
8552 not swallow low level entries.
8554 You can also force a different level, either by using a numeric prefix
8555 argument, or by inserting the heading marker by hand. For example, if the
8556 cursor is after \"*****\", then the tree will be shifted to level 5.
8558 If optional TREE is given, use this text instead of the kill ring.
8560 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8561 move back over whitespace before inserting, and move point to the end of
8562 the inserted text when done.
8564 When REMOVE is non-nil, remove the subtree from the clipboard."
8565 (interactive "P")
8566 (setq tree (or tree (and kill-ring (current-kill 0))))
8567 (unless (org-kill-is-subtree-p tree)
8568 (user-error "%s"
8569 (substitute-command-keys
8570 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8571 (org-with-limited-levels
8572 (let* ((visp (not (outline-invisible-p)))
8573 (txt tree)
8574 (^re_ "\\(\\*+\\)[ \t]*")
8575 (old-level (if (string-match org-outline-regexp-bol txt)
8576 (- (match-end 0) (match-beginning 0) 1)
8577 -1))
8578 (force-level (cond (level (prefix-numeric-value level))
8579 ((and (looking-at "[ \t]*$")
8580 (string-match
8581 "^\\*+$" (buffer-substring
8582 (point-at-bol) (point))))
8583 (- (match-end 0) (match-beginning 0)))
8584 ((and (bolp)
8585 (looking-at org-outline-regexp))
8586 (- (match-end 0) (point) 1))))
8587 (previous-level (save-excursion
8588 (condition-case nil
8589 (progn
8590 (outline-previous-visible-heading 1)
8591 (if (looking-at ^re_)
8592 (- (match-end 0) (match-beginning 0) 1)
8594 (error 1))))
8595 (next-level (save-excursion
8596 (condition-case nil
8597 (progn
8598 (or (looking-at org-outline-regexp)
8599 (outline-next-visible-heading 1))
8600 (if (looking-at ^re_)
8601 (- (match-end 0) (match-beginning 0) 1)
8603 (error 1))))
8604 (new-level (or force-level (max previous-level next-level)))
8605 (shift (if (or (= old-level -1)
8606 (= new-level -1)
8607 (= old-level new-level))
8609 (- new-level old-level)))
8610 (delta (if (> shift 0) -1 1))
8611 (func (if (> shift 0) 'org-demote 'org-promote))
8612 (org-odd-levels-only nil)
8613 beg end newend)
8614 ;; Remove the forced level indicator
8615 (if force-level
8616 (delete-region (point-at-bol) (point)))
8617 ;; Paste
8618 (beginning-of-line (if (bolp) 1 2))
8619 (setq beg (point))
8620 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8621 (insert-before-markers txt)
8622 (unless (string-match "\n\\'" txt) (insert "\n"))
8623 (setq newend (point))
8624 (org-reinstall-markers-in-region beg)
8625 (setq end (point))
8626 (goto-char beg)
8627 (skip-chars-forward " \t\n\r")
8628 (setq beg (point))
8629 (if (and (outline-invisible-p) visp)
8630 (save-excursion (outline-show-heading)))
8631 ;; Shift if necessary
8632 (unless (= shift 0)
8633 (save-restriction
8634 (narrow-to-region beg end)
8635 (while (not (= shift 0))
8636 (org-map-region func (point-min) (point-max))
8637 (setq shift (+ delta shift)))
8638 (goto-char (point-min))
8639 (setq newend (point-max))))
8640 (when (or (org-called-interactively-p 'interactive) for-yank)
8641 (message "Clipboard pasted as level %d subtree" new-level))
8642 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8643 kill-ring
8644 (eq org-subtree-clip (current-kill 0))
8645 org-subtree-clip-folded)
8646 ;; The tree was folded before it was killed/copied
8647 (outline-hide-subtree))
8648 (and for-yank (goto-char newend))
8649 (and remove (setq kill-ring (cdr kill-ring))))))
8651 (defun org-kill-is-subtree-p (&optional txt)
8652 "Check if the current kill is an outline subtree, or a set of trees.
8653 Returns nil if kill does not start with a headline, or if the first
8654 headline level is not the largest headline level in the tree.
8655 So this will actually accept several entries of equal levels as well,
8656 which is OK for `org-paste-subtree'.
8657 If optional TXT is given, check this string instead of the current kill."
8658 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8659 (re (org-get-limited-outline-regexp))
8660 (^re (concat "^" re))
8661 (start-level (and kill
8662 (string-match
8663 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8664 kill)
8665 (- (match-end 2) (match-beginning 2) 1)))
8666 (start (1+ (or (match-beginning 2) -1))))
8667 (if (not start-level)
8668 (progn
8669 nil) ;; does not even start with a heading
8670 (catch 'exit
8671 (while (setq start (string-match ^re kill (1+ start)))
8672 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8673 (throw 'exit nil)))
8674 t))))
8676 (defvar org-markers-to-move nil
8677 "Markers that should be moved with a cut-and-paste operation.
8678 Those markers are stored together with their positions relative to
8679 the start of the region.")
8681 (defun org-save-markers-in-region (beg end)
8682 "Check markers in region.
8683 If these markers are between BEG and END, record their position relative
8684 to BEG, so that after moving the block of text, we can put the markers back
8685 into place.
8686 This function gets called just before an entry or tree gets cut from the
8687 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8688 called immediately, to move the markers with the entries."
8689 (setq org-markers-to-move nil)
8690 (when (featurep 'org-clock)
8691 (org-clock-save-markers-for-cut-and-paste beg end))
8692 (when (featurep 'org-agenda)
8693 (org-agenda-save-markers-for-cut-and-paste beg end)))
8695 (defun org-check-and-save-marker (marker beg end)
8696 "Check if MARKER is between BEG and END.
8697 If yes, remember the marker and the distance to BEG."
8698 (when (and (marker-buffer marker)
8699 (equal (marker-buffer marker) (current-buffer)))
8700 (if (and (>= marker beg) (< marker end))
8701 (push (cons marker (- marker beg)) org-markers-to-move))))
8703 (defun org-reinstall-markers-in-region (beg)
8704 "Move all remembered markers to their position relative to BEG."
8705 (mapc (lambda (x)
8706 (move-marker (car x) (+ beg (cdr x))))
8707 org-markers-to-move)
8708 (setq org-markers-to-move nil))
8710 (defun org-narrow-to-subtree ()
8711 "Narrow buffer to the current subtree."
8712 (interactive)
8713 (save-excursion
8714 (save-match-data
8715 (org-with-limited-levels
8716 (narrow-to-region
8717 (progn (org-back-to-heading t) (point))
8718 (progn (org-end-of-subtree t t)
8719 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8720 (point)))))))
8722 (defun org-narrow-to-block ()
8723 "Narrow buffer to the current block."
8724 (interactive)
8725 (let* ((case-fold-search t)
8726 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8727 "^[ \t]*#\\+end_.*")))
8728 (if blockp
8729 (narrow-to-region (car blockp) (cdr blockp))
8730 (user-error "Not in a block"))))
8732 (defun org-clone-subtree-with-time-shift (n &optional shift)
8733 "Clone the task (subtree) at point N times.
8734 The clones will be inserted as siblings.
8736 In interactive use, the user will be prompted for the number of
8737 clones to be produced. If the entry has a timestamp, the user
8738 will also be prompted for a time shift, which may be a repeater
8739 as used in time stamps, for example `+3d'. To disable this,
8740 you can call the function with a universal prefix argument.
8742 When a valid repeater is given and the entry contains any time
8743 stamps, the clones will become a sequence in time, with time
8744 stamps in the subtree shifted for each clone produced. If SHIFT
8745 is nil or the empty string, time stamps will be left alone. The
8746 ID property of the original subtree is removed.
8748 If the original subtree did contain time stamps with a repeater,
8749 the following will happen:
8750 - the repeater will be removed in each clone
8751 - an additional clone will be produced, with the current, unshifted
8752 date(s) in the entry.
8753 - the original entry will be placed *after* all the clones, with
8754 repeater intact.
8755 - the start days in the repeater in the original entry will be shifted
8756 to past the last clone.
8757 In this way you can spell out a number of instances of a repeating task,
8758 and still retain the repeater to cover future instances of the task.
8760 As described above, N+1 clones are produced when the original
8761 subtree has a repeater. Setting N to 0, then, can be used to
8762 remove the repeater from a subtree and create a shifted clone
8763 with the original repeater."
8764 (interactive "nNumber of clones to produce: ")
8765 (let ((shift
8766 (or shift
8767 (if (and (not (equal current-prefix-arg '(4)))
8768 (save-excursion
8769 (re-search-forward org-ts-regexp-both
8770 (save-excursion
8771 (org-end-of-subtree t)
8772 (point)) t)))
8773 (read-from-minibuffer
8774 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8775 ""))) ;; No time shift
8776 (n-no-remove -1)
8777 (drawer-re org-drawer-regexp)
8778 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8779 beg end template task idprop
8780 shift-n shift-what doshift nmin nmax)
8781 (unless (wholenump n)
8782 (user-error "Invalid number of replications %s" n))
8783 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8784 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8785 shift)))
8786 (user-error "Invalid shift specification %s" shift))
8787 (when doshift
8788 (setq shift-n (string-to-number (match-string 1 shift))
8789 shift-what (cdr (assoc (match-string 2 shift)
8790 '(("d" . day) ("w" . week)
8791 ("m" . month) ("y" . year))))))
8792 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8793 (setq nmin 1 nmax n)
8794 (org-back-to-heading t)
8795 (setq beg (point))
8796 (setq idprop (org-entry-get nil "ID"))
8797 (org-end-of-subtree t t)
8798 (or (bolp) (insert "\n"))
8799 (setq end (point))
8800 (setq template (buffer-substring beg end))
8801 (when (and doshift
8802 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8803 (delete-region beg end)
8804 (setq end beg)
8805 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8806 (goto-char end)
8807 (loop for n from nmin to nmax do
8808 ;; prepare clone
8809 (with-temp-buffer
8810 (insert template)
8811 (org-mode)
8812 (goto-char (point-min))
8813 (org-show-subtree)
8814 (and idprop (if org-clone-delete-id
8815 (org-entry-delete nil "ID")
8816 (org-id-get-create t)))
8817 (unless (= n 0)
8818 (while (re-search-forward org-clock-re nil t)
8819 (kill-whole-line))
8820 (goto-char (point-min))
8821 (while (re-search-forward drawer-re nil t)
8822 (org-remove-empty-drawer-at (point))))
8823 (goto-char (point-min))
8824 (when doshift
8825 (while (re-search-forward org-ts-regexp-both nil t)
8826 (org-timestamp-change (* n shift-n) shift-what))
8827 (unless (= n n-no-remove)
8828 (goto-char (point-min))
8829 (while (re-search-forward org-ts-regexp nil t)
8830 (save-excursion
8831 (goto-char (match-beginning 0))
8832 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8833 (delete-region (match-beginning 1) (match-end 1)))))))
8834 (setq task (buffer-string)))
8835 (insert task))
8836 (goto-char beg)))
8838 ;;; Outline Sorting
8840 (defun org-sort (with-case)
8841 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8842 Optional argument WITH-CASE means sort case-sensitively."
8843 (interactive "P")
8844 (cond
8845 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8846 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8848 (org-call-with-arg 'org-sort-entries with-case))))
8850 (defun org-sort-remove-invisible (s)
8851 "Remove invisible links from string S."
8852 (remove-text-properties 0 (length s) org-rm-props s)
8853 (while (string-match org-bracket-link-regexp s)
8854 (setq s (replace-match (if (match-end 2)
8855 (match-string 3 s)
8856 (match-string 1 s))
8857 t t s)))
8858 (let ((st (format " %s " s)))
8859 (while (string-match org-emph-re st)
8860 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8861 (setq s (substring st 1 -1)))
8864 (defvar org-priority-regexp) ; defined later in the file
8866 (defvar org-after-sorting-entries-or-items-hook nil
8867 "Hook that is run after a bunch of entries or items have been sorted.
8868 When children are sorted, the cursor is in the parent line when this
8869 hook gets called. When a region or a plain list is sorted, the cursor
8870 will be in the first entry of the sorted region/list.")
8872 (defun org-sort-entries
8873 (&optional with-case sorting-type getkey-func compare-func property)
8874 "Sort entries on a certain level of an outline tree.
8875 If there is an active region, the entries in the region are sorted.
8876 Else, if the cursor is before the first entry, sort the top-level items.
8877 Else, the children of the entry at point are sorted.
8879 Sorting can be alphabetically, numerically, by date/time as given by
8880 a time stamp, by a property, by priority order, or by a custom function.
8882 The command prompts for the sorting type unless it has been given to the
8883 function through the SORTING-TYPE argument, which needs to be a character,
8884 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8885 the precise meaning of each character:
8887 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8888 c By creation time, which is assumed to be the first inactive time stamp
8889 at the beginning of a line.
8890 d By deadline date/time.
8891 k By clocking time.
8892 n Numerically, by converting the beginning of the entry/item to a number.
8893 o By order of TODO keywords.
8894 p By priority according to the cookie.
8895 r By the value of a property.
8896 s By scheduled date/time.
8897 t By date/time, either the first active time stamp in the entry, or, if
8898 none exist, by the first inactive one.
8900 Capital letters will reverse the sort order.
8902 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8903 called with point at the beginning of the record. It must return either
8904 a string or a number that should serve as the sorting key for that record.
8906 Comparing entries ignores case by default. However, with an optional argument
8907 WITH-CASE, the sorting considers case as well.
8909 Sorting is done against the visible part of the headlines, it ignores hidden
8910 links.
8912 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8913 (interactive "P")
8914 (let ((case-func (if with-case 'identity 'downcase))
8915 (cmstr
8916 ;; The clock marker is lost when using `sort-subr', let's
8917 ;; store the clocking string.
8918 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8919 (save-excursion
8920 (goto-char org-clock-marker)
8921 (buffer-substring-no-properties (line-beginning-position)
8922 (point)))))
8923 start beg end stars re re2
8924 txt what tmp)
8925 ;; Find beginning and end of region to sort
8926 (cond
8927 ((org-region-active-p)
8928 ;; we will sort the region
8929 (setq end (region-end)
8930 what "region")
8931 (goto-char (region-beginning))
8932 (if (not (org-at-heading-p)) (outline-next-heading))
8933 (setq start (point)))
8934 ((or (org-at-heading-p)
8935 (ignore-errors (progn (org-back-to-heading) t)))
8936 ;; we will sort the children of the current headline
8937 (org-back-to-heading)
8938 (setq start (point)
8939 end (progn (org-end-of-subtree t t)
8940 (or (bolp) (insert "\n"))
8941 (when (>= (org-back-over-empty-lines) 1)
8942 (forward-line 1))
8943 (point))
8944 what "children")
8945 (goto-char start)
8946 (outline-show-subtree)
8947 (outline-next-heading))
8949 ;; we will sort the top-level entries in this file
8950 (goto-char (point-min))
8951 (or (org-at-heading-p) (outline-next-heading))
8952 (setq start (point))
8953 (goto-char (point-max))
8954 (beginning-of-line 1)
8955 (when (looking-at ".*?\\S-")
8956 ;; File ends in a non-white line
8957 (end-of-line 1)
8958 (insert "\n"))
8959 (setq end (point-max))
8960 (setq what "top-level")
8961 (goto-char start)
8962 (outline-show-all)))
8964 (setq beg (point))
8965 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8967 (looking-at "\\(\\*+\\)")
8968 (setq stars (match-string 1)
8969 re (concat "^" (regexp-quote stars) " +")
8970 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8971 txt (buffer-substring beg end))
8972 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8973 (if (and (not (equal stars "*")) (string-match re2 txt))
8974 (user-error "Region to sort contains a level above the first entry"))
8976 (unless sorting-type
8977 (message
8978 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8979 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8980 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8981 what)
8982 (setq sorting-type (read-char-exclusive))
8984 (unless getkey-func
8985 (and (= (downcase sorting-type) ?f)
8986 (setq getkey-func
8987 (org-icompleting-read "Sort using function: "
8988 obarray 'fboundp t nil nil))
8989 (setq getkey-func (intern getkey-func))))
8991 (and (= (downcase sorting-type) ?r)
8992 (not property)
8993 (setq property
8994 (org-icompleting-read "Property: "
8995 (mapcar 'list (org-buffer-property-keys t))
8996 nil t))))
8998 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8999 (message "Sorting entries...")
9001 (save-restriction
9002 (narrow-to-region start end)
9003 (let ((dcst (downcase sorting-type))
9004 (case-fold-search nil)
9005 (now (current-time)))
9006 (sort-subr
9007 (/= dcst sorting-type)
9008 ;; This function moves to the beginning character of the "record" to
9009 ;; be sorted.
9010 (lambda nil
9011 (if (re-search-forward re nil t)
9012 (goto-char (match-beginning 0))
9013 (goto-char (point-max))))
9014 ;; This function moves to the last character of the "record" being
9015 ;; sorted.
9016 (lambda nil
9017 (save-match-data
9018 (condition-case nil
9019 (outline-forward-same-level 1)
9020 (error
9021 (goto-char (point-max))))))
9022 ;; This function returns the value that gets sorted against.
9023 (lambda nil
9024 (cond
9025 ((= dcst ?n)
9026 (if (looking-at org-complex-heading-regexp)
9027 (string-to-number (org-sort-remove-invisible (match-string 4)))
9028 nil))
9029 ((= dcst ?a)
9030 (if (looking-at org-complex-heading-regexp)
9031 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9032 nil))
9033 ((= dcst ?k)
9034 (or (get-text-property (point) :org-clock-minutes) 0))
9035 ((= dcst ?t)
9036 (let ((end (save-excursion (outline-next-heading) (point))))
9037 (if (or (re-search-forward org-ts-regexp end t)
9038 (re-search-forward org-ts-regexp-both end t))
9039 (org-time-string-to-seconds (match-string 0))
9040 (org-float-time now))))
9041 ((= dcst ?c)
9042 (let ((end (save-excursion (outline-next-heading) (point))))
9043 (if (re-search-forward
9044 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9045 end t)
9046 (org-time-string-to-seconds (match-string 0))
9047 (org-float-time now))))
9048 ((= dcst ?s)
9049 (let ((end (save-excursion (outline-next-heading) (point))))
9050 (if (re-search-forward org-scheduled-time-regexp end t)
9051 (org-time-string-to-seconds (match-string 1))
9052 (org-float-time now))))
9053 ((= dcst ?d)
9054 (let ((end (save-excursion (outline-next-heading) (point))))
9055 (if (re-search-forward org-deadline-time-regexp end t)
9056 (org-time-string-to-seconds (match-string 1))
9057 (org-float-time now))))
9058 ((= dcst ?p)
9059 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9060 (string-to-char (match-string 2))
9061 org-default-priority))
9062 ((= dcst ?r)
9063 (or (org-entry-get nil property) ""))
9064 ((= dcst ?o)
9065 (if (looking-at org-complex-heading-regexp)
9066 (let* ((m (match-string 2))
9067 (s (if (member m org-done-keywords) '- '+)))
9068 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9069 ((= dcst ?f)
9070 (if getkey-func
9071 (progn
9072 (setq tmp (funcall getkey-func))
9073 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
9074 tmp)
9075 (error "Invalid key function `%s'" getkey-func)))
9076 (t (error "Invalid sorting type `%c'" sorting-type))))
9078 (cond
9079 ((= dcst ?a) 'string<)
9080 ((= dcst ?f) compare-func)
9081 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9082 (run-hooks 'org-after-sorting-entries-or-items-hook)
9083 ;; Reset the clock marker if needed
9084 (when cmstr
9085 (save-excursion
9086 (goto-char start)
9087 (search-forward cmstr nil t)
9088 (move-marker org-clock-marker (point))))
9089 (message "Sorting entries...done")))
9091 ;;; The orgstruct minor mode
9093 ;; Define a minor mode which can be used in other modes in order to
9094 ;; integrate the org-mode structure editing commands.
9096 ;; This is really a hack, because the org-mode structure commands use
9097 ;; keys which normally belong to the major mode. Here is how it
9098 ;; works: The minor mode defines all the keys necessary to operate the
9099 ;; structure commands, but wraps the commands into a function which
9100 ;; tests if the cursor is currently at a headline or a plain list
9101 ;; item. If that is the case, the structure command is used,
9102 ;; temporarily setting many Org-mode variables like regular
9103 ;; expressions for filling etc. However, when any of those keys is
9104 ;; used at a different location, function uses `key-binding' to look
9105 ;; up if the key has an associated command in another currently active
9106 ;; keymap (minor modes, major mode, global), and executes that
9107 ;; command. There might be problems if any of the keys is otherwise
9108 ;; used as a prefix key.
9110 (defcustom orgstruct-heading-prefix-regexp ""
9111 "Regexp that matches the custom prefix of Org headlines in
9112 orgstruct(++)-mode."
9113 :group 'org
9114 :version "24.4"
9115 :package-version '(Org . "8.3")
9116 :type 'regexp)
9117 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9119 (defcustom orgstruct-setup-hook nil
9120 "Hook run after orgstruct-mode-map is filled."
9121 :group 'org
9122 :version "24.4"
9123 :package-version '(Org . "8.0")
9124 :type 'hook)
9126 (defvar orgstruct-initialized nil)
9128 (defvar org-local-vars nil
9129 "List of local variables, for use by `orgstruct-mode'.")
9131 ;;;###autoload
9132 (define-minor-mode orgstruct-mode
9133 "Toggle the minor mode `orgstruct-mode'.
9134 This mode is for using Org-mode structure commands in other
9135 modes. The following keys behave as if Org-mode were active, if
9136 the cursor is on a headline, or on a plain list item (both as
9137 defined by Org-mode)."
9138 nil " OrgStruct" (make-sparse-keymap)
9139 (funcall (if orgstruct-mode
9140 'add-to-invisibility-spec
9141 'remove-from-invisibility-spec)
9142 '(outline . t))
9143 (when orgstruct-mode
9144 (org-load-modules-maybe)
9145 (unless orgstruct-initialized
9146 (orgstruct-setup)
9147 (setq orgstruct-initialized t))))
9149 ;;;###autoload
9150 (defun turn-on-orgstruct ()
9151 "Unconditionally turn on `orgstruct-mode'."
9152 (orgstruct-mode 1))
9154 (defvar org-fb-vars nil)
9155 (make-variable-buffer-local 'org-fb-vars)
9156 (defun orgstruct++-mode (&optional arg)
9157 "Toggle `orgstruct-mode', the enhanced version of it.
9158 In addition to setting orgstruct-mode, this also exports all
9159 indentation and autofilling variables from org-mode into the
9160 buffer. It will also recognize item context in multiline items."
9161 (interactive "P")
9162 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9163 (if (< arg 1)
9164 (progn (orgstruct-mode -1)
9165 (mapc (lambda(v)
9166 (org-set-local (car v)
9167 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9168 org-fb-vars))
9169 (orgstruct-mode 1)
9170 (setq org-fb-vars nil)
9171 (unless org-local-vars
9172 (setq org-local-vars (org-get-local-variables)))
9173 (let (var val)
9174 (mapc
9175 (lambda (x)
9176 (when (string-match
9177 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9178 (symbol-name (car x)))
9179 (setq var (car x) val (nth 1 x))
9180 (push (list var `(quote ,(eval var))) org-fb-vars)
9181 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9182 org-local-vars)
9183 (org-set-local 'orgstruct-is-++ t))))
9185 (defvar orgstruct-is-++ nil
9186 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9187 (make-variable-buffer-local 'orgstruct-is-++)
9189 ;;;###autoload
9190 (defun turn-on-orgstruct++ ()
9191 "Unconditionally turn on `orgstruct++-mode'."
9192 (orgstruct++-mode 1))
9194 (defun orgstruct-error ()
9195 "Error when there is no default binding for a structure key."
9196 (interactive)
9197 (funcall (if (fboundp 'user-error)
9198 'user-error
9199 'error)
9200 "This key has no function outside structure elements"))
9202 (defun orgstruct-setup ()
9203 "Setup orgstruct keymap."
9204 (dolist (cell '((org-demote . t)
9205 (org-metaleft . t)
9206 (org-metaright . t)
9207 (org-promote . t)
9208 (org-shiftmetaleft . t)
9209 (org-shiftmetaright . t)
9210 org-backward-element
9211 org-backward-heading-same-level
9212 org-ctrl-c-ret
9213 org-ctrl-c-minus
9214 org-ctrl-c-star
9215 org-cycle
9216 org-forward-heading-same-level
9217 org-insert-heading
9218 org-insert-heading-respect-content
9219 org-kill-note-or-show-branches
9220 org-mark-subtree
9221 org-meta-return
9222 org-metadown
9223 org-metaup
9224 org-narrow-to-subtree
9225 org-promote-subtree
9226 org-reveal
9227 org-shiftdown
9228 org-shiftleft
9229 org-shiftmetadown
9230 org-shiftmetaup
9231 org-shiftright
9232 org-shifttab
9233 org-shifttab
9234 org-shiftup
9235 org-show-children
9236 org-show-subtree
9237 org-sort
9238 org-up-element
9239 outline-demote
9240 outline-next-visible-heading
9241 outline-previous-visible-heading
9242 outline-promote
9243 outline-up-heading))
9244 (let ((f (or (car-safe cell) cell))
9245 (disable-when-heading-prefix (cdr-safe cell)))
9246 (when (fboundp f)
9247 (let ((new-bindings))
9248 (dolist (binding (nconc (where-is-internal f org-mode-map)
9249 (where-is-internal f outline-mode-map)))
9250 (push binding new-bindings)
9251 ;; TODO use local-function-key-map
9252 (dolist (rep '(("<tab>" . "TAB")
9253 ("<return>" . "RET")
9254 ("<escape>" . "ESC")
9255 ("<delete>" . "DEL")))
9256 (setq binding (read-kbd-macro
9257 (let ((case-fold-search))
9258 (replace-regexp-in-string
9259 (regexp-quote (cdr rep))
9260 (car rep)
9261 (key-description binding)))))
9262 (pushnew binding new-bindings :test 'equal)))
9263 (dolist (binding new-bindings)
9264 (let ((key (lookup-key orgstruct-mode-map binding)))
9265 (when (or (not key) (numberp key))
9266 (ignore-errors
9267 (org-defkey orgstruct-mode-map
9268 binding
9269 (orgstruct-make-binding
9270 f binding disable-when-heading-prefix))))))))))
9271 (run-hooks 'orgstruct-setup-hook))
9273 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9274 "Create a function for binding in the structure minor mode.
9275 FUN is the command to call inside a table. KEY is the key that
9276 should be checked in for a command to execute outside of tables.
9277 Non-nil `disable-when-heading-prefix' means to disable the command
9278 if `orgstruct-heading-prefix-regexp' is not empty."
9279 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9280 (let ((nname name)
9281 (i 0))
9282 (while (fboundp (intern nname))
9283 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9284 (setq name (intern nname)))
9285 (eval
9286 (let ((bindings '((org-heading-regexp
9287 (concat "^"
9288 orgstruct-heading-prefix-regexp
9289 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9290 (org-outline-regexp
9291 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9292 (org-outline-regexp-bol
9293 (concat "^" org-outline-regexp))
9294 (outline-regexp org-outline-regexp)
9295 (outline-heading-end-regexp "\n")
9296 (outline-level 'org-outline-level)
9297 (outline-heading-alist))))
9298 `(defun ,name (arg)
9299 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9300 "Outside of structure, run the binding of `"
9301 (key-description key) "'."
9302 (when disable-when-heading-prefix
9303 (concat
9304 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9305 "back to the default binding due to limitations of Org's implementation of\n"
9306 "`" (symbol-name fun) "'.")))
9307 (interactive "p")
9308 (let* ((disable
9309 ,(and disable-when-heading-prefix
9310 '(not (string= orgstruct-heading-prefix-regexp ""))))
9311 (fallback
9312 (or disable
9313 (not
9314 (let* ,bindings
9315 (org-context-p 'headline 'item
9316 ,(when (memq fun
9317 '(org-insert-heading
9318 org-insert-heading-respect-content
9319 org-meta-return))
9320 '(when orgstruct-is-++
9321 'item-body))))))))
9322 (if fallback
9323 (let* ((orgstruct-mode)
9324 (binding
9325 (let ((key ,key))
9326 (catch 'exit
9327 (dolist
9328 (rep
9329 '(nil
9330 ("<\\([^>]*\\)tab>" . "\\1TAB")
9331 ("<\\([^>]*\\)return>" . "\\1RET")
9332 ("<\\([^>]*\\)escape>" . "\\1ESC")
9333 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9334 nil)
9335 (when rep
9336 (setq key (read-kbd-macro
9337 (let ((case-fold-search))
9338 (replace-regexp-in-string
9339 (car rep)
9340 (cdr rep)
9341 (key-description key))))))
9342 (when (key-binding key)
9343 (throw 'exit (key-binding key))))))))
9344 (if (keymapp binding)
9345 (org-set-transient-map binding)
9346 (let ((func (or binding
9347 (unless disable
9348 'orgstruct-error))))
9349 (when func
9350 (call-interactively func)))))
9351 (org-run-like-in-org-mode
9352 (lambda ()
9353 (interactive)
9354 (let* ,bindings
9355 (call-interactively ',fun)))))))))
9356 name))
9358 (defun org-contextualize-keys (alist contexts)
9359 "Return valid elements in ALIST depending on CONTEXTS.
9361 `org-agenda-custom-commands' or `org-capture-templates' are the
9362 values used for ALIST, and `org-agenda-custom-commands-contexts'
9363 or `org-capture-templates-contexts' are the associated contexts
9364 definitions."
9365 (let ((contexts
9366 ;; normalize contexts
9367 (mapcar
9368 (lambda(c) (cond ((listp (cadr c))
9369 (list (car c) (car c) (cadr c)))
9370 ((string= "" (cadr c))
9371 (list (car c) (car c) (caddr c)))
9372 (t c)))
9373 contexts))
9374 (a alist) r s)
9375 ;; loop over all commands or templates
9376 (dolist (c a)
9377 (let (vrules repl)
9378 (cond
9379 ((not (assoc (car c) contexts))
9380 (push c r))
9381 ((and (assoc (car c) contexts)
9382 (setq vrules (org-contextualize-validate-key
9383 (car c) contexts)))
9384 (mapc (lambda (vr)
9385 (when (not (equal (car vr) (cadr vr)))
9386 (setq repl vr)))
9387 vrules)
9388 (if (not repl) (push c r)
9389 (push (cadr repl) s)
9390 (push
9391 (cons (car c)
9392 (cdr (or (assoc (cadr repl) alist)
9393 (error "Undefined key `%s' as contextual replacement for `%s'"
9394 (cadr repl) (car c)))))
9395 r))))))
9396 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9397 (delq
9399 (delete-dups
9400 (mapcar (lambda (x)
9401 (let ((tpl (car x)))
9402 (when (not (delq
9404 (mapcar (lambda (y)
9405 (equal y tpl))
9406 s)))
9407 x)))
9408 (reverse r))))))
9410 (defun org-contextualize-validate-key (key contexts)
9411 "Check CONTEXTS for agenda or capture KEY."
9412 (let (rr res)
9413 (dolist (r contexts)
9414 (mapc
9415 (lambda (rr)
9416 (when
9417 (and (equal key (car r))
9418 (if (functionp rr) (funcall rr)
9419 (or (and (eq (car rr) 'in-file)
9420 (buffer-file-name)
9421 (string-match (cdr rr) (buffer-file-name)))
9422 (and (eq (car rr) 'in-mode)
9423 (string-match (cdr rr) (symbol-name major-mode)))
9424 (and (eq (car rr) 'in-buffer)
9425 (string-match (cdr rr) (buffer-name)))
9426 (when (and (eq (car rr) 'not-in-file)
9427 (buffer-file-name))
9428 (not (string-match (cdr rr) (buffer-file-name))))
9429 (when (eq (car rr) 'not-in-mode)
9430 (not (string-match (cdr rr) (symbol-name major-mode))))
9431 (when (eq (car rr) 'not-in-buffer)
9432 (not (string-match (cdr rr) (buffer-name)))))))
9433 (push r res)))
9434 (car (last r))))
9435 (delete-dups (delq nil res))))
9437 (defun org-context-p (&rest contexts)
9438 "Check if local context is any of CONTEXTS.
9439 Possible values in the list of contexts are `table', `headline', and `item'."
9440 (let ((pos (point)))
9441 (goto-char (point-at-bol))
9442 (prog1 (or (and (memq 'table contexts)
9443 (looking-at "[ \t]*|"))
9444 (and (memq 'headline contexts)
9445 (looking-at org-outline-regexp))
9446 (and (memq 'item contexts)
9447 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9448 (and (memq 'item-body contexts)
9449 (org-in-item-p)))
9450 (goto-char pos))))
9452 (defun org-get-local-variables ()
9453 "Return a list of all local variables in an Org mode buffer."
9454 (let (varlist)
9455 (with-current-buffer (get-buffer-create "*Org tmp*")
9456 (erase-buffer)
9457 (org-mode)
9458 (setq varlist (buffer-local-variables)))
9459 (kill-buffer "*Org tmp*")
9460 (delq nil
9461 (mapcar
9462 (lambda (x)
9463 (setq x
9464 (if (symbolp x)
9465 (list x)
9466 (list (car x) (cdr x))))
9467 (if (and (not (get (car x) 'org-state))
9468 (string-match
9469 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9470 (symbol-name (car x))))
9471 x nil))
9472 varlist))))
9474 (defun org-clone-local-variables (from-buffer &optional regexp)
9475 "Clone local variables from FROM-BUFFER.
9476 Optional argument REGEXP selects variables to clone."
9477 (mapc
9478 (lambda (pair)
9479 (and (symbolp (car pair))
9480 (or (null regexp)
9481 (string-match regexp (symbol-name (car pair))))
9482 (set (make-local-variable (car pair))
9483 (cdr pair))))
9484 (buffer-local-variables from-buffer)))
9486 ;;;###autoload
9487 (defun org-run-like-in-org-mode (cmd)
9488 "Run a command, pretending that the current buffer is in Org-mode.
9489 This will temporarily bind local variables that are typically bound in
9490 Org-mode to the values they have in Org-mode, and then interactively
9491 call CMD."
9492 (org-load-modules-maybe)
9493 (unless org-local-vars
9494 (setq org-local-vars (org-get-local-variables)))
9495 (let (binds)
9496 (dolist (var org-local-vars)
9497 (when (or (not (boundp (car var)))
9498 (eq (symbol-value (car var))
9499 (default-value (car var))))
9500 (push (list (car var) `(quote ,(cadr var))) binds)))
9501 (eval `(let ,binds
9502 (call-interactively (quote ,cmd))))))
9504 (defun org-get-category (&optional pos force-refresh)
9505 "Get the category applying to position POS."
9506 (save-match-data
9507 (if force-refresh (org-refresh-category-properties))
9508 (let ((pos (or pos (point))))
9509 (or (get-text-property pos 'org-category)
9510 (progn (org-refresh-category-properties)
9511 (get-text-property pos 'org-category))))))
9513 ;;; Refresh properties
9515 (defun org-refresh-properties (dprop tprop)
9516 "Refresh buffer text properties.
9517 DPROP is the drawer property and TPROP is either the
9518 corresponding text property to set, or an alist with each element
9519 being a text property (as a symbol) and a function to apply to
9520 the value of the drawer property."
9521 (let ((case-fold-search t)
9522 (inhibit-read-only t))
9523 (org-with-silent-modifications
9524 (save-excursion
9525 (save-restriction
9526 (widen)
9527 (goto-char (point-min))
9528 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9529 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9531 (defun org-refresh-property (tprop p)
9532 "Refresh the buffer text property TPROP from the drawer property P.
9533 The refresh happens only for the current tree (not subtree)."
9534 (unless (org-before-first-heading-p)
9535 (save-excursion
9536 (org-back-to-heading t)
9537 (if (symbolp tprop)
9538 ;; TPROP is a text property symbol
9539 (put-text-property
9540 (point) (or (outline-next-heading) (point-max)) tprop p)
9541 ;; TPROP is an alist with (properties . function) elements
9542 (dolist (al tprop)
9543 (save-excursion
9544 (put-text-property
9545 (line-beginning-position) (or (outline-next-heading) (point-max))
9546 (car al)
9547 (funcall (cdr al) p))))))))
9549 (defun org-refresh-category-properties ()
9550 "Refresh category text properties in the buffer."
9551 (let ((case-fold-search t)
9552 (inhibit-read-only t)
9553 (default-category
9554 (cond ((null org-category)
9555 (if buffer-file-name
9556 (file-name-sans-extension
9557 (file-name-nondirectory buffer-file-name))
9558 "???"))
9559 ((symbolp org-category) (symbol-name org-category))
9560 (t org-category))))
9561 (org-with-silent-modifications
9562 (org-with-wide-buffer
9563 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9564 ;; This is the default category for the buffer. If none is
9565 ;; found, fall-back to `org-category' or buffer file name.
9566 (put-text-property
9567 (point-min) (point-max)
9568 'org-category
9569 (catch 'buffer-category
9570 (goto-char (point-max))
9571 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9572 (let ((element (org-element-at-point)))
9573 (when (eq (org-element-type element) 'keyword)
9574 (throw 'buffer-category
9575 (org-element-property :value element)))))
9576 default-category))
9577 ;; Set sub-tree specific categories.
9578 (goto-char (point-min))
9579 (let ((regexp (org-re-property "CATEGORY")))
9580 (while (re-search-forward regexp nil t)
9581 (let ((value (org-match-string-no-properties 3)))
9582 (when (org-at-property-p)
9583 (put-text-property
9584 (save-excursion (org-back-to-heading t) (point))
9585 (save-excursion (org-end-of-subtree t t) (point))
9586 'org-category
9587 value)))))))))
9589 (defun org-refresh-stats-properties ()
9590 "Refresh stats text properties in the buffer."
9591 (let (stats)
9592 (org-with-silent-modifications
9593 (save-excursion
9594 (save-restriction
9595 (widen)
9596 (goto-char (point-min))
9597 (while (re-search-forward
9598 (concat org-outline-regexp-bol ".*"
9599 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9600 nil t)
9601 (setq stats (cond ((equal (match-string 3) "0") 0)
9602 ((match-string 2)
9603 (/ (* (string-to-number (match-string 2)) 100)
9604 (string-to-number (match-string 3))))
9605 (t (string-to-number (match-string 1)))))
9606 (org-back-to-heading t)
9607 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9608 'org-stats stats)))))))
9610 (defun org-refresh-effort-properties ()
9611 "Refresh effort properties"
9612 (org-refresh-properties
9613 org-effort-property
9614 '((effort . identity)
9615 (effort-minutes . org-duration-string-to-minutes))))
9617 ;;;; Link Stuff
9619 ;;; Link abbreviations
9621 (defun org-link-expand-abbrev (link)
9622 "Apply replacements as defined in `org-link-abbrev-alist'."
9623 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9624 (let* ((key (match-string 1 link))
9625 (as (or (assoc key org-link-abbrev-alist-local)
9626 (assoc key org-link-abbrev-alist)))
9627 (tag (and (match-end 2) (match-string 3 link)))
9628 rpl)
9629 (if (not as)
9630 link
9631 (setq rpl (cdr as))
9632 (cond
9633 ((symbolp rpl) (funcall rpl tag))
9634 ((string-match "%(\\([^)]+\\))" rpl)
9635 (replace-match
9636 (save-match-data
9637 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9638 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9639 ((string-match "%h" rpl)
9640 (replace-match (url-hexify-string (or tag "")) t t rpl))
9641 (t (concat rpl tag)))))
9642 link))
9644 ;;; Storing and inserting links
9646 (defvar org-insert-link-history nil
9647 "Minibuffer history for links inserted with `org-insert-link'.")
9649 (defvar org-stored-links nil
9650 "Contains the links stored with `org-store-link'.")
9652 (defvar org-store-link-plist nil
9653 "Plist with info about the most recently link created with `org-store-link'.")
9655 (defvar org-link-protocols nil
9656 "Link protocols added to Org-mode using `org-add-link-type'.")
9658 (defvar org-store-link-functions nil
9659 "List of functions that are called to create and store a link.
9660 Each function will be called in turn until one returns a non-nil
9661 value. Each function should check if it is responsible for creating
9662 this link (for example by looking at the major mode).
9663 If not, it must exit and return nil.
9664 If yes, it should return a non-nil value after a calling
9665 `org-store-link-props' with a list of properties and values.
9666 Special properties are:
9668 :type The link prefix, like \"http\". This must be given.
9669 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9670 This is obligatory as well.
9671 :description Optional default description for the second pair
9672 of brackets in an Org-mode link. The user can still change
9673 this when inserting this link into an Org-mode buffer.
9675 In addition to these, any additional properties can be specified
9676 and then used in capture templates.")
9678 (defun org-add-link-type (type &optional follow export)
9679 "Add TYPE to the list of `org-link-types'.
9680 Re-compute all regular expressions depending on `org-link-types'
9682 FOLLOW and EXPORT are two functions.
9684 FOLLOW should take the link path as the single argument and do whatever
9685 is necessary to follow the link, for example find a file or display
9686 a mail message.
9688 EXPORT should format the link path for export to one of the export formats.
9689 It should be a function accepting three arguments:
9691 path the path of the link, the text after the prefix (like \"http:\")
9692 desc the description of the link, if any
9693 format the export format, a symbol like `html' or `latex' or `ascii'.
9695 The function may use the FORMAT information to return different values
9696 depending on the format. The return value will be put literally into
9697 the exported file. If the return value is nil, this means Org should
9698 do what it normally does with links which do not have EXPORT defined.
9700 Org mode has a built-in default for exporting links. If you are happy with
9701 this default, there is no need to define an export function for the link
9702 type. For a simple example of an export function, see `org-bbdb.el'."
9703 (add-to-list 'org-link-types type t)
9704 (org-make-link-regexps)
9705 (org-element-update-syntax)
9706 (if (assoc type org-link-protocols)
9707 (setcdr (assoc type org-link-protocols) (list follow export))
9708 (push (list type follow export) org-link-protocols)))
9710 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9711 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9713 ;;;###autoload
9714 (defun org-store-link (arg)
9715 "\\<org-mode-map>Store an org-link to the current location.
9716 This link is added to `org-stored-links' and can later be inserted
9717 into an Org buffer with \\[org-insert-link].
9719 For some link types, a prefix ARG is interpreted.
9720 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9721 For file links, ARG negates `org-context-in-file-links'.
9723 A double prefix ARG force skipping storing functions that are not
9724 part of Org's core.
9726 A triple prefix ARG force storing a link for each line in the
9727 active region."
9728 (interactive "P")
9729 (org-load-modules-maybe)
9730 (if (and (equal arg '(64)) (org-region-active-p))
9731 (save-excursion
9732 (let ((end (region-end)))
9733 (goto-char (region-beginning))
9734 (set-mark (point))
9735 (while (< (point-at-eol) end)
9736 (move-end-of-line 1) (activate-mark)
9737 (let (current-prefix-arg)
9738 (call-interactively 'org-store-link))
9739 (move-beginning-of-line 2)
9740 (set-mark (point)))))
9741 (org-with-limited-levels
9742 (setq org-store-link-plist nil)
9743 (let (link cpltxt desc description search
9744 txt custom-id agenda-link sfuns sfunsn)
9745 (cond
9747 ;; Store a link using an external link type
9748 ((and (not (equal arg '(16)))
9749 (setq sfuns
9750 (delq
9751 nil (mapcar (lambda (f)
9752 (let (fs) (if (funcall f) (push f fs))))
9753 org-store-link-functions))
9754 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9755 (or (and (cdr sfuns)
9756 (funcall (intern
9757 (completing-read
9758 "Which function for creating the link? "
9759 sfunsn nil t (car sfunsn)))))
9760 (funcall (caar sfuns)))
9761 (setq link (plist-get org-store-link-plist :link)
9762 desc (or (plist-get org-store-link-plist
9763 :description)
9764 link))))
9766 ;; Store a link from a source code buffer.
9767 ((org-src-edit-buffer-p)
9768 (cond
9769 ((save-excursion
9770 (beginning-of-line)
9771 (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
9772 "[ \t]*$")))
9773 (setq link (format "(%s)" (org-match-string-no-properties 1))))
9774 ((org-called-interactively-p 'any)
9775 (let (label)
9776 (while (or (not label)
9777 (org-with-wide-buffer
9778 (goto-char (point-min))
9779 (re-search-forward
9780 (regexp-quote (format org-coderef-label-format label))
9781 nil t)))
9782 (when label (message "Label exists already") (sit-for 2))
9783 (setq label (read-string "Code line label: " label)))
9784 (end-of-line)
9785 (setq link (format org-coderef-label-format label))
9786 (let ((gc (- 79 (length link))))
9787 (if (< (current-column) gc) (org-move-to-column gc t)
9788 (insert " ")))
9789 (insert link)
9790 (setq link (concat "(" label ")") desc nil)))
9791 (t (setq link nil))))
9793 ;; We are in the agenda, link to referenced location
9794 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9795 (let ((m (or (get-text-property (point) 'org-hd-marker)
9796 (get-text-property (point) 'org-marker))))
9797 (when m
9798 (org-with-point-at m
9799 (setq agenda-link
9800 (if (org-called-interactively-p 'any)
9801 (call-interactively 'org-store-link)
9802 (org-store-link nil)))))))
9804 ((eq major-mode 'calendar-mode)
9805 (let ((cd (calendar-cursor-to-date)))
9806 (setq link
9807 (format-time-string
9808 (car org-time-stamp-formats)
9809 (apply 'encode-time
9810 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9811 nil nil nil))))
9812 (org-store-link-props :type "calendar" :date cd)))
9814 ((eq major-mode 'help-mode)
9815 (setq link (concat "help:" (save-excursion
9816 (goto-char (point-min))
9817 (looking-at "^[^ ]+")
9818 (match-string 0))))
9819 (org-store-link-props :type "help"))
9821 ((eq major-mode 'w3-mode)
9822 (setq cpltxt (if (and (buffer-name)
9823 (not (string-match "Untitled" (buffer-name))))
9824 (buffer-name)
9825 (url-view-url t))
9826 link (url-view-url t))
9827 (org-store-link-props :type "w3" :url (url-view-url t)))
9829 ((eq major-mode 'image-mode)
9830 (setq cpltxt (concat "file:"
9831 (abbreviate-file-name buffer-file-name))
9832 link cpltxt)
9833 (org-store-link-props :type "image" :file buffer-file-name))
9835 ;; In dired, store a link to the file of the current line
9836 ((derived-mode-p 'dired-mode)
9837 (let ((file (dired-get-filename nil t)))
9838 (setq file (if file
9839 (abbreviate-file-name
9840 (expand-file-name (dired-get-filename nil t)))
9841 ;; otherwise, no file so use current directory.
9842 default-directory))
9843 (setq cpltxt (concat "file:" file)
9844 link cpltxt)))
9846 ((setq search (run-hook-with-args-until-success
9847 'org-create-file-search-functions))
9848 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9849 "::" search))
9850 (setq cpltxt (or description link)))
9852 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9853 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9854 (cond
9855 ;; Store a link using the target at point
9856 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9857 (setq cpltxt
9858 (concat "file:"
9859 (abbreviate-file-name
9860 (buffer-file-name (buffer-base-buffer)))
9861 "::" (match-string 1))
9862 link cpltxt))
9863 ((and (featurep 'org-id)
9864 (or (eq org-id-link-to-org-use-id t)
9865 (and (org-called-interactively-p 'any)
9866 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9867 (and (eq org-id-link-to-org-use-id
9868 'create-if-interactive-and-no-custom-id)
9869 (not custom-id))))
9870 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9871 ;; Store a link using the ID at point
9872 (setq link (condition-case nil
9873 (prog1 (org-id-store-link)
9874 (setq desc (or (plist-get org-store-link-plist
9875 :description)
9876 "")))
9877 (error
9878 ;; Probably before first headline, link only to file
9879 (concat "file:"
9880 (abbreviate-file-name
9881 (buffer-file-name (buffer-base-buffer))))))))
9883 ;; Just link to current headline
9884 (setq cpltxt (concat "file:"
9885 (abbreviate-file-name
9886 (buffer-file-name (buffer-base-buffer)))))
9887 ;; Add a context search string
9888 (when (org-xor org-context-in-file-links arg)
9889 (let* ((ee (org-element-at-point))
9890 (et (org-element-type ee))
9891 (ev (plist-get (cadr ee) :value))
9892 (ek (plist-get (cadr ee) :key))
9893 (eok (and (stringp ek) (string-match "name" ek))))
9894 (setq txt (cond
9895 ((org-at-heading-p) nil)
9896 ((and (eq et 'keyword) eok) ev)
9897 ((org-region-active-p)
9898 (buffer-substring (region-beginning) (region-end)))))
9899 (when (or (null txt) (string-match "\\S-" txt))
9900 (setq cpltxt
9901 (concat cpltxt "::"
9902 (condition-case nil
9903 (org-make-org-heading-search-string txt)
9904 (error "")))
9905 desc (or (and (eq et 'keyword) eok ev)
9906 (nth 4 (ignore-errors (org-heading-components)))
9907 "NONE")))))
9908 (if (string-match "::\\'" cpltxt)
9909 (setq cpltxt (substring cpltxt 0 -2)))
9910 (setq link cpltxt))))
9912 ((buffer-file-name (buffer-base-buffer))
9913 ;; Just link to this file here.
9914 (setq cpltxt (concat "file:"
9915 (abbreviate-file-name
9916 (buffer-file-name (buffer-base-buffer)))))
9917 ;; Add a context string.
9918 (when (org-xor org-context-in-file-links arg)
9919 (setq txt (if (org-region-active-p)
9920 (buffer-substring (region-beginning) (region-end))
9921 (buffer-substring (point-at-bol) (point-at-eol))))
9922 ;; Only use search option if there is some text.
9923 (when (string-match "\\S-" txt)
9924 (setq cpltxt
9925 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9926 desc "NONE")))
9927 (setq link cpltxt))
9929 ((org-called-interactively-p 'interactive)
9930 (user-error "No method for storing a link from this buffer"))
9932 (t (setq link nil)))
9934 ;; We're done setting link and desc, clean up
9935 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9936 (setq link (or link cpltxt)
9937 desc (or desc cpltxt))
9938 (cond ((equal desc "NONE") (setq desc nil))
9939 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9940 (let ((d0 (match-string 3 desc))
9941 (p0 (match-string 5 desc)))
9942 (setq desc
9943 (replace-regexp-in-string
9944 org-bracket-link-regexp
9945 (concat (or p0 d0)
9946 (if (equal (length (match-string 0 desc))
9947 (length desc)) "*" "")) desc)))))
9949 ;; Return the link
9950 (if (not (and (or (org-called-interactively-p 'any)
9951 executing-kbd-macro)
9952 link))
9953 (or agenda-link (and link (org-make-link-string link desc)))
9954 (push (list link desc) org-stored-links)
9955 (message "Stored: %s" (or desc link))
9956 (when custom-id
9957 (setq link (concat "file:" (abbreviate-file-name
9958 (buffer-file-name)) "::#" custom-id))
9959 (push (list link desc) org-stored-links))
9960 (car org-stored-links))))))
9962 (defun org-store-link-props (&rest plist)
9963 "Store link properties, extract names and addresses."
9964 (let (x adr)
9965 (when (setq x (plist-get plist :from))
9966 (setq adr (mail-extract-address-components x))
9967 (setq plist (plist-put plist :fromname (car adr)))
9968 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9969 (when (setq x (plist-get plist :to))
9970 (setq adr (mail-extract-address-components x))
9971 (setq plist (plist-put plist :toname (car adr)))
9972 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9973 (let ((from (plist-get plist :from))
9974 (to (plist-get plist :to)))
9975 (when (and from to org-from-is-user-regexp)
9976 (setq plist
9977 (plist-put plist :fromto
9978 (if (string-match org-from-is-user-regexp from)
9979 (concat "to %t")
9980 (concat "from %f"))))))
9981 (setq org-store-link-plist plist))
9983 (defun org-add-link-props (&rest plist)
9984 "Add these properties to the link property list."
9985 (let (key value)
9986 (while plist
9987 (setq key (pop plist) value (pop plist))
9988 (setq org-store-link-plist
9989 (plist-put org-store-link-plist key value)))))
9991 (defun org-email-link-description (&optional fmt)
9992 "Return the description part of an email link.
9993 This takes information from `org-store-link-plist' and formats it
9994 according to FMT (default from `org-email-link-description-format')."
9995 (setq fmt (or fmt org-email-link-description-format))
9996 (let* ((p org-store-link-plist)
9997 (to (plist-get p :toaddress))
9998 (from (plist-get p :fromaddress))
9999 (table
10000 (list
10001 (cons "%c" (plist-get p :fromto))
10002 (cons "%F" (plist-get p :from))
10003 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10004 (cons "%T" (plist-get p :to))
10005 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10006 (cons "%s" (plist-get p :subject))
10007 (cons "%d" (plist-get p :date))
10008 (cons "%m" (plist-get p :message-id)))))
10009 (when (string-match "%c" fmt)
10010 ;; Check if the user wrote this message
10011 (if (and org-from-is-user-regexp from to
10012 (save-match-data (string-match org-from-is-user-regexp from)))
10013 (setq fmt (replace-match "to %t" t t fmt))
10014 (setq fmt (replace-match "from %f" t t fmt))))
10015 (org-replace-escapes fmt table)))
10017 (defun org-make-org-heading-search-string (&optional string)
10018 "Make search string for the current headline or STRING."
10019 (let ((s (or string
10020 (and (derived-mode-p 'org-mode)
10021 (save-excursion
10022 (org-back-to-heading t)
10023 (org-element-property :raw-value (org-element-at-point))))))
10024 (lines org-context-in-file-links))
10025 (or string (setq s (concat "*" s))) ; Add * for headlines
10026 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10027 (when (and string (integerp lines) (> lines 0))
10028 (let ((slines (org-split-string s "\n")))
10029 (when (< lines (length slines))
10030 (setq s (mapconcat
10031 'identity
10032 (reverse (nthcdr (- (length slines) lines)
10033 (reverse slines))) "\n")))))
10034 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10036 (defun org-make-link-string (link &optional description)
10037 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10038 (unless (org-string-nw-p link) (error "Empty link"))
10039 (let ((uri (cond ((string-match org-link-types-re link)
10040 (concat (match-string 1 link)
10041 (org-link-escape (substring link (match-end 1)))))
10042 ;; For readability, url-encode internal links only
10043 ;; when absolutely needed (i.e, when they contain
10044 ;; square brackets). File links however, are
10045 ;; encoded since, e.g., spaces are significant.
10046 ((or (file-name-absolute-p link)
10047 (org-string-match-p "\\`\\.\\.?/\\|[][]" link))
10048 (org-link-escape link))
10049 (t link)))
10050 (description
10051 (and (org-string-nw-p description)
10052 ;; Remove brackets from description, as they are fatal.
10053 (replace-regexp-in-string
10054 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10055 (org-trim description)))))
10056 (format "[[%s]%s]"
10058 (if description (format "[%s]" description) ""))))
10060 (defconst org-link-escape-chars
10061 ;;%20 %5B %5D %25
10062 '(?\s ?\[ ?\] ?%)
10063 "List of characters that should be escaped in a link when stored to Org.
10064 This is the list that is used for internal purposes.")
10066 (defconst org-link-escape-chars-browser
10067 ;;%20 %22
10068 '(?\s ?\")
10069 "List of characters to be escaped before handing over to the browser.
10070 If you consider using this constant then you probably want to use
10071 the function `org-link-escape-browser' instead. See there why
10072 this constant is a candidate to be removed once Org drops support
10073 for Emacs 24.1 and 24.2.")
10075 (defun org-link-escape (text &optional table merge)
10076 "Return percent escaped representation of TEXT.
10077 TEXT is a string with the text to escape.
10078 Optional argument TABLE is a list with characters that should be
10079 escaped. When nil, `org-link-escape-chars' is used.
10080 If optional argument MERGE is set, merge TABLE into
10081 `org-link-escape-chars'."
10082 (let ((characters-to-encode
10083 (cond ((null table) org-link-escape-chars)
10084 (merge (append org-link-escape-chars table))
10085 (t table))))
10086 (mapconcat
10087 (lambda (c)
10088 (if (or (memq c characters-to-encode)
10089 (and org-url-hexify-p (or (< c 32) (> c 126))))
10090 (mapconcat (lambda (e) (format "%%%.2X" e))
10091 (or (encode-coding-char c 'utf-8)
10092 (error "Unable to percent escape character: %c" c))
10094 (char-to-string c)))
10095 text "")))
10097 (defun org-link-escape-browser (text)
10098 "Escape some characters before handing over to the browser.
10099 This function is a candidate to be removed together with the
10100 constant `org-link-escape-chars-browser' once Org drops support
10101 for Emacs 24.1 and 24.2. All calls to this function will have to
10102 be replaced with `url-encode-url' which is available since Emacs
10103 24.3.1."
10104 ;; Example with the Org link
10105 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10106 ;; to open the browser with +subject:"Release 8.2" filled into the
10107 ;; query field: In this case the variable TEXT contains the
10108 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10109 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10110 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10111 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10112 (if (fboundp 'url-encode-url)
10113 (url-encode-url text)
10114 (if (org-string-match-p
10115 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10116 text)
10117 (org-link-escape text org-link-escape-chars-browser)
10118 text)))
10120 (defun org-link-unescape (str)
10121 "Unhex hexified Unicode parts in string STR.
10122 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10123 reciprocal of `org-link-escape', which see."
10124 (if (org-string-nw-p str)
10125 (replace-regexp-in-string
10126 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10127 str))
10129 (defun org-link-unescape-compound (hex)
10130 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10131 Note: this function also decodes single byte encodings like
10132 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10133 (save-match-data
10134 (let* ((bytes (cdr (split-string hex "%")))
10135 (ret "")
10136 (eat 0)
10137 (sum 0))
10138 (while bytes
10139 (let* ((val (string-to-number (pop bytes) 16))
10140 (shift-xor
10141 (if (= 0 eat)
10142 (cond
10143 ((>= val 252) (cons 6 252))
10144 ((>= val 248) (cons 5 248))
10145 ((>= val 240) (cons 4 240))
10146 ((>= val 224) (cons 3 224))
10147 ((>= val 192) (cons 2 192))
10148 (t (cons 0 0)))
10149 (cons 6 128))))
10150 (if (>= val 192) (setq eat (car shift-xor)))
10151 (setq val (logxor val (cdr shift-xor)))
10152 (setq sum (+ (lsh sum (car shift-xor)) val))
10153 (if (> eat 0) (setq eat (- eat 1)))
10154 (cond
10155 ((= 0 eat) ;multi byte
10156 (setq ret (concat ret (org-char-to-string sum)))
10157 (setq sum 0))
10158 ((not bytes) ; single byte(s)
10159 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10160 ret)))
10162 (defun org-link-unescape-single-byte-sequence (hex)
10163 "Unhexify hex-encoded single byte character sequences."
10164 (mapconcat (lambda (byte)
10165 (char-to-string (string-to-number byte 16)))
10166 (cdr (split-string hex "%")) ""))
10168 (defun org-xor (a b)
10169 "Exclusive or."
10170 (if a (not b) b))
10172 (defun org-fixup-message-id-for-http (s)
10173 "Replace special characters in a message id, so it can be used in an http query."
10174 (when (string-match "%" s)
10175 (setq s (mapconcat (lambda (c)
10176 (if (eq c ?%)
10177 "%25"
10178 (char-to-string c)))
10179 s "")))
10180 (while (string-match "<" s)
10181 (setq s (replace-match "%3C" t t s)))
10182 (while (string-match ">" s)
10183 (setq s (replace-match "%3E" t t s)))
10184 (while (string-match "@" s)
10185 (setq s (replace-match "%40" t t s)))
10188 (defun org-link-prettify (link)
10189 "Return a human-readable representation of LINK.
10190 The car of LINK must be a raw link.
10191 The cdr of LINK must be either a link description or nil."
10192 (let ((desc (or (cadr link) "<no description>")))
10193 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10194 "<" (car link) ">")))
10196 ;;;###autoload
10197 (defun org-insert-link-global ()
10198 "Insert a link like Org-mode does.
10199 This command can be called in any mode to insert a link in Org-mode syntax."
10200 (interactive)
10201 (org-load-modules-maybe)
10202 (org-run-like-in-org-mode 'org-insert-link))
10204 (defun org-insert-all-links (arg &optional pre post)
10205 "Insert all links in `org-stored-links'.
10206 When a universal prefix, do not delete the links from `org-stored-links'.
10207 When `ARG' is a number, insert the last N link(s).
10208 `PRE' and `POST' are optional arguments to define a string to
10209 prepend or to append."
10210 (interactive "P")
10211 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10212 (links (copy-seq org-stored-links))
10213 (pr (or pre "- "))
10214 (po (or post "\n"))
10215 (cnt 1) l)
10216 (if (null org-stored-links)
10217 (message "No link to insert")
10218 (while (and (or (listp arg) (>= arg cnt))
10219 (setq l (if (listp arg)
10220 (pop links)
10221 (pop org-stored-links))))
10222 (setq cnt (1+ cnt))
10223 (insert pr)
10224 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10225 (insert po)))))
10227 (defun org-insert-last-stored-link (arg)
10228 "Insert the last link stored in `org-stored-links'."
10229 (interactive "p")
10230 (org-insert-all-links arg "" "\n"))
10232 (defun org-link-fontify-links-to-this-file ()
10233 "Fontify links to the current file in `org-stored-links'."
10234 (let ((f (buffer-file-name)) a b)
10235 (setq a (mapcar (lambda(l)
10236 (let ((ll (car l)))
10237 (when (and (string-match "^file:\\(.+\\)::" ll)
10238 (equal f (expand-file-name (match-string 1 ll))))
10239 ll)))
10240 org-stored-links))
10241 (when (featurep 'org-id)
10242 (setq b (mapcar (lambda(l)
10243 (let ((ll (car l)))
10244 (when (and (string-match "^id:\\(.+\\)$" ll)
10245 (equal f (expand-file-name
10246 (or (org-id-find-id-file
10247 (match-string 1 ll)) ""))))
10248 ll)))
10249 org-stored-links)))
10250 (mapcar (lambda(l)
10251 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10252 (delq nil (append a b)))))
10254 (defvar org-link-links-in-this-file nil)
10255 (defun org-insert-link (&optional complete-file link-location default-description)
10256 "Insert a link. At the prompt, enter the link.
10258 Completion can be used to insert any of the link protocol prefixes like
10259 http or ftp in use.
10261 The history can be used to select a link previously stored with
10262 `org-store-link'. When the empty string is entered (i.e. if you just
10263 press RET at the prompt), the link defaults to the most recently
10264 stored link. As SPC triggers completion in the minibuffer, you need to
10265 use M-SPC or C-q SPC to force the insertion of a space character.
10267 You will also be prompted for a description, and if one is given, it will
10268 be displayed in the buffer instead of the link.
10270 If there is already a link at point, this command will allow you to edit link
10271 and description parts.
10273 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10274 be selected using completion. The path to the file will be relative to the
10275 current directory if the file is in the current directory or a subdirectory.
10276 Otherwise, the link will be the absolute path as completed in the minibuffer
10277 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10278 option `org-link-file-path-type'.
10280 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10281 the current directory or below.
10283 With three \\[universal-argument] prefixes, negate the meaning of
10284 `org-keep-stored-link-after-insertion'.
10286 If `org-make-link-description-function' is non-nil, this function will be
10287 called with the link target, and the result will be the default
10288 link description.
10290 If the LINK-LOCATION parameter is non-nil, this value will be
10291 used as the link location instead of reading one interactively.
10293 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10294 be used as the default description."
10295 (interactive "P")
10296 (let* ((wcf (current-window-configuration))
10297 (origbuf (current-buffer))
10298 (region (if (org-region-active-p)
10299 (buffer-substring (region-beginning) (region-end))))
10300 (remove (and region (list (region-beginning) (region-end))))
10301 (desc region)
10302 tmphist ; byte-compile incorrectly complains about this
10303 (link link-location)
10304 (abbrevs org-link-abbrev-alist-local)
10305 entry file all-prefixes auto-desc)
10306 (cond
10307 (link-location) ; specified by arg, just use it.
10308 ((org-in-regexp org-bracket-link-regexp 1)
10309 ;; We do have a link at point, and we are going to edit it.
10310 (setq remove (list (match-beginning 0) (match-end 0)))
10311 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10312 (setq link (read-string "Link: "
10313 (org-link-unescape
10314 (org-match-string-no-properties 1)))))
10315 ((or (org-in-regexp org-angle-link-re)
10316 (org-in-regexp org-plain-link-re))
10317 ;; Convert to bracket link
10318 (setq remove (list (match-beginning 0) (match-end 0))
10319 link (read-string "Link: "
10320 (org-remove-angle-brackets (match-string 0)))))
10321 ((member complete-file '((4) (16)))
10322 ;; Completing read for file names.
10323 (setq link (org-file-complete-link complete-file)))
10325 ;; Read link, with completion for stored links.
10326 (org-link-fontify-links-to-this-file)
10327 (org-switch-to-buffer-other-window "*Org Links*")
10328 (with-current-buffer "*Org Links*"
10329 (erase-buffer)
10330 (insert "Insert a link.
10331 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10332 (when org-stored-links
10333 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10334 (insert (mapconcat 'org-link-prettify
10335 (reverse org-stored-links) "\n")))
10336 (goto-char (point-min)))
10337 (let ((cw (selected-window)))
10338 (select-window (get-buffer-window "*Org Links*" 'visible))
10339 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10340 (unless (pos-visible-in-window-p (point-max))
10341 (org-fit-window-to-buffer))
10342 (and (window-live-p cw) (select-window cw)))
10343 ;; Fake a link history, containing the stored links.
10344 (setq tmphist (append (mapcar 'car org-stored-links)
10345 org-insert-link-history))
10346 (setq all-prefixes (append (mapcar 'car abbrevs)
10347 (mapcar 'car org-link-abbrev-alist)
10348 org-link-types))
10349 (unwind-protect
10350 (progn
10351 (setq link
10352 (org-completing-read
10353 "Link: "
10354 (append
10355 (mapcar (lambda (x) (concat x ":"))
10356 all-prefixes)
10357 (mapcar 'car org-stored-links))
10358 nil nil nil
10359 'tmphist
10360 (caar org-stored-links)))
10361 (if (not (string-match "\\S-" link))
10362 (user-error "No link selected"))
10363 (mapc (lambda(l)
10364 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10365 org-stored-links)
10366 (if (or (member link all-prefixes)
10367 (and (equal ":" (substring link -1))
10368 (member (substring link 0 -1) all-prefixes)
10369 (setq link (substring link 0 -1))))
10370 (setq link (with-current-buffer origbuf
10371 (org-link-try-special-completion link)))))
10372 (set-window-configuration wcf)
10373 (kill-buffer "*Org Links*"))
10374 (setq entry (assoc link org-stored-links))
10375 (or entry (push link org-insert-link-history))
10376 (setq desc (or desc (nth 1 entry)))))
10378 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10379 (not org-keep-stored-link-after-insertion))
10380 (setq org-stored-links (delq (assoc link org-stored-links)
10381 org-stored-links)))
10383 (if (and (string-match org-plain-link-re link)
10384 (not (string-match org-ts-regexp link)))
10385 ;; URL-like link, normalize the use of angular brackets.
10386 (setq link (org-remove-angle-brackets link)))
10388 ;; Check if we are linking to the current file with a search
10389 ;; option If yes, simplify the link by using only the search
10390 ;; option.
10391 (when (and buffer-file-name
10392 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10393 (let* ((path (match-string 1 link))
10394 (case-fold-search nil)
10395 (search (match-string 2 link)))
10396 (save-match-data
10397 (if (equal (file-truename buffer-file-name) (file-truename path))
10398 ;; We are linking to this same file, with a search option
10399 (setq link search)))))
10401 ;; Check if we can/should use a relative path. If yes, simplify the link
10402 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10403 (let* ((type (match-string 1 link))
10404 (path (match-string 2 link))
10405 (origpath path)
10406 (case-fold-search nil))
10407 (cond
10408 ((or (eq org-link-file-path-type 'absolute)
10409 (equal complete-file '(16)))
10410 (setq path (abbreviate-file-name (expand-file-name path))))
10411 ((eq org-link-file-path-type 'noabbrev)
10412 (setq path (expand-file-name path)))
10413 ((eq org-link-file-path-type 'relative)
10414 (setq path (file-relative-name path)))
10416 (save-match-data
10417 (if (string-match (concat "^" (regexp-quote
10418 (expand-file-name
10419 (file-name-as-directory
10420 default-directory))))
10421 (expand-file-name path))
10422 ;; We are linking a file with relative path name.
10423 (setq path (substring (expand-file-name path)
10424 (match-end 0)))
10425 (setq path (abbreviate-file-name (expand-file-name path)))))))
10426 (setq link (concat type path))
10427 (if (equal desc origpath)
10428 (setq desc path))))
10430 (if org-make-link-description-function
10431 (setq desc
10432 (or (condition-case nil
10433 (funcall org-make-link-description-function link desc)
10434 (error (progn (message "Can't get link description from `%s'"
10435 (symbol-name org-make-link-description-function))
10436 (sit-for 2) nil)))
10437 (read-string "Description: " default-description)))
10438 (if default-description (setq desc default-description)
10439 (setq desc (or (and auto-desc desc)
10440 (read-string "Description: " desc)))))
10442 (unless (string-match "\\S-" desc) (setq desc nil))
10443 (if remove (apply 'delete-region remove))
10444 (insert (org-make-link-string link desc))))
10446 (defun org-link-try-special-completion (type)
10447 "If there is completion support for link type TYPE, offer it."
10448 (let ((fun (intern (concat "org-" type "-complete-link"))))
10449 (if (functionp fun)
10450 (funcall fun)
10451 (read-string "Link (no completion support): " (concat type ":")))))
10453 (defun org-file-complete-link (&optional arg)
10454 "Create a file link using completion."
10455 (let ((file (org-iread-file-name "File: "))
10456 (pwd (file-name-as-directory (expand-file-name ".")))
10457 (pwd1 (file-name-as-directory (abbreviate-file-name
10458 (expand-file-name ".")))))
10459 (cond ((equal arg '(16))
10460 (concat "file:"
10461 (abbreviate-file-name (expand-file-name file))))
10462 ((string-match
10463 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10464 (concat "file:" (match-string 1 file)))
10465 ((string-match
10466 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10467 (expand-file-name file))
10468 (concat "file:"
10469 (match-string 1 (expand-file-name file))))
10470 (t (concat "file:" file)))))
10472 (defun org-iread-file-name (&rest args)
10473 "Read-file-name using `ido-mode' speedup if available.
10474 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10475 See `read-file-name' for a description of parameters."
10476 (org-without-partial-completion
10477 (if (and org-completion-use-ido
10478 (fboundp 'ido-read-file-name)
10479 (org-bound-and-true-p ido-mode)
10480 (listp (nth 1 args)))
10481 (let ((ido-enter-matching-directory nil))
10482 (apply #'ido-read-file-name args))
10483 (apply #'read-file-name args))))
10485 (defun org-completing-read (&rest args)
10486 "Completing-read with SPACE being a normal character."
10487 (let ((enable-recursive-minibuffers t)
10488 (minibuffer-local-completion-map
10489 (copy-keymap minibuffer-local-completion-map)))
10490 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10491 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10492 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10493 (apply 'org-icompleting-read args)))
10495 (defun org-completing-read-no-i (&rest args)
10496 (let (org-completion-use-ido org-completion-use-iswitchb)
10497 (apply 'org-completing-read args)))
10499 (defun org-iswitchb-completing-read (prompt choices &rest args)
10500 "Use iswitch as a completing-read replacement to choose from choices.
10501 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10502 from."
10503 (let* ((iswitchb-use-virtual-buffers nil)
10504 (iswitchb-make-buflist-hook
10505 (lambda ()
10506 (setq iswitchb-temp-buflist choices))))
10507 (iswitchb-read-buffer prompt)))
10509 (defun org-icompleting-read (&rest args)
10510 "Completing-read using `ido-mode' or `iswitchb' speedups if available.
10511 Should be called like `completing-read'."
10512 (org-without-partial-completion
10513 (if (not (listp (nth 1 args)))
10514 ;; Ido only supports lists as the COLLECTION argument. Use
10515 ;; default completion function when second argument is not
10516 ;; a list.
10517 (apply #'completing-read args)
10518 (let ((ido-enter-matching-directory nil))
10519 (apply (cond ((and org-completion-use-ido
10520 (fboundp 'ido-completing-read)
10521 (org-bound-and-true-p ido-mode))
10522 #'ido-completing-read)
10523 ((and org-completion-use-iswitchb
10524 (org-bound-and-true-p iswitchb-mode))
10525 #'org-iswitchb-completing-read)
10526 (t #'completing-read))
10527 args)))))
10529 ;;; Opening/following a link
10531 (defvar org-link-search-failed nil)
10533 (defvar org-open-link-functions nil
10534 "Hook for functions finding a plain text link.
10535 These functions must take a single argument, the link content.
10536 They will be called for links that look like [[link text][description]]
10537 when LINK TEXT does not have a protocol like \"http:\" and does not look
10538 like a filename (e.g. \"./blue.png\").
10540 These functions will be called *before* Org attempts to resolve the
10541 link by doing text searches in the current buffer - so if you want a
10542 link \"[[target]]\" to still find \"<<target>>\", your function should
10543 handle this as a special case.
10545 When the function does handle the link, it must return a non-nil value.
10546 If it decides that it is not responsible for this link, it must return
10547 nil to indicate that that Org-mode can continue with other options
10548 like exact and fuzzy text search.")
10550 (defun org-next-link (&optional search-backward)
10551 "Move forward to the next link.
10552 If the link is in hidden text, expose it."
10553 (interactive "P")
10554 (when (and org-link-search-failed (eq this-command last-command))
10555 (goto-char (point-min))
10556 (message "Link search wrapped back to beginning of buffer"))
10557 (setq org-link-search-failed nil)
10558 (let* ((pos (point))
10559 (ct (org-context))
10560 (a (assoc :link ct))
10561 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10562 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10563 ((looking-at org-any-link-re)
10564 ;; Don't stay stuck at link without an org-link face
10565 (forward-char (if search-backward -1 1))))
10566 (if (funcall srch-fun org-any-link-re nil t)
10567 (progn
10568 (goto-char (match-beginning 0))
10569 (if (outline-invisible-p) (org-show-context)))
10570 (goto-char pos)
10571 (setq org-link-search-failed t)
10572 (message "No further link found"))))
10574 (defun org-previous-link ()
10575 "Move backward to the previous link.
10576 If the link is in hidden text, expose it."
10577 (interactive)
10578 (funcall 'org-next-link t))
10580 (defun org-translate-link (s)
10581 "Translate a link string if a translation function has been defined."
10582 (with-temp-buffer
10583 (insert (org-trim s))
10584 (org-trim (org-element-interpret-data (org-element-context)))))
10586 (defun org-translate-link-from-planner (type path)
10587 "Translate a link from Emacs Planner syntax so that Org can follow it.
10588 This is still an experimental function, your mileage may vary."
10589 (cond
10590 ((member type '("http" "https" "news" "ftp"))
10591 ;; standard Internet links are the same.
10592 nil)
10593 ((and (equal type "irc") (string-match "^//" path))
10594 ;; Planner has two / at the beginning of an irc link, we have 1.
10595 ;; We should have zero, actually....
10596 (setq path (substring path 1)))
10597 ((and (equal type "lisp") (string-match "^/" path))
10598 ;; Planner has a slash, we do not.
10599 (setq type "elisp" path (substring path 1)))
10600 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10601 ;; A typical message link. Planner has the id after the final slash,
10602 ;; we separate it with a hash mark
10603 (setq path (concat (match-string 1 path) "#"
10604 (org-remove-angle-brackets (match-string 2 path))))))
10605 (cons type path))
10607 (defun org-find-file-at-mouse (ev)
10608 "Open file link or URL at mouse."
10609 (interactive "e")
10610 (mouse-set-point ev)
10611 (org-open-at-point 'in-emacs))
10613 (defun org-open-at-mouse (ev)
10614 "Open file link or URL at mouse.
10615 See the docstring of `org-open-file' for details."
10616 (interactive "e")
10617 (mouse-set-point ev)
10618 (if (eq major-mode 'org-agenda-mode)
10619 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10620 (org-open-at-point))
10622 (defvar org-window-config-before-follow-link nil
10623 "The window configuration before following a link.
10624 This is saved in case the need arises to restore it.")
10626 ;;;###autoload
10627 (defun org-open-at-point-global ()
10628 "Follow a link like Org-mode does.
10629 This command can be called in any mode to follow a link that has
10630 Org-mode syntax."
10631 (interactive)
10632 (org-run-like-in-org-mode 'org-open-at-point))
10634 ;;;###autoload
10635 (defun org-open-link-from-string (s &optional arg reference-buffer)
10636 "Open a link in the string S, as if it was in Org-mode."
10637 (interactive "sLink: \nP")
10638 (let ((reference-buffer (or reference-buffer (current-buffer))))
10639 (with-temp-buffer
10640 (let ((org-inhibit-startup (not reference-buffer)))
10641 (org-mode)
10642 (insert s)
10643 (goto-char (point-min))
10644 (when reference-buffer
10645 (setq org-link-abbrev-alist-local
10646 (with-current-buffer reference-buffer
10647 org-link-abbrev-alist-local)))
10648 (org-open-at-point arg reference-buffer)))))
10650 (defvar org-open-at-point-functions nil
10651 "Hook that is run when following a link at point.
10653 Functions in this hook must return t if they identify and follow
10654 a link at point. If they don't find anything interesting at point,
10655 they must return nil.")
10657 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10658 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10659 (defun org-open-at-point (&optional arg reference-buffer)
10660 "Open link, timestamp, footnote or tags at point.
10662 When point is on a link, follow it. Normally, files will be
10663 opened by an appropriate application. If the optional prefix
10664 argument ARG is non-nil, Emacs will visit the file. With
10665 a double prefix argument, try to open outside of Emacs, in the
10666 application the system uses for this file type.
10668 When point is on a timestamp, open the agenda at the day
10669 specified.
10671 When point is a footnote definition, move to the first reference
10672 found. If it is on a reference, move to the associated
10673 definition.
10675 When point is on a headline, display a list of every link in the
10676 entry, so it is possible to pick one, or all, of them. If point
10677 is on a tag, call `org-tags-view' instead.
10679 When optional argument REFERENCE-BUFFER is non-nil, it should
10680 specify a buffer from where the link search should happen. This
10681 is used internally by `org-open-link-from-string'.
10683 On top of syntactically correct links, this function will open
10684 the link at point in comments or comment blocks and the first
10685 link in a property drawer line."
10686 (interactive "P")
10687 ;; On a code block, open block's results.
10688 (unless (call-interactively 'org-babel-open-src-block-result)
10689 (org-load-modules-maybe)
10690 (setq org-window-config-before-follow-link (current-window-configuration))
10691 (org-remove-occur-highlights nil nil t)
10692 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10693 (let* ((context
10694 ;; Only consider supported types, even if they are not
10695 ;; the closest one.
10696 (org-element-lineage
10697 (org-element-context)
10698 '(clock comment comment-block footnote-definition
10699 footnote-reference headline inlinetask keyword link
10700 node-property timestamp)
10702 (type (org-element-type context))
10703 (value (org-element-property :value context)))
10704 (cond
10705 ((not context) (user-error "No link found"))
10706 ;; Exception: open timestamps and links in properties
10707 ;; drawers, keywords and comments.
10708 ((memq type '(comment comment-block keyword node-property))
10709 (cond ((org-in-regexp org-any-link-re)
10710 (org-open-link-from-string (match-string-no-properties 0)))
10711 ((or (org-at-timestamp-p t) (org-at-date-range-p t))
10712 (org-follow-timestamp-link))
10713 (t (user-error "No link found"))))
10714 ;; On a headline or an inlinetask, but not on a timestamp,
10715 ;; a link, a footnote reference or on tags.
10716 ((and (memq type '(headline inlinetask))
10717 ;; Not on tags.
10718 (progn (save-excursion (beginning-of-line)
10719 (looking-at org-complex-heading-regexp))
10720 (or (not (match-beginning 5))
10721 (< (point) (match-beginning 5)))))
10722 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10723 (links (car data))
10724 (links-end (cdr data)))
10725 (if links
10726 (dolist (link (if (stringp links) (list links) links))
10727 (search-forward link nil links-end)
10728 (goto-char (match-beginning 0))
10729 (org-open-at-point))
10730 (require 'org-attach)
10731 (org-attach-reveal 'if-exists))))
10732 ;; On a clock line, make sure point is on the timestamp
10733 ;; before opening it.
10734 ((and (eq type 'clock)
10735 value
10736 (>= (point) (org-element-property :begin value))
10737 (<= (point) (org-element-property :end value)))
10738 (org-follow-timestamp-link))
10739 ;; Do nothing on white spaces after an object, unless point
10740 ;; is right after it.
10741 ((> (point)
10742 (save-excursion
10743 (goto-char (org-element-property :end context))
10744 (skip-chars-backward " \t")
10745 (point)))
10746 (user-error "No link found"))
10747 ((eq type 'timestamp) (org-follow-timestamp-link))
10748 ;; On tags within a headline or an inlinetask.
10749 ((and (memq type '(headline inlinetask))
10750 (progn (save-excursion (beginning-of-line)
10751 (looking-at org-complex-heading-regexp))
10752 (and (match-beginning 5)
10753 (>= (point) (match-beginning 5)))))
10754 (org-tags-view arg (substring (match-string 5) 0 -1)))
10755 ((eq type 'link)
10756 ;; When link is located within the description of another
10757 ;; link (e.g., an inline image), always open the parent
10758 ;; link.
10759 (let*((link (let ((up (org-element-property :parent context)))
10760 (if (eq (org-element-type up) 'link) up context)))
10761 (type (org-element-property :type link))
10762 (path (org-link-unescape (org-element-property :path link))))
10763 ;; Switch back to REFERENCE-BUFFER needed when called in
10764 ;; a temporary buffer through `org-open-link-from-string'.
10765 (with-current-buffer (or reference-buffer (current-buffer))
10766 (cond
10767 ((equal type "file")
10768 (if (string-match "[*?{]" (file-name-nondirectory path))
10769 (dired path)
10770 ;; Look into `org-link-protocols' in order to find
10771 ;; a DEDICATED-FUNCTION to open file. The function
10772 ;; will be applied on raw link instead of parsed
10773 ;; link due to the limitation in `org-add-link-type'
10774 ;; ("open" function called with a single argument).
10775 ;; If no such function is found, fallback to
10776 ;; `org-open-file'.
10778 ;; Note : "file+emacs" and "file+sys" types are
10779 ;; hard-coded in order to escape the previous
10780 ;; limitation.
10781 (let* ((option (org-element-property :search-option link))
10782 (app (org-element-property :application link))
10783 (dedicated-function
10784 (nth 1 (assoc app org-link-protocols))))
10785 (if dedicated-function
10786 (funcall dedicated-function
10787 (concat path
10788 (and option (concat "::" option))))
10789 (apply #'org-open-file
10790 path
10791 (cond (arg)
10792 ((equal app "emacs") 'emacs)
10793 ((equal app "sys") 'system))
10794 (cond ((not option) nil)
10795 ((org-string-match-p "\\`[0-9]+\\'" option)
10796 (list (string-to-number option)))
10797 (t (list nil
10798 (org-link-unescape option)))))))))
10799 ((assoc type org-link-protocols)
10800 (funcall (nth 1 (assoc type org-link-protocols)) path))
10801 ((equal type "help")
10802 (let ((f-or-v (intern path)))
10803 (cond ((fboundp f-or-v) (describe-function f-or-v))
10804 ((boundp f-or-v) (describe-variable f-or-v))
10805 (t (error "Not a known function or variable")))))
10806 ((member type '("http" "https" "ftp" "mailto" "news"))
10807 (browse-url (org-link-escape-browser (concat type ":" path))))
10808 ((equal type "doi")
10809 (browse-url
10810 (org-link-escape-browser (concat org-doi-server-url path))))
10811 ((equal type "message") (browse-url (concat type ":" path)))
10812 ((equal type "shell")
10813 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10814 (cmd path))
10815 (if (or (and (org-string-nw-p
10816 org-confirm-shell-link-not-regexp)
10817 (string-match
10818 org-confirm-shell-link-not-regexp cmd))
10819 (not org-confirm-shell-link-function)
10820 (funcall org-confirm-shell-link-function
10821 (format "Execute \"%s\" in shell? "
10822 (org-add-props cmd nil
10823 'face 'org-warning))))
10824 (progn
10825 (message "Executing %s" cmd)
10826 (shell-command cmd buf)
10827 (when (featurep 'midnight)
10828 (setq clean-buffer-list-kill-buffer-names
10829 (cons (buffer-name buf)
10830 clean-buffer-list-kill-buffer-names))))
10831 (user-error "Abort"))))
10832 ((equal type "elisp")
10833 (let ((cmd path))
10834 (if (or (and (org-string-nw-p
10835 org-confirm-elisp-link-not-regexp)
10836 (org-string-match-p
10837 org-confirm-elisp-link-not-regexp cmd))
10838 (not org-confirm-elisp-link-function)
10839 (funcall org-confirm-elisp-link-function
10840 (format "Execute \"%s\" as elisp? "
10841 (org-add-props cmd nil
10842 'face 'org-warning))))
10843 (message "%s => %s" cmd
10844 (if (eq (string-to-char cmd) ?\()
10845 (eval (read cmd))
10846 (call-interactively (read cmd))))
10847 (user-error "Abort"))))
10848 ((equal type "id")
10849 (require 'org-id)
10850 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10851 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10852 (unless (run-hook-with-args-until-success
10853 'org-open-link-functions path)
10854 (if (not arg) (org-mark-ring-push)
10855 (switch-to-buffer-other-window
10856 (org-get-buffer-for-internal-link (current-buffer))))
10857 (let ((destination
10858 (org-with-wide-buffer
10859 (if (equal type "radio")
10860 (org-search-radio-target
10861 (org-element-property :path link))
10862 (org-link-search
10863 (if (member type '("custom-id" "coderef"))
10864 (org-element-property :raw-link link)
10865 path)
10866 ;; Prevent fuzzy links from matching
10867 ;; themselves.
10868 (and (equal type "fuzzy")
10869 (+ 2 (org-element-property :begin link)))))
10870 (point))))
10871 (unless (and (<= (point-min) destination)
10872 (>= (point-max) destination))
10873 (widen))
10874 (goto-char destination))))
10875 (t (browse-url-at-point))))))
10876 ;; On a footnote reference or at a footnote definition's label.
10877 ((or (eq type 'footnote-reference)
10878 (and (eq type 'footnote-definition)
10879 (save-excursion
10880 ;; Do not validate action when point is on the
10881 ;; spaces right after the footnote label, in
10882 ;; order to be on par with behaviour on links.
10883 (skip-chars-forward " \t")
10884 (let ((begin
10885 (org-element-property :contents-begin context)))
10886 (if begin (< (point) begin)
10887 (= (org-element-property :post-affiliated context)
10888 (line-beginning-position)))))))
10889 (org-footnote-action))
10890 (t (user-error "No link found")))))
10891 (run-hook-with-args 'org-follow-link-hook)))
10893 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10894 "Offer links in the current entry and return the selected link.
10895 If there is only one link, return it.
10896 If NTH is an integer, return the NTH link found.
10897 If ZERO is a string, check also this string for a link, and if
10898 there is one, return it."
10899 (with-current-buffer buffer
10900 (save-excursion
10901 (save-restriction
10902 (widen)
10903 (goto-char marker)
10904 (let ((cnt ?0)
10905 (in-emacs (if (integerp nth) nil nth))
10906 have-zero end links link c)
10907 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10908 (push (match-string 0 zero) links)
10909 (setq cnt (1- cnt) have-zero t))
10910 (save-excursion
10911 (org-back-to-heading t)
10912 (setq end (save-excursion (outline-next-heading) (point)))
10913 (while (re-search-forward org-any-link-re end t)
10914 (push (match-string 0) links))
10915 (setq links (org-uniquify (reverse links))))
10916 (cond
10917 ((null links)
10918 (message "No links"))
10919 ((equal (length links) 1)
10920 (setq link (car links)))
10921 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10922 (setq link (nth (if have-zero nth (1- nth)) links)))
10923 (t ; we have to select a link
10924 (save-excursion
10925 (save-window-excursion
10926 (delete-other-windows)
10927 (with-output-to-temp-buffer "*Select Link*"
10928 (mapc (lambda (l)
10929 (if (not (string-match org-bracket-link-regexp l))
10930 (princ (format "[%c] %s\n" (incf cnt)
10931 (org-remove-angle-brackets l)))
10932 (if (match-end 3)
10933 (princ (format "[%c] %s (%s)\n" (incf cnt)
10934 (match-string 3 l) (match-string 1 l)))
10935 (princ (format "[%c] %s\n" (incf cnt)
10936 (match-string 1 l))))))
10937 links))
10938 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10939 (message "Select link to open, RET to open all:")
10940 (setq c (read-char-exclusive))
10941 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10942 (when (equal c ?q) (user-error "Abort"))
10943 (if (equal c ?\C-m)
10944 (setq link links)
10945 (setq nth (- c ?0))
10946 (if have-zero (setq nth (1+ nth)))
10947 (unless (and (integerp nth) (>= (length links) nth))
10948 (user-error "Invalid link selection"))
10949 (setq link (nth (1- nth) links)))))
10950 (cons link end))))))
10952 ;; TODO: These functions are deprecated since `org-open-at-point'
10953 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10954 (defun org-open-file-with-system (path)
10955 "Open file at PATH using the system way of opening it."
10956 (org-open-file path 'system))
10957 (defun org-open-file-with-emacs (path)
10958 "Open file at PATH in Emacs."
10959 (org-open-file path 'emacs))
10962 ;;; File search
10964 (defvar org-create-file-search-functions nil
10965 "List of functions to construct the right search string for a file link.
10966 These functions are called in turn with point at the location to
10967 which the link should point.
10969 A function in the hook should first test if it would like to
10970 handle this file type, for example by checking the `major-mode'
10971 or the file extension. If it decides not to handle this file, it
10972 should just return nil to give other functions a chance. If it
10973 does handle the file, it must return the search string to be used
10974 when following the link. The search string will be part of the
10975 file link, given after a double colon, and `org-open-at-point'
10976 will automatically search for it. If special measures must be
10977 taken to make the search successful, another function should be
10978 added to the companion hook `org-execute-file-search-functions',
10979 which see.
10981 A function in this hook may also use `setq' to set the variable
10982 `description' to provide a suggestion for the descriptive text to
10983 be used for this link when it gets inserted into an Org-mode
10984 buffer with \\[org-insert-link].")
10986 (defvar org-execute-file-search-functions nil
10987 "List of functions to execute a file search triggered by a link.
10989 Functions added to this hook must accept a single argument, the
10990 search string that was part of the file link, the part after the
10991 double colon. The function must first check if it would like to
10992 handle this search, for example by checking the `major-mode' or
10993 the file extension. If it decides not to handle this search, it
10994 should just return nil to give other functions a chance. If it
10995 does handle the search, it must return a non-nil value to keep
10996 other functions from trying.
10998 Each function can access the current prefix argument through the
10999 variable `current-prefix-arg'. Note that a single prefix is used
11000 to force opening a link in Emacs, so it may be good to only use a
11001 numeric or double prefix to guide the search function.
11003 In case this is needed, a function in this hook can also restore
11004 the window configuration before `org-open-at-point' was called using:
11006 (set-window-configuration org-window-config-before-follow-link)")
11008 (defun org-search-radio-target (target)
11009 "Search a radio target matching TARGET in current buffer.
11010 White spaces are not significant."
11011 (let ((re (format "<<<%s>>>"
11012 (mapconcat #'regexp-quote
11013 (org-split-string target "[ \t\n]+")
11014 "[ \t]+\\(?:\n[ \t]*\\)?")))
11015 (origin (point)))
11016 (goto-char (point-min))
11017 (catch :radio-match
11018 (while (re-search-forward re nil t)
11019 (backward-char)
11020 (let ((object (org-element-context)))
11021 (when (eq (org-element-type object) 'radio-target)
11022 (goto-char (org-element-property :begin object))
11023 (org-show-context 'link-search)
11024 (throw :radio-match nil))))
11025 (goto-char origin)
11026 (user-error "No match for radio target: %s" target))))
11028 (defun org-link-search (s &optional avoid-pos stealth)
11029 "Search for a search string S.
11031 If S starts with \"#\", it triggers a custom ID search.
11033 If S is enclosed within parenthesis, it initiates a coderef
11034 search.
11036 If S is surrounded by forward slashes, it is interpreted as
11037 a regular expression. In Org mode files, this will create an
11038 `org-occur' sparse tree. In ordinary files, `occur' will be used
11039 to list matches. If the current buffer is in `dired-mode', grep
11040 will be used to search in all files.
11042 When AVOID-POS is given, ignore matches near that position.
11044 When optional argument STEALTH is non-nil, do not modify
11045 visibility around point, thus ignoring `org-show-context-detail'
11046 variable.
11048 Search is case-insensitive and ignores white spaces. Return type
11049 of matched result, with is either `dedicated' or `fuzzy'."
11050 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11051 (let* ((case-fold-search t)
11052 (origin (point))
11053 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11054 (words (org-split-string s "[ \t\n]+"))
11055 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11056 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11057 type)
11058 (cond
11059 ;; Check if there are any special search functions.
11060 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11061 ((eq (string-to-char s) ?#)
11062 ;; Look for a custom ID S if S starts with "#".
11063 (let* ((id (substring normalized 1))
11064 (match (org-find-property "CUSTOM_ID" id)))
11065 (if match (progn (goto-char match) (setf type 'dedicated))
11066 (error "No match for custom ID: %s" id))))
11067 ((string-match "\\`(\\(.*\\))\\'" normalized)
11068 ;; Look for coderef targets if S is enclosed within parenthesis.
11069 (let ((coderef (match-string-no-properties 1 normalized))
11070 (re (substring s-single-re 1 -1)))
11071 (goto-char (point-min))
11072 (catch :coderef-match
11073 (while (re-search-forward re nil t)
11074 (let ((element (org-element-at-point)))
11075 (when (and (memq (org-element-type element)
11076 '(example-block src-block))
11077 ;; Build proper regexp according to current
11078 ;; block's label format.
11079 (let ((label-fmt
11080 (regexp-quote
11081 (or (org-element-property :label-fmt element)
11082 org-coderef-label-format))))
11083 (save-excursion
11084 (beginning-of-line)
11085 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11086 (format label-fmt coderef))))))
11087 (setq type 'dedicated)
11088 (goto-char (match-beginning 1))
11089 (throw :coderef-match nil))))
11090 (goto-char origin)
11091 (error "No match for coderef: %s" coderef))))
11092 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11093 ;; Look for a regular expression.
11094 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11095 (match-string 1 s)))
11096 ;; Fuzzy links.
11098 (let* ((starred (eq (string-to-char normalized) ?*))
11099 (headline-search (and (derived-mode-p 'org-mode)
11100 (or org-link-search-must-match-exact-headline
11101 starred))))
11102 (cond
11103 ;; Look for targets, only if not in a headline search.
11104 ((and (not starred)
11105 (let ((target (format "<<%s>>" s-multi-re)))
11106 (catch :target-match
11107 (goto-char (point-min))
11108 (while (re-search-forward target nil t)
11109 (backward-char)
11110 (let ((context (org-element-context)))
11111 (when (eq (org-element-type context) 'target)
11112 (setq type 'dedicated)
11113 (goto-char (org-element-property :begin context))
11114 (throw :target-match t))))
11115 nil))))
11116 ;; Look for elements named after S, only if not in a headline
11117 ;; search.
11118 ((and (not starred)
11119 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11120 (catch :name-match
11121 (goto-char (point-min))
11122 (while (re-search-forward name nil t)
11123 (let ((element (org-element-at-point)))
11124 (when (equal (org-split-string
11125 (org-element-property :name element)
11126 "[ \t]+")
11127 words)
11128 (setq type 'dedicated)
11129 (beginning-of-line)
11130 (throw :name-match t))))
11131 nil))))
11132 ;; Regular text search. Prefer headlines in Org mode
11133 ;; buffers.
11134 ((and (derived-mode-p 'org-mode)
11135 (let* ((wspace "[ \t]")
11136 (wspaceopt (concat wspace "*"))
11137 (cookie (concat "\\(?:"
11138 wspaceopt
11139 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11140 wspaceopt
11141 "\\)"))
11142 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11143 (re (concat
11144 org-outline-regexp-bol
11145 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11146 "\\(?:\\[#.\\][ \t]+\\)?"
11147 "\\(?:" org-comment-string "[ \t]+\\)?"
11148 sep "?"
11149 (let ((title (mapconcat #'regexp-quote
11150 words
11151 sep)))
11152 (if starred (substring title 1) title))
11153 sep "?"
11154 (org-re "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?")
11155 "[ \t]*$")))
11156 (goto-char (point-min))
11157 (re-search-forward re nil t)))
11158 (goto-char (match-beginning 0))
11159 (setq type 'dedicated))
11160 ;; Offer to create non-existent headline depending on
11161 ;; `org-link-search-must-match-exact-headline'.
11162 ((and (derived-mode-p 'org-mode)
11163 (not org-link-search-inhibit-query)
11164 (eq org-link-search-must-match-exact-headline 'query-to-create)
11165 (yes-or-no-p "No match - create this as a new heading? "))
11166 (goto-char (point-max))
11167 (unless (bolp) (newline))
11168 (org-insert-heading nil t t)
11169 (insert s "\n")
11170 (beginning-of-line 0))
11171 ;; Only headlines are looked after. No need to process
11172 ;; further: throw an error.
11173 ((and (derived-mode-p 'org-mode)
11174 (or starred org-link-search-must-match-exact-headline))
11175 (goto-char origin)
11176 (error "No match for fuzzy expression: %s" normalized))
11177 ;; Regular text search.
11178 ((catch :fuzzy-match
11179 (goto-char (point-min))
11180 (while (re-search-forward s-multi-re nil t)
11181 ;; Skip match if it contains AVOID-POS or it is included
11182 ;; in a link with a description but outside the
11183 ;; description.
11184 (unless (or (and avoid-pos
11185 (<= (match-beginning 0) avoid-pos)
11186 (> (match-end 0) avoid-pos))
11187 (and (save-match-data
11188 (org-in-regexp org-bracket-link-regexp))
11189 (match-beginning 3)
11190 (or (> (match-beginning 3) (point))
11191 (<= (match-end 3) (point)))
11192 (org-element-lineage
11193 (save-match-data (org-element-context))
11194 '(link) t)))
11195 (goto-char (match-beginning 0))
11196 (setq type 'fuzzy)
11197 (throw :fuzzy-match t)))
11198 nil))
11199 ;; All failed. Throw an error.
11200 (t (goto-char origin)
11201 (error "No match for fuzzy expression: %s" normalized))))))
11202 ;; Disclose surroundings of match, if appropriate.
11203 (when (and (derived-mode-p 'org-mode) (not stealth))
11204 (org-show-context 'link-search))
11205 type))
11207 (defun org-get-buffer-for-internal-link (buffer)
11208 "Return a buffer to be used for displaying the link target of internal links."
11209 (cond
11210 ((not org-display-internal-link-with-indirect-buffer)
11211 buffer)
11212 ((string-match "(Clone)$" (buffer-name buffer))
11213 (message "Buffer is already a clone, not making another one")
11214 ;; we also do not modify visibility in this case
11215 buffer)
11216 (t ; make a new indirect buffer for displaying the link
11217 (let* ((bn (buffer-name buffer))
11218 (ibn (concat bn "(Clone)"))
11219 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11220 (with-current-buffer ib (org-overview))
11221 ib))))
11223 (defun org-do-occur (regexp &optional cleanup)
11224 "Call the Emacs command `occur'.
11225 If CLEANUP is non-nil, remove the printout of the regular expression
11226 in the *Occur* buffer. This is useful if the regex is long and not useful
11227 to read."
11228 (occur regexp)
11229 (when cleanup
11230 (let ((cwin (selected-window)) win beg end)
11231 (when (setq win (get-buffer-window "*Occur*"))
11232 (select-window win))
11233 (goto-char (point-min))
11234 (when (re-search-forward "match[a-z]+" nil t)
11235 (setq beg (match-end 0))
11236 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11237 (setq end (1- (match-beginning 0)))))
11238 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11239 (goto-char (point-min))
11240 (select-window cwin))))
11242 ;;; The mark ring for links jumps
11244 (defvar org-mark-ring nil
11245 "Mark ring for positions before jumps in Org-mode.")
11246 (defvar org-mark-ring-last-goto nil
11247 "Last position in the mark ring used to go back.")
11248 ;; Fill and close the ring
11249 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11250 (loop for i from 1 to org-mark-ring-length do
11251 (push (make-marker) org-mark-ring))
11252 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11253 org-mark-ring)
11255 (defun org-mark-ring-push (&optional pos buffer)
11256 "Put the current position or POS into the mark ring and rotate it."
11257 (interactive)
11258 (setq pos (or pos (point)))
11259 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11260 (move-marker (car org-mark-ring)
11261 (or pos (point))
11262 (or buffer (current-buffer)))
11263 (message "%s"
11264 (substitute-command-keys
11265 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11267 (defun org-mark-ring-goto (&optional n)
11268 "Jump to the previous position in the mark ring.
11269 With prefix arg N, jump back that many stored positions. When
11270 called several times in succession, walk through the entire ring.
11271 Org-mode commands jumping to a different position in the current file,
11272 or to another Org-mode file, automatically push the old position
11273 onto the ring."
11274 (interactive "p")
11275 (let (p m)
11276 (if (eq last-command this-command)
11277 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11278 (setq p org-mark-ring))
11279 (setq org-mark-ring-last-goto p)
11280 (setq m (car p))
11281 (org-pop-to-buffer-same-window (marker-buffer m))
11282 (goto-char m)
11283 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11285 (defun org-remove-angle-brackets (s)
11286 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11287 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11289 (defun org-add-angle-brackets (s)
11290 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11291 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11293 (defun org-remove-double-quotes (s)
11294 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11295 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11298 ;;; Following specific links
11300 (defun org-follow-timestamp-link ()
11301 "Open an agenda view for the time-stamp date/range at point."
11302 (cond
11303 ((org-at-date-range-p t)
11304 (let ((org-agenda-start-on-weekday)
11305 (t1 (match-string 1))
11306 (t2 (match-string 2)) tt1 tt2)
11307 (setq tt1 (time-to-days (org-time-string-to-time t1))
11308 tt2 (time-to-days (org-time-string-to-time t2)))
11309 (let ((org-agenda-buffer-tmp-name
11310 (format "*Org Agenda(a:%s)"
11311 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11312 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11313 ((org-at-timestamp-p t)
11314 (let ((org-agenda-buffer-tmp-name
11315 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11316 (org-agenda-list nil (time-to-days (org-time-string-to-time
11317 (substring (match-string 1) 0 10)))
11318 1)))
11319 (t (error "This should not happen"))))
11322 ;;; Following file links
11323 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11324 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11325 (declare-function mailcap-mime-info
11326 "mailcap" (string &optional request no-decode))
11327 (defvar org-wait nil)
11328 (defun org-open-file (path &optional in-emacs line search)
11329 "Open the file at PATH.
11330 First, this expands any special file name abbreviations. Then the
11331 configuration variable `org-file-apps' is checked if it contains an
11332 entry for this file type, and if yes, the corresponding command is launched.
11334 If no application is found, Emacs simply visits the file.
11336 With optional prefix argument IN-EMACS, Emacs will visit the file.
11337 With a double \\[universal-argument] \\[universal-argument] \
11338 prefix arg, Org tries to avoid opening in Emacs
11339 and to use an external application to visit the file.
11341 Optional LINE specifies a line to go to, optional SEARCH a string
11342 to search for. If LINE or SEARCH is given, the file will be
11343 opened in Emacs, unless an entry from org-file-apps that makes
11344 use of groups in a regexp matches.
11346 If you want to change the way frames are used when following a
11347 link, please customize `org-link-frame-setup'.
11349 If the file does not exist, an error is thrown."
11350 (let* ((file (if (equal path "")
11351 buffer-file-name
11352 (substitute-in-file-name (expand-file-name path))))
11353 (file-apps (append org-file-apps (org-default-apps)))
11354 (apps (org-remove-if
11355 'org-file-apps-entry-match-against-dlink-p file-apps))
11356 (apps-dlink (org-remove-if-not
11357 'org-file-apps-entry-match-against-dlink-p file-apps))
11358 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11359 (dirp (if remp nil (file-directory-p file)))
11360 (file (if (and dirp org-open-directory-means-index-dot-org)
11361 (concat (file-name-as-directory file) "index.org")
11362 file))
11363 (a-m-a-p (assq 'auto-mode apps))
11364 (dfile (downcase file))
11365 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11366 (link (cond ((and (eq line nil)
11367 (eq search nil))
11368 file)
11369 (line
11370 (concat file "::" (number-to-string line)))
11371 (search
11372 (concat file "::" search))))
11373 (dlink (downcase link))
11374 (old-buffer (current-buffer))
11375 (old-pos (point))
11376 (old-mode major-mode)
11377 ext cmd link-match-data)
11378 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11379 (setq ext (match-string 1 dfile))
11380 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11381 (setq ext (match-string 1 dfile))))
11382 (cond
11383 ((member in-emacs '((16) system))
11384 (setq cmd (cdr (assoc 'system apps))))
11385 (in-emacs (setq cmd 'emacs))
11387 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11388 (and dirp (cdr (assoc 'directory apps)))
11389 ; first, try matching against apps-dlink
11390 ; if we get a match here, store the match data for later
11391 (let ((match (assoc-default dlink apps-dlink
11392 'string-match)))
11393 (if match
11394 (progn (setq link-match-data (match-data))
11395 match)
11396 (progn (setq in-emacs (or in-emacs line search))
11397 nil))) ; if we have no match in apps-dlink,
11398 ; always open the file in emacs if line or search
11399 ; is given (for backwards compatibility)
11400 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11401 'string-match)
11402 (cdr (assoc ext apps))
11403 (cdr (assoc t apps))))))
11404 (when (eq cmd 'system)
11405 (setq cmd (cdr (assoc 'system apps))))
11406 (when (eq cmd 'default)
11407 (setq cmd (cdr (assoc t apps))))
11408 (when (eq cmd 'mailcap)
11409 (require 'mailcap)
11410 (mailcap-parse-mailcaps)
11411 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11412 (command (mailcap-mime-info mime-type)))
11413 (if (stringp command)
11414 (setq cmd command)
11415 (setq cmd 'emacs))))
11416 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11417 (not (file-exists-p file))
11418 (not org-open-non-existing-files))
11419 (user-error "No such file: %s" file))
11420 (cond
11421 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11422 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11423 (while (string-match "['\"]%s['\"]" cmd)
11424 (setq cmd (replace-match "%s" t t cmd)))
11425 (while (string-match "%s" cmd)
11426 (setq cmd (replace-match
11427 (save-match-data
11428 (shell-quote-argument
11429 (convert-standard-filename file)))
11430 t t cmd)))
11432 ;; Replace "%1", "%2" etc. in command with group matches from regex
11433 (save-match-data
11434 (let ((match-index 1)
11435 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11436 (set-match-data link-match-data)
11437 (while (<= match-index number-of-groups)
11438 (let ((regex (concat "%" (number-to-string match-index)))
11439 (replace-with (match-string match-index dlink)))
11440 (while (string-match regex cmd)
11441 (setq cmd (replace-match replace-with t t cmd))))
11442 (setq match-index (+ match-index 1)))))
11444 (save-window-excursion
11445 (message "Running %s...done" cmd)
11446 (start-process-shell-command cmd nil cmd)
11447 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11448 ((or (stringp cmd)
11449 (eq cmd 'emacs))
11450 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11451 (widen)
11452 (if line (progn (org-goto-line line)
11453 (if (derived-mode-p 'org-mode)
11454 (org-reveal)))
11455 (if search (org-link-search search))))
11456 ((consp cmd)
11457 (let ((file (convert-standard-filename file)))
11458 (save-match-data
11459 (set-match-data link-match-data)
11460 (eval cmd))))
11461 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11462 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11463 (or (not (equal old-buffer (current-buffer)))
11464 (not (equal old-pos (point))))
11465 (org-mark-ring-push old-pos old-buffer))))
11467 (defun org-file-apps-entry-match-against-dlink-p (entry)
11468 "This function returns non-nil if `entry' uses a regular
11469 expression which should be matched against the whole link by
11470 org-open-file.
11472 It assumes that is the case when the entry uses a regular
11473 expression which has at least one grouping construct and the
11474 action is either a lisp form or a command string containing
11475 `%1', i.e. using at least one subexpression match as a
11476 parameter."
11477 (let ((selector (car entry))
11478 (action (cdr entry)))
11479 (if (stringp selector)
11480 (and (> (regexp-opt-depth selector) 0)
11481 (or (and (stringp action)
11482 (string-match "%[0-9]" action))
11483 (consp action)))
11484 nil)))
11486 (defun org-default-apps ()
11487 "Return the default applications for this operating system."
11488 (cond
11489 ((eq system-type 'darwin)
11490 org-file-apps-defaults-macosx)
11491 ((eq system-type 'windows-nt)
11492 org-file-apps-defaults-windowsnt)
11493 (t org-file-apps-defaults-gnu)))
11495 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11496 "Convert extensions to regular expressions in the cars of LIST.
11497 Also, weed out any non-string entries, because the return value is used
11498 only for regexp matching.
11499 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11500 point to the symbol `emacs', indicating that the file should
11501 be opened in Emacs."
11502 (append
11503 (delq nil
11504 (mapcar (lambda (x)
11505 (if (not (stringp (car x)))
11507 (if (string-match "\\W" (car x))
11509 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11510 list))
11511 (if add-auto-mode
11512 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11514 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11515 (defun org-file-remote-p (file)
11516 "Test whether FILE specifies a location on a remote system.
11517 Return non-nil if the location is indeed remote.
11519 For example, the filename \"/user@host:/foo\" specifies a location
11520 on the system \"/user@host:\"."
11521 (cond ((fboundp 'file-remote-p)
11522 (file-remote-p file))
11523 ((fboundp 'tramp-handle-file-remote-p)
11524 (tramp-handle-file-remote-p file))
11525 ((and (boundp 'ange-ftp-name-format)
11526 (string-match (car ange-ftp-name-format) file))
11527 t)))
11530 ;;;; Refiling
11532 (defun org-get-org-file ()
11533 "Read a filename, with default directory `org-directory'."
11534 (let ((default (or org-default-notes-file remember-data-file)))
11535 (read-file-name (format "File name [%s]: " default)
11536 (file-name-as-directory org-directory)
11537 default)))
11539 (defun org-notes-order-reversed-p ()
11540 "Check if the current file should receive notes in reversed order."
11541 (cond
11542 ((not org-reverse-note-order) nil)
11543 ((eq t org-reverse-note-order) t)
11544 ((not (listp org-reverse-note-order)) nil)
11545 (t (catch 'exit
11546 (dolist (entry org-reverse-note-order)
11547 (if (string-match (car entry) buffer-file-name)
11548 (throw 'exit (cdr entry))))))))
11550 (defvar org-refile-target-table nil
11551 "The list of refile targets, created by `org-refile'.")
11553 (defvar org-agenda-new-buffers nil
11554 "Buffers created to visit agenda files.")
11556 (defvar org-refile-cache nil
11557 "Cache for refile targets.")
11559 (defvar org-refile-markers nil
11560 "All the markers used for caching refile locations.")
11562 (defun org-refile-marker (pos)
11563 "Get a new refile marker, but only if caching is in use."
11564 (if (not org-refile-use-cache)
11566 (let ((m (make-marker)))
11567 (move-marker m pos)
11568 (push m org-refile-markers)
11569 m)))
11571 (defun org-refile-cache-clear ()
11572 "Clear the refile cache and disable all the markers."
11573 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11574 (setq org-refile-markers nil)
11575 (setq org-refile-cache nil)
11576 (message "Refile cache has been cleared"))
11578 (defun org-refile-cache-check-set (set)
11579 "Check if all the markers in the cache still have live buffers."
11580 (let (marker)
11581 (catch 'exit
11582 (while (and set (setq marker (nth 3 (pop set))))
11583 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11584 (when (and marker (null (marker-buffer marker)))
11585 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11586 (sit-for 3)
11587 (throw 'exit nil)))
11588 t)))
11590 (defun org-refile-cache-put (set &rest identifiers)
11591 "Push the refile targets SET into the cache, under IDENTIFIERS."
11592 (let* ((key (sha1 (prin1-to-string identifiers)))
11593 (entry (assoc key org-refile-cache)))
11594 (if entry
11595 (setcdr entry set)
11596 (push (cons key set) org-refile-cache))))
11598 (defun org-refile-cache-get (&rest identifiers)
11599 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11600 (cond
11601 ((not org-refile-cache) nil)
11602 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11604 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11605 org-refile-cache))))
11606 (and set (org-refile-cache-check-set set) set)))))
11608 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11609 "Produce a table with refile targets."
11610 (let ((case-fold-search nil)
11611 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11612 (entries (or org-refile-targets '((nil . (:level . 1)))))
11613 targets tgs txt re files desc descre fast-path-p level pos0)
11614 (message "Getting targets...")
11615 (with-current-buffer (or default-buffer (current-buffer))
11616 (dolist (entry entries)
11617 (setq files (car entry) desc (cdr entry))
11618 (setq fast-path-p nil)
11619 (cond
11620 ((null files) (setq files (list (current-buffer))))
11621 ((eq files 'org-agenda-files)
11622 (setq files (org-agenda-files 'unrestricted)))
11623 ((and (symbolp files) (fboundp files))
11624 (setq files (funcall files)))
11625 ((and (symbolp files) (boundp files))
11626 (setq files (symbol-value files))))
11627 (if (stringp files) (setq files (list files)))
11628 (cond
11629 ((eq (car desc) :tag)
11630 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11631 ((eq (car desc) :todo)
11632 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11633 ((eq (car desc) :regexp)
11634 (setq descre (cdr desc)))
11635 ((eq (car desc) :level)
11636 (setq descre (concat "^\\*\\{" (number-to-string
11637 (if org-odd-levels-only
11638 (1- (* 2 (cdr desc)))
11639 (cdr desc)))
11640 "\\}[ \t]")))
11641 ((eq (car desc) :maxlevel)
11642 (setq fast-path-p t)
11643 (setq descre (concat "^\\*\\{1," (number-to-string
11644 (if org-odd-levels-only
11645 (1- (* 2 (cdr desc)))
11646 (cdr desc)))
11647 "\\}[ \t]")))
11648 (t (error "Bad refiling target description %s" desc)))
11649 (dolist (f files)
11650 (with-current-buffer
11651 (if (bufferp f) f (org-get-agenda-file-buffer f))
11653 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11654 (progn
11655 (if (bufferp f) (setq f (buffer-file-name
11656 (buffer-base-buffer f))))
11657 (setq f (and f (expand-file-name f)))
11658 (if (eq org-refile-use-outline-path 'file)
11659 (push (list (file-name-nondirectory f) f nil nil) tgs))
11660 (save-excursion
11661 (save-restriction
11662 (widen)
11663 (goto-char (point-min))
11664 (while (re-search-forward descre nil t)
11665 (goto-char (setq pos0 (point-at-bol)))
11666 (catch 'next
11667 (when org-refile-target-verify-function
11668 (save-match-data
11669 (or (funcall org-refile-target-verify-function)
11670 (throw 'next t))))
11671 (when (and (looking-at org-complex-heading-regexp)
11672 (not (member (match-string 4) excluded-entries))
11673 (match-string 4))
11674 (setq level (org-reduced-level
11675 (- (match-end 1) (match-beginning 1)))
11676 txt (org-link-display-format (match-string 4))
11677 txt (replace-regexp-in-string "\\( *[[0-9]+/?[0-9]*%?]\\)+$" "" txt)
11678 re (format org-complex-heading-regexp-format
11679 (regexp-quote (match-string 4))))
11680 (when org-refile-use-outline-path
11681 (setq txt (mapconcat
11682 'org-protect-slash
11683 (append
11684 (if (eq org-refile-use-outline-path
11685 'file)
11686 (list (file-name-nondirectory
11687 (buffer-file-name
11688 (buffer-base-buffer))))
11689 (if (eq org-refile-use-outline-path
11690 'full-file-path)
11691 (list (buffer-file-name
11692 (buffer-base-buffer)))))
11693 (org-get-outline-path fast-path-p
11694 level txt)
11695 (list txt))
11696 "/")))
11697 (push (list txt f re (org-refile-marker (point)))
11698 tgs)))
11699 (when (= (point) pos0)
11700 ;; verification function has not moved point
11701 (goto-char (point-at-eol))))))))
11702 (when org-refile-use-cache
11703 (org-refile-cache-put tgs (buffer-file-name) descre))
11704 (setq targets (append tgs targets))))))
11705 (message "Getting targets...done")
11706 (nreverse targets)))
11708 (defun org-protect-slash (s)
11709 (while (string-match "/" s)
11710 (setq s (replace-match "\\" t t s)))
11713 (defvar org-olpa (make-vector 20 nil))
11715 (defun org-get-outline-path (&optional fastp level heading)
11716 "Return the outline path to the current entry, as a list.
11718 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11719 routine which makes outline path derivations for an entire file,
11720 avoiding backtracing. Refile target collection makes use of that."
11721 (if fastp
11722 (progn
11723 (if (> level 19)
11724 (error "Outline path failure, more than 19 levels"))
11725 (loop for i from level upto 19 do
11726 (aset org-olpa i nil))
11727 (prog1
11728 (delq nil (append org-olpa nil))
11729 (aset org-olpa level heading)))
11730 (let (rtn case-fold-search)
11731 (save-excursion
11732 (save-restriction
11733 (widen)
11734 (while (org-up-heading-safe)
11735 (when (looking-at org-complex-heading-regexp)
11736 (push (org-trim
11737 (replace-regexp-in-string
11738 ;; Remove statistical/checkboxes cookies
11739 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11740 (org-match-string-no-properties 4)))
11741 rtn)))
11742 rtn)))))
11744 (defun org-format-outline-path (path &optional width prefix separator)
11745 "Format the outline path PATH for display.
11746 WIDTH is the maximum number of characters that is available.
11747 PREFIX is a prefix to be included in the returned string,
11748 such as the file name.
11749 SEPARATOR is inserted between the different parts of the path,
11750 the default is \"/\"."
11751 (setq width (or width 79))
11752 (if prefix (setq width (- width (length prefix))))
11753 (if (not path)
11754 (or prefix "")
11755 (let* ((nsteps (length path))
11756 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11757 (maxwidth (if (<= total-width width)
11758 10000 ;; everything fits
11759 ;; we need to shorten the level headings
11760 (/ (- width nsteps) nsteps)))
11761 (org-odd-levels-only nil)
11762 (n 0)
11763 (total (1+ (length prefix))))
11764 (setq maxwidth (max maxwidth 10))
11765 (concat prefix
11766 (if prefix (or separator "/"))
11767 (mapconcat
11768 (lambda (h)
11769 (setq n (1+ n))
11770 (if (and (= n nsteps) (< maxwidth 10000))
11771 (setq maxwidth (- total-width total)))
11772 (if (< (length h) maxwidth)
11773 (progn (setq total (+ total (length h) 1)) h)
11774 (setq h (substring h 0 (- maxwidth 2))
11775 total (+ total maxwidth 1))
11776 (if (string-match "[ \t]+\\'" h)
11777 (setq h (substring h 0 (match-beginning 0))))
11778 (setq h (concat h "..")))
11779 (org-add-props h nil 'face
11780 (nth (% (1- n) org-n-level-faces)
11781 org-level-faces))
11783 path (or separator "/"))))))
11785 (defun org-display-outline-path (&optional file current separator just-return-string)
11786 "Display the current outline path in the echo area.
11788 If FILE is non-nil, prepend the output with the file name.
11789 If CURRENT is non-nil, append the current heading to the output.
11790 SEPARATOR is passed through to `org-format-outline-path'. It separates
11791 the different parts of the path and defaults to \"/\".
11792 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11793 (interactive "P")
11794 (let* (case-fold-search
11795 (bfn (buffer-file-name (buffer-base-buffer)))
11796 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11797 res)
11798 (if current (setq path (append path
11799 (save-excursion
11800 (org-back-to-heading t)
11801 (if (looking-at org-complex-heading-regexp)
11802 (list (match-string 4)))))))
11803 (setq res
11804 (org-format-outline-path
11805 path
11806 (1- (frame-width))
11807 (and file bfn (concat (file-name-nondirectory bfn) separator))
11808 separator))
11809 (if just-return-string
11810 (org-no-properties res)
11811 (org-unlogged-message "%s" res))))
11813 (defvar org-refile-history nil
11814 "History for refiling operations.")
11816 (defvar org-after-refile-insert-hook nil
11817 "Hook run after `org-refile' has inserted its stuff at the new location.
11818 Note that this is still *before* the stuff will be removed from
11819 the *old* location.")
11821 (defvar org-capture-last-stored-marker)
11822 (defvar org-refile-keep nil
11823 "Non-nil means `org-refile' will copy instead of refile.")
11825 (defun org-copy ()
11826 "Like `org-refile', but copy."
11827 (interactive)
11828 (let ((org-refile-keep t))
11829 (funcall 'org-refile nil nil nil "Copy")))
11831 (defun org-refile (&optional arg default-buffer rfloc msg)
11832 "Move the entry or entries at point to another heading.
11833 The list of target headings is compiled using the information in
11834 `org-refile-targets', which see.
11836 At the target location, the entry is filed as a subitem of the
11837 target heading. Depending on `org-reverse-note-order', the new
11838 subitem will either be the first or the last subitem.
11840 If there is an active region, all entries in that region will be
11841 refiled. However, the region must fulfill the requirement that
11842 the first heading sets the top-level of the moved text.
11844 With prefix arg ARG, the command will only visit the target
11845 location and not actually move anything.
11847 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11848 refiling operation has put the subtree.
11850 With a numeric prefix argument of `2', refile to the running clock.
11852 With a numeric prefix argument of `3', emulate `org-refile-keep'
11853 being set to t and copy to the target location, don't move it.
11854 Beware that keeping refiled entries may result in duplicated ID
11855 properties.
11857 RFLOC can be a refile location obtained in a different way.
11859 MSG is a string to replace \"Refile\" in the default prompt with
11860 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11862 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11864 If you are using target caching (see `org-refile-use-cache'), you
11865 have to clear the target cache in order to find new targets.
11866 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11867 prefix argument (`C-u C-u C-u C-c C-w')."
11868 (interactive "P")
11869 (if (member arg '(0 (64)))
11870 (org-refile-cache-clear)
11871 (let* ((actionmsg (cond (msg msg)
11872 ((equal arg 3) "Refile (and keep)")
11873 (t "Refile")))
11874 (cbuf (current-buffer))
11875 (regionp (org-region-active-p))
11876 (region-start (and regionp (region-beginning)))
11877 (region-end (and regionp (region-end)))
11878 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11879 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11880 pos it nbuf file re level reversed)
11881 (setq last-command nil)
11882 (when regionp
11883 (goto-char region-start)
11884 (or (bolp) (goto-char (point-at-bol)))
11885 (setq region-start (point))
11886 (unless (or (org-kill-is-subtree-p
11887 (buffer-substring region-start region-end))
11888 (prog1 org-refile-active-region-within-subtree
11889 (let ((s (point-at-eol)))
11890 (org-toggle-heading)
11891 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11892 (user-error "The region is not a (sequence of) subtree(s)")))
11893 (if (equal arg '(16))
11894 (org-refile-goto-last-stored)
11895 (when (or
11896 (and (equal arg 2)
11897 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11898 (prog1
11899 (setq it (list (or org-clock-heading "running clock")
11900 (buffer-file-name
11901 (marker-buffer org-clock-hd-marker))
11903 (marker-position org-clock-hd-marker)))
11904 (setq arg nil)))
11905 (setq it (or rfloc
11906 (let (heading-text)
11907 (save-excursion
11908 (unless (and arg (listp arg))
11909 (org-back-to-heading t)
11910 (setq heading-text
11911 (replace-regexp-in-string
11912 org-bracket-link-regexp
11913 "\\3"
11914 (nth 4 (org-heading-components)))))
11915 (org-refile-get-location
11916 (cond ((and arg (listp arg)) "Goto")
11917 (regionp (concat actionmsg " region to"))
11918 (t (concat actionmsg " subtree \""
11919 heading-text "\" to")))
11920 default-buffer
11921 (and (not (equal '(4) arg))
11922 org-refile-allow-creating-parent-nodes)
11923 arg))))))
11924 (setq file (nth 1 it)
11925 re (nth 2 it)
11926 pos (nth 3 it))
11927 (if (and (not arg)
11929 (equal (buffer-file-name) file)
11930 (if regionp
11931 (and (>= pos region-start)
11932 (<= pos region-end))
11933 (and (>= pos (point))
11934 (< pos (save-excursion
11935 (org-end-of-subtree t t))))))
11936 (error "Cannot refile to position inside the tree or region"))
11937 (setq nbuf (or (find-buffer-visiting file)
11938 (find-file-noselect file)))
11939 (if (and arg (not (equal arg 3)))
11940 (progn
11941 (org-pop-to-buffer-same-window nbuf)
11942 (goto-char pos)
11943 (org-show-context 'org-goto))
11944 (if regionp
11945 (progn
11946 (org-kill-new (buffer-substring region-start region-end))
11947 (org-save-markers-in-region region-start region-end))
11948 (org-copy-subtree 1 nil t))
11949 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11950 (find-file-noselect file)))
11951 (setq reversed (org-notes-order-reversed-p))
11952 (save-excursion
11953 (save-restriction
11954 (widen)
11955 (if pos
11956 (progn
11957 (goto-char pos)
11958 (looking-at org-outline-regexp)
11959 (setq level (org-get-valid-level (funcall outline-level) 1))
11960 (goto-char
11961 (if reversed
11962 (or (outline-next-heading) (point-max))
11963 (or (save-excursion (org-get-next-sibling))
11964 (org-end-of-subtree t t)
11965 (point-max)))))
11966 (setq level 1)
11967 (if (not reversed)
11968 (goto-char (point-max))
11969 (goto-char (point-min))
11970 (or (outline-next-heading) (goto-char (point-max)))))
11971 (if (not (bolp)) (newline))
11972 (org-paste-subtree level nil nil t)
11973 (when org-log-refile
11974 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11975 (unless (eq org-log-refile 'note)
11976 (save-excursion (org-add-log-note))))
11977 (and org-auto-align-tags
11978 (let ((org-loop-over-headlines-in-active-region nil))
11979 (org-set-tags nil t)))
11980 (let ((bookmark-name (plist-get org-bookmark-names-plist
11981 :last-refile)))
11982 (when bookmark-name
11983 (with-demoted-errors
11984 (bookmark-set bookmark-name))))
11985 ;; If we are refiling for capture, make sure that the
11986 ;; last-capture pointers point here
11987 (when (org-bound-and-true-p org-refile-for-capture)
11988 (let ((bookmark-name (plist-get org-bookmark-names-plist
11989 :last-capture-marker)))
11990 (when bookmark-name
11991 (with-demoted-errors
11992 (bookmark-set bookmark-name))))
11993 (move-marker org-capture-last-stored-marker (point)))
11994 (if (fboundp 'deactivate-mark) (deactivate-mark))
11995 (run-hooks 'org-after-refile-insert-hook))))
11996 (unless org-refile-keep
11997 (if regionp
11998 (delete-region (point) (+ (point) (- region-end region-start)))
11999 (delete-region
12000 (and (org-back-to-heading t) (point))
12001 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12002 (when (featurep 'org-inlinetask)
12003 (org-inlinetask-remove-END-maybe))
12004 (setq org-markers-to-move nil)
12005 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12007 (defun org-refile-goto-last-stored ()
12008 "Go to the location where the last refile was stored."
12009 (interactive)
12010 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12011 (message "This is the location of the last refile"))
12013 (defun org-refile--get-location (refloc tbl)
12014 "When user refile to REFLOC, find the associated target in TBL.
12015 Also check `org-refile-target-table'."
12016 (car (delq
12018 (mapcar
12019 (lambda (r) (or (assoc r tbl)
12020 (assoc r org-refile-target-table)))
12021 (list (replace-regexp-in-string "/$" "" refloc)
12022 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12024 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
12025 no-exclude)
12026 "Prompt the user for a refile location, using PROMPT.
12027 PROMPT should not be suffixed with a colon and a space, because
12028 this function appends the default value from
12029 `org-refile-history' automatically, if that is not empty.
12030 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
12031 this is used for the GOTO interface."
12032 (let ((org-refile-targets org-refile-targets)
12033 (org-refile-use-outline-path org-refile-use-outline-path)
12034 excluded-entries)
12035 (when (and (derived-mode-p 'org-mode)
12036 (not org-refile-use-cache)
12037 (not no-exclude))
12038 (org-map-tree
12039 (lambda()
12040 (setq excluded-entries
12041 (append excluded-entries (list (org-get-heading t t)))))))
12042 (setq org-refile-target-table
12043 (org-refile-get-targets default-buffer excluded-entries)))
12044 (unless org-refile-target-table
12045 (user-error "No refile targets"))
12046 (let* ((cbuf (current-buffer))
12047 (partial-completion-mode nil)
12048 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12049 (cfunc (if (and org-refile-use-outline-path
12050 org-outline-path-complete-in-steps)
12051 'org-olpath-completing-read
12052 'org-icompleting-read))
12053 (extra (if org-refile-use-outline-path "/" ""))
12054 (cbnex (concat (buffer-name) extra))
12055 (filename (and cfn (expand-file-name cfn)))
12056 (tbl (mapcar
12057 (lambda (x)
12058 (if (and (not (member org-refile-use-outline-path
12059 '(file full-file-path)))
12060 (not (equal filename (nth 1 x))))
12061 (cons (concat (car x) extra " ("
12062 (file-name-nondirectory (nth 1 x)) ")")
12063 (cdr x))
12064 (cons (concat (car x) extra) (cdr x))))
12065 org-refile-target-table))
12066 (completion-ignore-case t)
12067 cdef
12068 (prompt (concat prompt
12069 (or (and (car org-refile-history)
12070 (concat " (default " (car org-refile-history) ")"))
12071 (and (assoc cbnex tbl) (setq cdef cbnex)
12072 (concat " (default " cbnex ")"))) ": "))
12073 pa answ parent-target child parent old-hist)
12074 (setq old-hist org-refile-history)
12075 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12076 nil 'org-refile-history (or cdef (car org-refile-history))))
12077 (if (setq pa (org-refile--get-location answ tbl))
12078 (progn
12079 (org-refile-check-position pa)
12080 (when (or (not org-refile-history)
12081 (not (eq old-hist org-refile-history))
12082 (not (equal (car pa) (car org-refile-history))))
12083 (setq org-refile-history
12084 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12085 org-refile-history
12086 (cdr org-refile-history))))
12087 (if (equal (car org-refile-history) (nth 1 org-refile-history))
12088 (pop org-refile-history)))
12090 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12091 (progn
12092 (setq parent (match-string 1 answ)
12093 child (match-string 2 answ))
12094 (setq parent-target (org-refile--get-location parent tbl))
12095 (when (and parent-target
12096 (or (eq new-nodes t)
12097 (and (eq new-nodes 'confirm)
12098 (y-or-n-p (format "Create new node \"%s\"? "
12099 child)))))
12100 (org-refile-new-child parent-target child)))
12101 (user-error "Invalid target location")))))
12103 (declare-function org-string-nw-p "org-macs" (s))
12104 (defun org-refile-check-position (refile-pointer)
12105 "Check if the refile pointer matches the headline to which it points."
12106 (let* ((file (nth 1 refile-pointer))
12107 (re (nth 2 refile-pointer))
12108 (pos (nth 3 refile-pointer))
12109 buffer)
12110 (if (and (not (markerp pos)) (not file))
12111 (user-error "Please indicate a target file in the refile path")
12112 (when (org-string-nw-p re)
12113 (setq buffer (if (markerp pos)
12114 (marker-buffer pos)
12115 (or (find-buffer-visiting file)
12116 (find-file-noselect file))))
12117 (with-current-buffer buffer
12118 (save-excursion
12119 (save-restriction
12120 (widen)
12121 (goto-char pos)
12122 (beginning-of-line 1)
12123 (unless (org-looking-at-p re)
12124 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12126 (defun org-refile-new-child (parent-target child)
12127 "Use refile target PARENT-TARGET to add new CHILD below it."
12128 (unless parent-target
12129 (error "Cannot find parent for new node"))
12130 (let ((file (nth 1 parent-target))
12131 (pos (nth 3 parent-target))
12132 level)
12133 (with-current-buffer (or (find-buffer-visiting file)
12134 (find-file-noselect file))
12135 (save-excursion
12136 (save-restriction
12137 (widen)
12138 (if pos
12139 (goto-char pos)
12140 (goto-char (point-max))
12141 (if (not (bolp)) (newline)))
12142 (when (looking-at org-outline-regexp)
12143 (setq level (funcall outline-level))
12144 (org-end-of-subtree t t))
12145 (org-back-over-empty-lines)
12146 (insert "\n" (make-string
12147 (if pos (org-get-valid-level level 1) 1) ?*)
12148 " " child "\n")
12149 (beginning-of-line 0)
12150 (list (concat (car parent-target) "/" child) file "" (point)))))))
12152 (defun org-olpath-completing-read (prompt collection &rest args)
12153 "Read an outline path like a file name."
12154 (let ((thetable collection)
12155 (org-completion-use-ido nil) ; does not work with ido.
12156 (org-completion-use-iswitchb nil)) ; or iswitchb
12157 (apply #'org-icompleting-read
12158 prompt
12159 (lambda (string predicate &optional flag)
12160 (cond
12161 ((eq flag nil) (try-completion string thetable))
12162 ((eq flag t)
12163 (let ((l (length string)))
12164 (mapcar (lambda (x)
12165 (let ((r (substring x l))
12166 (f (if (string-match " ([^)]*)$" x)
12167 (match-string 0 x)
12168 "")))
12169 (if (string-match "/" r)
12170 (concat string (substring r 0 (match-end 0)) f)
12171 x)))
12172 (all-completions string thetable predicate))))
12173 ;; Exact match?
12174 ((eq flag 'lambda) (assoc string thetable))))
12175 args)))
12177 ;;;; Dynamic blocks
12179 (defun org-find-dblock (name)
12180 "Find the first dynamic block with name NAME in the buffer.
12181 If not found, stay at current position and return nil."
12182 (let ((case-fold-search t) pos)
12183 (save-excursion
12184 (goto-char (point-min))
12185 (setq pos (and (re-search-forward
12186 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12187 (match-beginning 0))))
12188 (if pos (goto-char pos))
12189 pos))
12191 (defun org-create-dblock (plist)
12192 "Create a dynamic block section, with parameters taken from PLIST.
12193 PLIST must contain a :name entry which is used as the name of the block."
12194 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12195 (end-of-line 1)
12196 (newline))
12197 (let ((col (current-column))
12198 (name (plist-get plist :name)))
12199 (insert "#+BEGIN: " name)
12200 (while plist
12201 (if (eq (car plist) :name)
12202 (setq plist (cddr plist))
12203 (insert " " (prin1-to-string (pop plist)))))
12204 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12205 (beginning-of-line -2)))
12207 (defun org-prepare-dblock ()
12208 "Prepare dynamic block for refresh.
12209 This empties the block, puts the cursor at the insert position and returns
12210 the property list including an extra property :name with the block name."
12211 (unless (looking-at org-dblock-start-re)
12212 (user-error "Not at a dynamic block"))
12213 (let* ((begdel (1+ (match-end 0)))
12214 (name (org-no-properties (match-string 1)))
12215 (params (append (list :name name)
12216 (read (concat "(" (match-string 3) ")")))))
12217 (save-excursion
12218 (beginning-of-line 1)
12219 (skip-chars-forward " \t")
12220 (setq params (plist-put params :indentation-column (current-column))))
12221 (unless (re-search-forward org-dblock-end-re nil t)
12222 (error "Dynamic block not terminated"))
12223 (setq params
12224 (append params
12225 (list :content (buffer-substring
12226 begdel (match-beginning 0)))))
12227 (delete-region begdel (match-beginning 0))
12228 (goto-char begdel)
12229 (open-line 1)
12230 params))
12232 (defun org-map-dblocks (&optional command)
12233 "Apply COMMAND to all dynamic blocks in the current buffer.
12234 If COMMAND is not given, use `org-update-dblock'."
12235 (let ((cmd (or command 'org-update-dblock)))
12236 (save-excursion
12237 (goto-char (point-min))
12238 (while (re-search-forward org-dblock-start-re nil t)
12239 (goto-char (match-beginning 0))
12240 (save-excursion
12241 (condition-case nil
12242 (funcall cmd)
12243 (error (message "Error during update of dynamic block"))))
12244 (unless (re-search-forward org-dblock-end-re nil t)
12245 (error "Dynamic block not terminated"))))))
12247 (defun org-dblock-update (&optional arg)
12248 "User command for updating dynamic blocks.
12249 Update the dynamic block at point. With prefix ARG, update all dynamic
12250 blocks in the buffer."
12251 (interactive "P")
12252 (if arg
12253 (org-update-all-dblocks)
12254 (or (looking-at org-dblock-start-re)
12255 (org-beginning-of-dblock))
12256 (org-update-dblock)))
12258 (defun org-update-dblock ()
12259 "Update the dynamic block at point.
12260 This means to empty the block, parse for parameters and then call
12261 the correct writing function."
12262 (interactive)
12263 (save-excursion
12264 (let* ((win (selected-window))
12265 (pos (point))
12266 (line (org-current-line))
12267 (params (org-prepare-dblock))
12268 (name (plist-get params :name))
12269 (indent (plist-get params :indentation-column))
12270 (cmd (intern (concat "org-dblock-write:" name))))
12271 (message "Updating dynamic block `%s' at line %d..." name line)
12272 (funcall cmd params)
12273 (message "Updating dynamic block `%s' at line %d...done" name line)
12274 (goto-char pos)
12275 (when (and indent (> indent 0))
12276 (setq indent (make-string indent ?\ ))
12277 (save-excursion
12278 (select-window win)
12279 (org-beginning-of-dblock)
12280 (forward-line 1)
12281 (while (not (looking-at org-dblock-end-re))
12282 (insert indent)
12283 (beginning-of-line 2))
12284 (when (looking-at org-dblock-end-re)
12285 (and (looking-at "[ \t]+")
12286 (replace-match ""))
12287 (insert indent)))))))
12289 (defun org-beginning-of-dblock ()
12290 "Find the beginning of the dynamic block at point.
12291 Error if there is no such block at point."
12292 (let ((pos (point))
12293 beg)
12294 (end-of-line 1)
12295 (if (and (re-search-backward org-dblock-start-re nil t)
12296 (setq beg (match-beginning 0))
12297 (re-search-forward org-dblock-end-re nil t)
12298 (> (match-end 0) pos))
12299 (goto-char beg)
12300 (goto-char pos)
12301 (error "Not in a dynamic block"))))
12303 (defun org-update-all-dblocks ()
12304 "Update all dynamic blocks in the buffer.
12305 This function can be used in a hook."
12306 (interactive)
12307 (when (derived-mode-p 'org-mode)
12308 (org-map-dblocks 'org-update-dblock)))
12311 ;;;; Completion
12313 (declare-function org-export-backend-name "org-export" (cl-x))
12314 (declare-function org-export-backend-options "org-export" (cl-x))
12315 (defun org-get-export-keywords ()
12316 "Return a list of all currently understood export keywords.
12317 Export keywords include options, block names, attributes and
12318 keywords relative to each registered export back-end."
12319 (let (keywords)
12320 (dolist (backend
12321 (org-bound-and-true-p org-export-registered-backends)
12322 (delq nil keywords))
12323 ;; Back-end name (for keywords, like #+LATEX:)
12324 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12325 (dolist (option-entry (org-export-backend-options backend))
12326 ;; Back-end options.
12327 (push (nth 1 option-entry) keywords)))))
12329 (defconst org-options-keywords
12330 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12331 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12332 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12333 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12334 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12336 (defcustom org-structure-template-alist
12337 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12338 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12339 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12340 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12341 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12342 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12343 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX")
12344 ("L" "#+LaTeX: ")
12345 ("h" "#+BEGIN_HTML\n?\n#+END_HTML")
12346 ("H" "#+HTML: ")
12347 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
12348 ("A" "#+ASCII: ")
12349 ("i" "#+INDEX: ?")
12350 ("I" "#+INCLUDE: %file ?"))
12351 "Structure completion elements.
12352 This is a list of abbreviation keys and values. The value gets inserted
12353 if you type `<' followed by the key and then press the completion key,
12354 usually `TAB'. %file will be replaced by a file name after prompting
12355 for the file using completion. The cursor will be placed at the position
12356 of the `?' in the template.
12357 There are two templates for each key, the first uses the original Org syntax,
12358 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12359 the default when the /org-mtags.el/ module has been loaded. See also the
12360 variable `org-mtags-prefer-muse-templates'."
12361 :group 'org-completion
12362 :type '(repeat
12363 (list
12364 (string :tag "Key")
12365 (string :tag "Template")))
12366 :version "25.1"
12367 :package-version '(Org . "8.3"))
12369 (defun org-try-structure-completion ()
12370 "Try to complete a structure template before point.
12371 This looks for strings like \"<e\" on an otherwise empty line and
12372 expands them."
12373 (let ((l (buffer-substring (point-at-bol) (point)))
12375 (when (and (looking-at "[ \t]*$")
12376 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12377 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12378 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12379 (match-beginning 1)) a)
12380 t)))
12382 (defun org-complete-expand-structure-template (start cell)
12383 "Expand a structure template."
12384 (let ((rpl (nth 1 cell))
12385 (ind ""))
12386 (delete-region start (point))
12387 (when (string-match "\\`[ \t]*#\\+" rpl)
12388 (cond
12389 ((bolp))
12390 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12391 (setq ind (buffer-substring (point-at-bol) (point))))
12392 (t (newline))))
12393 (setq start (point))
12394 (if (string-match "%file" rpl)
12395 (setq rpl (replace-match
12396 (concat
12397 "\""
12398 (save-match-data
12399 (abbreviate-file-name (read-file-name "Include file: ")))
12400 "\"")
12401 t t rpl)))
12402 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12403 (concat "\n" ind)))
12404 (insert rpl)
12405 (if (re-search-backward "\\?" start t) (delete-char 1))))
12407 ;;;; TODO, DEADLINE, Comments
12409 (defun org-toggle-comment ()
12410 "Change the COMMENT state of an entry."
12411 (interactive)
12412 (save-excursion
12413 (org-back-to-heading)
12414 (looking-at org-complex-heading-regexp)
12415 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12416 (skip-chars-forward " \t")
12417 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12418 (if (org-in-commented-heading-p t)
12419 (delete-region (point)
12420 (progn (search-forward " " (line-end-position) 'move)
12421 (skip-chars-forward " \t")
12422 (point)))
12423 (insert org-comment-string)
12424 (unless (eolp) (insert " ")))))
12426 (defvar org-last-todo-state-is-todo nil
12427 "This is non-nil when the last TODO state change led to a TODO state.
12428 If the last change removed the TODO tag or switched to DONE, then
12429 this is nil.")
12431 (defvar org-setting-tags nil) ; dynamically skipped
12433 (defvar org-todo-setup-filter-hook nil
12434 "Hook for functions that pre-filter todo specs.
12435 Each function takes a todo spec and returns either nil or the spec
12436 transformed into canonical form." )
12438 (defvar org-todo-get-default-hook nil
12439 "Hook for functions that get a default item for todo.
12440 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12441 nil or a string to be used for the todo mark." )
12443 (defvar org-agenda-headline-snapshot-before-repeat)
12445 (defun org-current-effective-time ()
12446 "Return current time adjusted for `org-extend-today-until' variable."
12447 (let* ((ct (org-current-time))
12448 (dct (decode-time ct))
12449 (ct1
12450 (cond
12451 (org-use-last-clock-out-time-as-effective-time
12452 (or (org-clock-get-last-clock-out-time) ct))
12453 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12454 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12455 (t ct))))
12456 ct1))
12458 (defun org-todo-yesterday (&optional arg)
12459 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12460 (interactive "P")
12461 (if (eq major-mode 'org-agenda-mode)
12462 (apply 'org-agenda-todo-yesterday arg)
12463 (let* ((org-use-effective-time t)
12464 (hour (third (decode-time
12465 (org-current-time))))
12466 (org-extend-today-until (1+ hour)))
12467 (org-todo arg))))
12469 (defvar org-block-entry-blocking ""
12470 "First entry preventing the TODO state change.")
12472 (defun org-cancel-repeater ()
12473 "Cancel a repeater by setting its numeric value to zero."
12474 (interactive)
12475 (save-excursion
12476 (org-back-to-heading t)
12477 (let ((bound1 (point))
12478 (bound0 (save-excursion (outline-next-heading) (point))))
12479 (when (re-search-forward
12480 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12481 org-deadline-time-regexp "\\)\\|\\("
12482 org-ts-regexp "\\)")
12483 bound0 t)
12484 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12485 (replace-match "0" t nil nil 1))))))
12487 (defun org-todo (&optional arg)
12488 "Change the TODO state of an item.
12489 The state of an item is given by a keyword at the start of the heading,
12490 like
12491 *** TODO Write paper
12492 *** DONE Call mom
12494 The different keywords are specified in the variable `org-todo-keywords'.
12495 By default the available states are \"TODO\" and \"DONE\".
12496 So for this example: when the item starts with TODO, it is changed to DONE.
12497 When it starts with DONE, the DONE is removed. And when neither TODO nor
12498 DONE are present, add TODO at the beginning of the heading.
12500 With \\[universal-argument] prefix arg, use completion to determine the new \
12501 state.
12502 With numeric prefix arg, switch to that state.
12503 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12504 keywords (nextset).
12505 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12506 With a numeric prefix arg of 0, inhibit note taking for the change.
12507 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12509 When called through ELisp, arg is also interpreted in the following way:
12510 `none' -> empty state
12511 \"\"(empty string) -> switch to empty state
12512 `done' -> switch to DONE
12513 `nextset' -> switch to the next set of keywords
12514 `previousset' -> switch to the previous set of keywords
12515 \"WAITING\" -> switch to the specified keyword, but only if it
12516 really is a member of `org-todo-keywords'."
12517 (interactive "P")
12518 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12519 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12520 'region-start-level 'region))
12521 org-loop-over-headlines-in-active-region)
12522 (org-map-entries
12523 `(org-todo ,arg)
12524 org-loop-over-headlines-in-active-region
12525 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12526 (if (equal arg '(16)) (setq arg 'nextset))
12527 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12528 (let ((org-blocker-hook org-blocker-hook)
12529 commentp
12530 case-fold-search)
12531 (when (equal arg '(64))
12532 (setq arg nil org-blocker-hook nil))
12533 (when (and org-blocker-hook
12534 (or org-inhibit-blocking
12535 (org-entry-get nil "NOBLOCKING")))
12536 (setq org-blocker-hook nil))
12537 (save-excursion
12538 (catch 'exit
12539 (org-back-to-heading t)
12540 (when (org-in-commented-heading-p t)
12541 (org-toggle-comment)
12542 (setq commentp t))
12543 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12544 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12545 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12546 (let* ((match-data (match-data))
12547 (startpos (point-at-bol))
12548 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12549 (org-log-done org-log-done)
12550 (org-log-repeat org-log-repeat)
12551 (org-todo-log-states org-todo-log-states)
12552 (org-inhibit-logging
12553 (if (equal arg 0)
12554 (progn (setq arg nil) 'note) org-inhibit-logging))
12555 (this (match-string 1))
12556 (hl-pos (match-beginning 0))
12557 (head (org-get-todo-sequence-head this))
12558 (ass (assoc head org-todo-kwd-alist))
12559 (interpret (nth 1 ass))
12560 (done-word (nth 3 ass))
12561 (final-done-word (nth 4 ass))
12562 (org-last-state (or this ""))
12563 (completion-ignore-case t)
12564 (member (member this org-todo-keywords-1))
12565 (tail (cdr member))
12566 (org-state (cond
12567 ((and org-todo-key-trigger
12568 (or (and (equal arg '(4))
12569 (eq org-use-fast-todo-selection 'prefix))
12570 (and (not arg) org-use-fast-todo-selection
12571 (not (eq org-use-fast-todo-selection
12572 'prefix)))))
12573 ;; Use fast selection
12574 (org-fast-todo-selection))
12575 ((and (equal arg '(4))
12576 (or (not org-use-fast-todo-selection)
12577 (not org-todo-key-trigger)))
12578 ;; Read a state with completion
12579 (org-icompleting-read
12580 "State: " (mapcar 'list org-todo-keywords-1)
12581 nil t))
12582 ((eq arg 'right)
12583 (if this
12584 (if tail (car tail) nil)
12585 (car org-todo-keywords-1)))
12586 ((eq arg 'left)
12587 (if (equal member org-todo-keywords-1)
12589 (if this
12590 (nth (- (length org-todo-keywords-1)
12591 (length tail) 2)
12592 org-todo-keywords-1)
12593 (org-last org-todo-keywords-1))))
12594 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12595 (setq arg nil))) ; hack to fall back to cycling
12596 (arg
12597 ;; user or caller requests a specific state
12598 (cond
12599 ((equal arg "") nil)
12600 ((eq arg 'none) nil)
12601 ((eq arg 'done) (or done-word (car org-done-keywords)))
12602 ((eq arg 'nextset)
12603 (or (car (cdr (member head org-todo-heads)))
12604 (car org-todo-heads)))
12605 ((eq arg 'previousset)
12606 (let ((org-todo-heads (reverse org-todo-heads)))
12607 (or (car (cdr (member head org-todo-heads)))
12608 (car org-todo-heads))))
12609 ((car (member arg org-todo-keywords-1)))
12610 ((stringp arg)
12611 (user-error "State `%s' not valid in this file" arg))
12612 ((nth (1- (prefix-numeric-value arg))
12613 org-todo-keywords-1))))
12614 ((null member) (or head (car org-todo-keywords-1)))
12615 ((equal this final-done-word) nil) ;; -> make empty
12616 ((null tail) nil) ;; -> first entry
12617 ((memq interpret '(type priority))
12618 (if (eq this-command last-command)
12619 (car tail)
12620 (if (> (length tail) 0)
12621 (or done-word (car org-done-keywords))
12622 nil)))
12624 (car tail))))
12625 (org-state (or
12626 (run-hook-with-args-until-success
12627 'org-todo-get-default-hook org-state org-last-state)
12628 org-state))
12629 (next (if org-state (concat " " org-state " ") " "))
12630 (change-plist (list :type 'todo-state-change :from this :to org-state
12631 :position startpos))
12632 dolog now-done-p)
12633 (when org-blocker-hook
12634 (setq org-last-todo-state-is-todo
12635 (not (member this org-done-keywords)))
12636 (unless (save-excursion
12637 (save-match-data
12638 (org-with-wide-buffer
12639 (run-hook-with-args-until-failure
12640 'org-blocker-hook change-plist))))
12641 (if (org-called-interactively-p 'interactive)
12642 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12643 this org-state org-block-entry-blocking)
12644 ;; fail silently
12645 (message "TODO state change from %s to %s blocked (by \"%s\")"
12646 this org-state org-block-entry-blocking)
12647 (throw 'exit nil))))
12648 (store-match-data match-data)
12649 (replace-match next t t)
12650 (cond ((equal this org-state)
12651 (message "TODO state was already %s" (org-trim next)))
12652 ((pos-visible-in-window-p hl-pos)
12653 (message "TODO state changed to %s" (org-trim next))))
12654 (unless head
12655 (setq head (org-get-todo-sequence-head org-state)
12656 ass (assoc head org-todo-kwd-alist)
12657 interpret (nth 1 ass)
12658 done-word (nth 3 ass)
12659 final-done-word (nth 4 ass)))
12660 (when (memq arg '(nextset previousset))
12661 (message "Keyword-Set %d/%d: %s"
12662 (- (length org-todo-sets) -1
12663 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12664 (length org-todo-sets)
12665 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12666 (setq org-last-todo-state-is-todo
12667 (not (member org-state org-done-keywords)))
12668 (setq now-done-p (and (member org-state org-done-keywords)
12669 (not (member this org-done-keywords))))
12670 (and logging (org-local-logging logging))
12671 (when (and (or org-todo-log-states org-log-done)
12672 (not (eq org-inhibit-logging t))
12673 (not (memq arg '(nextset previousset))))
12674 ;; we need to look at recording a time and note
12675 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12676 (nth 2 (assoc this org-todo-log-states))))
12677 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12678 (setq dolog 'time))
12679 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12680 (and org-state
12681 (member org-state org-not-done-keywords)
12682 (not (member this org-not-done-keywords))))
12683 ;; This is now a todo state and was not one before
12684 ;; If there was a CLOSED time stamp, get rid of it.
12685 (org-add-planning-info nil nil 'closed))
12686 (when (and now-done-p org-log-done)
12687 ;; It is now done, and it was not done before
12688 (org-add-planning-info 'closed (org-current-effective-time))
12689 (if (and (not dolog) (eq 'note org-log-done))
12690 (org-add-log-setup 'done org-state this 'findpos 'note)))
12691 (when (and org-state dolog)
12692 ;; This is a non-nil state, and we need to log it
12693 (org-add-log-setup 'state org-state this 'findpos dolog)))
12694 ;; Fixup tag positioning
12695 (org-todo-trigger-tag-changes org-state)
12696 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12697 (when org-provide-todo-statistics
12698 (org-update-parent-todo-statistics))
12699 (run-hooks 'org-after-todo-state-change-hook)
12700 (if (and arg (not (member org-state org-done-keywords)))
12701 (setq head (org-get-todo-sequence-head org-state)))
12702 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12703 ;; Do we need to trigger a repeat?
12704 (when now-done-p
12705 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12706 ;; This is for the agenda, take a snapshot of the headline.
12707 (save-match-data
12708 (setq org-agenda-headline-snapshot-before-repeat
12709 (org-get-heading))))
12710 (org-auto-repeat-maybe org-state))
12711 ;; Fixup cursor location if close to the keyword
12712 (if (and (outline-on-heading-p)
12713 (not (bolp))
12714 (save-excursion (beginning-of-line 1)
12715 (looking-at org-todo-line-regexp))
12716 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12717 (progn
12718 (goto-char (or (match-end 2) (match-end 1)))
12719 (and (looking-at " ") (just-one-space))))
12720 (when org-trigger-hook
12721 (save-excursion
12722 (run-hook-with-args 'org-trigger-hook change-plist)))
12723 (when commentp (org-toggle-comment))))))))
12725 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12726 "Block turning an entry into a TODO, using the hierarchy.
12727 This checks whether the current task should be blocked from state
12728 changes. Such blocking occurs when:
12730 1. The task has children which are not all in a completed state.
12732 2. A task has a parent with the property :ORDERED:, and there
12733 are siblings prior to the current task with incomplete
12734 status.
12736 3. The parent of the task is blocked because it has siblings that should
12737 be done first, or is child of a block grandparent TODO entry."
12739 (if (not org-enforce-todo-dependencies)
12740 t ; if locally turned off don't block
12741 (catch 'dont-block
12742 ;; If this is not a todo state change, or if this entry is already DONE,
12743 ;; do not block
12744 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12745 (member (plist-get change-plist :from)
12746 (cons 'done org-done-keywords))
12747 (member (plist-get change-plist :to)
12748 (cons 'todo org-not-done-keywords))
12749 (not (plist-get change-plist :to)))
12750 (throw 'dont-block t))
12751 ;; If this task has children, and any are undone, it's blocked
12752 (save-excursion
12753 (org-back-to-heading t)
12754 (let ((this-level (funcall outline-level)))
12755 (outline-next-heading)
12756 (let ((child-level (funcall outline-level)))
12757 (while (and (not (eobp))
12758 (> child-level this-level))
12759 ;; this todo has children, check whether they are all
12760 ;; completed
12761 (if (and (not (org-entry-is-done-p))
12762 (org-entry-is-todo-p))
12763 (progn (setq org-block-entry-blocking (org-get-heading))
12764 (throw 'dont-block nil)))
12765 (outline-next-heading)
12766 (setq child-level (funcall outline-level))))))
12767 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12768 ;; any previous siblings are undone, it's blocked
12769 (save-excursion
12770 (org-back-to-heading t)
12771 (let* ((pos (point))
12772 (parent-pos (and (org-up-heading-safe) (point))))
12773 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12774 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12775 (forward-line 1)
12776 (re-search-forward org-not-done-heading-regexp pos t))
12777 (setq org-block-entry-blocking (match-string 0))
12778 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12779 ;; Search further up the hierarchy, to see if an ancestor is blocked
12780 (while t
12781 (goto-char parent-pos)
12782 (if (not (looking-at org-not-done-heading-regexp))
12783 (throw 'dont-block t)) ; do not block, parent is not a TODO
12784 (setq pos (point))
12785 (setq parent-pos (and (org-up-heading-safe) (point)))
12786 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12787 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12788 (forward-line 1)
12789 (re-search-forward org-not-done-heading-regexp pos t)
12790 (setq org-block-entry-blocking (org-get-heading)))
12791 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12793 (defcustom org-track-ordered-property-with-tag nil
12794 "Should the ORDERED property also be shown as a tag?
12795 The ORDERED property decides if an entry should require subtasks to be
12796 completed in sequence. Since a property is not very visible, setting
12797 this option means that toggling the ORDERED property with the command
12798 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12799 not relevant for the behavior, but it makes things more visible.
12801 Note that toggling the tag with tags commands will not change the property
12802 and therefore not influence behavior!
12804 This can be t, meaning the tag ORDERED should be used, It can also be a
12805 string to select a different tag for this task."
12806 :group 'org-todo
12807 :type '(choice
12808 (const :tag "No tracking" nil)
12809 (const :tag "Track with ORDERED tag" t)
12810 (string :tag "Use other tag")))
12812 (defun org-toggle-ordered-property ()
12813 "Toggle the ORDERED property of the current entry.
12814 For better visibility, you can track the value of this property with a tag.
12815 See variable `org-track-ordered-property-with-tag'."
12816 (interactive)
12817 (let* ((t1 org-track-ordered-property-with-tag)
12818 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12819 (save-excursion
12820 (org-back-to-heading)
12821 (if (org-entry-get nil "ORDERED")
12822 (progn
12823 (org-delete-property "ORDERED")
12824 (and tag (org-toggle-tag tag 'off))
12825 (message "Subtasks can be completed in arbitrary order"))
12826 (org-entry-put nil "ORDERED" "t")
12827 (and tag (org-toggle-tag tag 'on))
12828 (message "Subtasks must be completed in sequence")))))
12830 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12831 (defun org-block-todo-from-checkboxes (change-plist)
12832 "Block turning an entry into a TODO, using checkboxes.
12833 This checks whether the current task should be blocked from state
12834 changes because there are unchecked boxes in this entry."
12835 (if (not org-enforce-todo-checkbox-dependencies)
12836 t ; if locally turned off don't block
12837 (catch 'dont-block
12838 ;; If this is not a todo state change, or if this entry is already DONE,
12839 ;; do not block
12840 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12841 (member (plist-get change-plist :from)
12842 (cons 'done org-done-keywords))
12843 (member (plist-get change-plist :to)
12844 (cons 'todo org-not-done-keywords))
12845 (not (plist-get change-plist :to)))
12846 (throw 'dont-block t))
12847 ;; If this task has checkboxes that are not checked, it's blocked
12848 (save-excursion
12849 (org-back-to-heading t)
12850 (let ((beg (point)) end)
12851 (outline-next-heading)
12852 (setq end (point))
12853 (goto-char beg)
12854 (if (org-list-search-forward
12855 (concat (org-item-beginning-re)
12856 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12857 "\\[[- ]\\]")
12858 end t)
12859 (progn
12860 (if (boundp 'org-blocked-by-checkboxes)
12861 (setq org-blocked-by-checkboxes t))
12862 (throw 'dont-block nil)))))
12863 t))) ; do not block
12865 (defun org-entry-blocked-p ()
12866 "Non-nil if entry at point is blocked."
12867 (and (not (org-entry-get nil "NOBLOCKING"))
12868 (member (org-entry-get nil "TODO") org-not-done-keywords)
12869 (not (run-hook-with-args-until-failure
12870 'org-blocker-hook
12871 (list :type 'todo-state-change
12872 :position (point)
12873 :from 'todo
12874 :to 'done)))))
12876 (defun org-update-statistics-cookies (all)
12877 "Update the statistics cookie, either from TODO or from checkboxes.
12878 This should be called with the cursor in a line with a statistics cookie."
12879 (interactive "P")
12880 (if all
12881 (progn
12882 (org-update-checkbox-count 'all)
12883 (org-map-entries 'org-update-parent-todo-statistics))
12884 (if (not (org-at-heading-p))
12885 (org-update-checkbox-count)
12886 (let ((pos (point-marker))
12887 end l1 l2)
12888 (ignore-errors (org-back-to-heading t))
12889 (if (not (org-at-heading-p))
12890 (org-update-checkbox-count)
12891 (setq l1 (org-outline-level))
12892 (setq end (save-excursion
12893 (outline-next-heading)
12894 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12895 (point)))
12896 (if (and (save-excursion
12897 (re-search-forward
12898 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12899 (not (save-excursion (re-search-forward
12900 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12901 (org-update-checkbox-count)
12902 (if (and l2 (> l2 l1))
12903 (progn
12904 (goto-char end)
12905 (org-update-parent-todo-statistics))
12906 (goto-char pos)
12907 (beginning-of-line 1)
12908 (while (re-search-forward
12909 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12910 (point-at-eol) t)
12911 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12912 (goto-char pos)
12913 (move-marker pos nil)))))
12915 (defvar org-entry-property-inherited-from) ;; defined below
12916 (defun org-update-parent-todo-statistics ()
12917 "Update any statistics cookie in the parent of the current headline.
12918 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12919 the entire subtree and this will travel up the hierarchy and update
12920 statistics everywhere."
12921 (let* ((prop (save-excursion (org-up-heading-safe)
12922 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12923 (recursive (or (not org-hierarchical-todo-statistics)
12924 (and prop (string-match "\\<recursive\\>" prop))))
12925 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12927 (first t)
12928 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12929 level ltoggle l1 new ndel
12930 (cnt-all 0) (cnt-done 0) is-percent kwd
12931 checkbox-beg ov ovs ove cookie-present)
12932 (catch 'exit
12933 (save-excursion
12934 (beginning-of-line 1)
12935 (setq ltoggle (funcall outline-level))
12936 ;; Three situations are to consider:
12938 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12939 ;; to the top-level ancestor on the headline;
12941 ;; 2. If parent has "recursive" property, repeat up to the
12942 ;; headline setting that property, taking inheritance into
12943 ;; account;
12945 ;; 3. Else, move up to direct parent and proceed only once.
12946 (while (and (setq level (org-up-heading-safe))
12947 (or recursive first)
12948 (>= (point) lim))
12949 (setq first nil cookie-present nil)
12950 (unless (and level
12951 (not (string-match
12952 "\\<checkbox\\>"
12953 (downcase (or (org-entry-get nil "COOKIE_DATA")
12954 "")))))
12955 (throw 'exit nil))
12956 (while (re-search-forward box-re (point-at-eol) t)
12957 (setq cnt-all 0 cnt-done 0 cookie-present t)
12958 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12959 (save-match-data
12960 (unless (outline-next-heading) (throw 'exit nil))
12961 (while (and (looking-at org-complex-heading-regexp)
12962 (> (setq l1 (length (match-string 1))) level))
12963 (setq kwd (and (or recursive (= l1 ltoggle))
12964 (match-string 2)))
12965 (if (or (eq org-provide-todo-statistics 'all-headlines)
12966 (and (eq org-provide-todo-statistics t)
12967 (or (member kwd org-done-keywords)))
12968 (and (listp org-provide-todo-statistics)
12969 (stringp (car org-provide-todo-statistics))
12970 (or (member kwd org-provide-todo-statistics)
12971 (member kwd org-done-keywords)))
12972 (and (listp org-provide-todo-statistics)
12973 (listp (car org-provide-todo-statistics))
12974 (or (member kwd (car org-provide-todo-statistics))
12975 (and (member kwd org-done-keywords)
12976 (member kwd (cadr org-provide-todo-statistics))))))
12977 (setq cnt-all (1+ cnt-all))
12978 (if (eq org-provide-todo-statistics t)
12979 (and kwd (setq cnt-all (1+ cnt-all)))))
12980 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12981 (member kwd org-done-keywords))
12982 (and (listp org-provide-todo-statistics)
12983 (listp (car org-provide-todo-statistics))
12984 (member kwd org-done-keywords)
12985 (member kwd (cadr org-provide-todo-statistics)))
12986 (and (listp org-provide-todo-statistics)
12987 (stringp (car org-provide-todo-statistics))
12988 (member kwd org-done-keywords)))
12989 (setq cnt-done (1+ cnt-done)))
12990 (outline-next-heading)))
12991 (setq new
12992 (if is-percent
12993 (format "[%d%%]" (floor (* 100.0 cnt-done)
12994 (max 1 cnt-all)))
12995 (format "[%d/%d]" cnt-done cnt-all))
12996 ndel (- (match-end 0) checkbox-beg))
12997 ;; handle overlays when updating cookie from column view
12998 (when (setq ov (car (overlays-at checkbox-beg)))
12999 (setq ovs (overlay-start ov) ove (overlay-end ov))
13000 (delete-overlay ov))
13001 (goto-char checkbox-beg)
13002 (insert new)
13003 (delete-region (point) (+ (point) ndel))
13004 (when org-auto-align-tags (org-fix-tags-on-the-fly))
13005 (when ov (move-overlay ov ovs ove)))
13006 (when cookie-present
13007 (run-hook-with-args 'org-after-todo-statistics-hook
13008 cnt-done (- cnt-all cnt-done))))))
13009 (run-hooks 'org-todo-statistics-hook)))
13011 (defvar org-after-todo-statistics-hook nil
13012 "Hook that is called after a TODO statistics cookie has been updated.
13013 Each function is called with two arguments: the number of not-done entries
13014 and the number of done entries.
13016 For example, the following function, when added to this hook, will switch
13017 an entry to DONE when all children are done, and back to TODO when new
13018 entries are set to a TODO status. Note that this hook is only called
13019 when there is a statistics cookie in the headline!
13021 (defun org-summary-todo (n-done n-not-done)
13022 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13023 (let (org-log-done org-log-states) ; turn off logging
13024 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13027 (defvar org-todo-statistics-hook nil
13028 "Hook that is run whenever Org thinks TODO statistics should be updated.
13029 This hook runs even if there is no statistics cookie present, in which case
13030 `org-after-todo-statistics-hook' would not run.")
13032 (defun org-todo-trigger-tag-changes (state)
13033 "Apply the changes defined in `org-todo-state-tags-triggers'."
13034 (let ((l org-todo-state-tags-triggers)
13035 changes)
13036 (when (or (not state) (equal state ""))
13037 (setq changes (append changes (cdr (assoc "" l)))))
13038 (when (and (stringp state) (> (length state) 0))
13039 (setq changes (append changes (cdr (assoc state l)))))
13040 (when (member state org-not-done-keywords)
13041 (setq changes (append changes (cdr (assoc 'todo l)))))
13042 (when (member state org-done-keywords)
13043 (setq changes (append changes (cdr (assoc 'done l)))))
13044 (dolist (c changes)
13045 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13047 (defun org-local-logging (value)
13048 "Get logging settings from a property VALUE."
13049 ;; Directly set the variables, they are already local.
13050 (setq org-log-done nil
13051 org-log-repeat nil
13052 org-todo-log-states nil)
13053 (dolist (w (org-split-string value))
13054 (let (a)
13055 (cond
13056 ((setq a (assoc w org-startup-options))
13057 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13058 (set (nth 1 a) (nth 2 a))))
13059 ((setq a (org-extract-log-state-settings w))
13060 (and (member (car a) org-todo-keywords-1)
13061 (push a org-todo-log-states)))))))
13063 (defun org-get-todo-sequence-head (kwd)
13064 "Return the head of the TODO sequence to which KWD belongs.
13065 If KWD is not set, check if there is a text property remembering the
13066 right sequence."
13067 (let (p)
13068 (cond
13069 ((not kwd)
13070 (or (get-text-property (point-at-bol) 'org-todo-head)
13071 (progn
13072 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13073 nil (point-at-eol)))
13074 (get-text-property p 'org-todo-head))))
13075 ((not (member kwd org-todo-keywords-1))
13076 (car org-todo-keywords-1))
13077 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13079 (defun org-fast-todo-selection ()
13080 "Fast TODO keyword selection with single keys.
13081 Returns the new TODO keyword, or nil if no state change should occur."
13082 (let* ((fulltable org-todo-key-alist)
13083 (done-keywords org-done-keywords) ;; needed for the faces.
13084 (maxlen (apply 'max (mapcar
13085 (lambda (x)
13086 (if (stringp (car x)) (string-width (car x)) 0))
13087 fulltable)))
13088 (expert nil)
13089 (fwidth (+ maxlen 3 1 3))
13090 (ncol (/ (- (window-width) 4) fwidth))
13091 tg cnt e c tbl
13092 groups ingroup)
13093 (save-excursion
13094 (save-window-excursion
13095 (if expert
13096 (set-buffer (get-buffer-create " *Org todo*"))
13097 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13098 (erase-buffer)
13099 (org-set-local 'org-done-keywords done-keywords)
13100 (setq tbl fulltable cnt 0)
13101 (while (setq e (pop tbl))
13102 (cond
13103 ((equal e '(:startgroup))
13104 (push '() groups) (setq ingroup t)
13105 (when (not (= cnt 0))
13106 (setq cnt 0)
13107 (insert "\n"))
13108 (insert "{ "))
13109 ((equal e '(:endgroup))
13110 (setq ingroup nil cnt 0)
13111 (insert "}\n"))
13112 ((equal e '(:newline))
13113 (when (not (= cnt 0))
13114 (setq cnt 0)
13115 (insert "\n")
13116 (setq e (car tbl))
13117 (while (equal (car tbl) '(:newline))
13118 (insert "\n")
13119 (setq tbl (cdr tbl)))))
13121 (setq tg (car e) c (cdr e))
13122 (if ingroup (push tg (car groups)))
13123 (setq tg (org-add-props tg nil 'face
13124 (org-get-todo-face tg)))
13125 (if (and (= cnt 0) (not ingroup)) (insert " "))
13126 (insert "[" c "] " tg (make-string
13127 (- fwidth 4 (length tg)) ?\ ))
13128 (when (= (setq cnt (1+ cnt)) ncol)
13129 (insert "\n")
13130 (if ingroup (insert " "))
13131 (setq cnt 0)))))
13132 (insert "\n")
13133 (goto-char (point-min))
13134 (if (not expert) (org-fit-window-to-buffer))
13135 (message "[a-z..]:Set [SPC]:clear")
13136 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13137 (cond
13138 ((or (= c ?\C-g)
13139 (and (= c ?q) (not (rassoc c fulltable))))
13140 (setq quit-flag t))
13141 ((= c ?\ ) nil)
13142 ((setq e (rassoc c fulltable) tg (car e))
13144 (t (setq quit-flag t)))))))
13146 (defun org-entry-is-todo-p ()
13147 (member (org-get-todo-state) org-not-done-keywords))
13149 (defun org-entry-is-done-p ()
13150 (member (org-get-todo-state) org-done-keywords))
13152 (defun org-get-todo-state ()
13153 "Return the TODO keyword of the current subtree."
13154 (save-excursion
13155 (org-back-to-heading t)
13156 (and (looking-at org-todo-line-regexp)
13157 (match-end 2)
13158 (match-string 2))))
13160 (defun org-at-date-range-p (&optional inactive-ok)
13161 "Non-nil if point is inside a date range.
13163 When optional argument INACTIVE-OK is non-nil, also consider
13164 inactive time ranges.
13166 When this function returns a non-nil value, match data is set
13167 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13168 on INACTIVE-OK."
13169 (interactive)
13170 (save-excursion
13171 (catch 'exit
13172 (let ((pos (point)))
13173 (skip-chars-backward "^[<\r\n")
13174 (skip-chars-backward "<[")
13175 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13176 (>= (match-end 0) pos)
13177 (throw 'exit t))
13178 (skip-chars-backward "^<[\r\n")
13179 (skip-chars-backward "<[")
13180 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13181 (>= (match-end 0) pos)
13182 (throw 'exit t)))
13183 nil)))
13185 (defun org-get-repeat (&optional tagline)
13186 "Check if there is a deadline/schedule with repeater in this entry."
13187 (save-match-data
13188 (save-excursion
13189 (org-back-to-heading t)
13190 (and (re-search-forward (if tagline
13191 (concat tagline "\\s-*" org-repeat-re)
13192 org-repeat-re)
13193 (org-entry-end-position) t)
13194 (match-string-no-properties 1)))))
13196 (defvar org-last-changed-timestamp)
13197 (defvar org-last-inserted-timestamp)
13198 (defvar org-log-post-message)
13199 (defvar org-log-note-purpose)
13200 (defvar org-log-note-how nil)
13201 (defvar org-log-note-extra)
13202 (defun org-auto-repeat-maybe (done-word)
13203 "Check if the current headline contains a repeated deadline/schedule.
13204 If yes, set TODO state back to what it was and change the base date
13205 of repeating deadline/scheduled time stamps to new date.
13206 This function is run automatically after each state change to a DONE state."
13207 ;; last-state is dynamically scoped into this function
13208 (let* ((repeat (org-get-repeat))
13209 (aa (assoc org-last-state org-todo-kwd-alist))
13210 (interpret (nth 1 aa))
13211 (head (nth 2 aa))
13212 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13213 (msg "Entry repeats: ")
13214 (org-log-done nil)
13215 (org-todo-log-states nil)
13216 re type n what ts time to-state)
13217 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13218 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
13219 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
13220 org-todo-repeat-to-state))
13221 (unless (and to-state (member to-state org-todo-keywords-1))
13222 (setq to-state (if (eq interpret 'type) org-last-state head)))
13223 (org-todo to-state)
13224 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13225 (org-entry-put nil "LAST_REPEAT" (format-time-string
13226 (org-time-stamp-format t t))))
13227 (when org-log-repeat
13228 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13229 (memq 'org-add-log-note post-command-hook))
13230 ;; OK, we are already setup for some record
13231 (if (eq org-log-repeat 'note)
13232 ;; make sure we take a note, not only a time stamp
13233 (setq org-log-note-how 'note))
13234 ;; Set up for taking a record
13235 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13236 org-last-state
13237 'findpos org-log-repeat)))
13238 (org-back-to-heading t)
13239 (org-add-planning-info nil nil 'closed)
13240 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13241 org-deadline-time-regexp "\\)\\|\\("
13242 org-ts-regexp "\\)"))
13243 (while (re-search-forward
13244 re (save-excursion (outline-next-heading) (point)) t)
13245 (setq type (if (match-end 1) org-scheduled-string
13246 (if (match-end 3) org-deadline-string "Plain:"))
13247 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13248 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13249 (setq n (string-to-number (match-string 2 ts))
13250 what (match-string 3 ts))
13251 (if (equal what "w") (setq n (* n 7) what "d"))
13252 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13253 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13254 ;; Preparation, see if we need to modify the start date for the change
13255 (when (match-end 1)
13256 (setq time (save-match-data (org-time-string-to-time ts)))
13257 (cond
13258 ((equal (match-string 1 ts) ".")
13259 ;; Shift starting date to today
13260 (org-timestamp-change
13261 (- (org-today) (time-to-days time))
13262 'day))
13263 ((equal (match-string 1 ts) "+")
13264 (let ((nshiftmax 10) (nshift 0))
13265 (while (or (= nshift 0)
13266 (<= (time-to-days time)
13267 (time-to-days (current-time))))
13268 (when (= (incf nshift) nshiftmax)
13269 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13270 (user-error "Abort")))
13271 (org-timestamp-change n (cdr (assoc what whata)))
13272 (org-at-timestamp-p t)
13273 (setq ts (match-string 1))
13274 (setq time (save-match-data (org-time-string-to-time ts)))))
13275 (org-timestamp-change (- n) (cdr (assoc what whata)))
13276 ;; rematch, so that we have everything in place for the real shift
13277 (org-at-timestamp-p t)
13278 (setq ts (match-string 1))
13279 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13280 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13281 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13282 (setq org-log-post-message msg)
13283 (message "%s" msg))))
13285 (defun org-show-todo-tree (arg)
13286 "Make a compact tree which shows all headlines marked with TODO.
13287 The tree will show the lines where the regexp matches, and all higher
13288 headlines above the match.
13289 With a \\[universal-argument] prefix, prompt for a regexp to match.
13290 With a numeric prefix N, construct a sparse tree for the Nth element
13291 of `org-todo-keywords-1'."
13292 (interactive "P")
13293 (let ((case-fold-search nil)
13294 (kwd-re
13295 (cond ((null arg) org-not-done-regexp)
13296 ((equal arg '(4))
13297 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13298 (mapcar 'list org-todo-keywords-1))))
13299 (concat "\\("
13300 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13301 "\\)\\>")))
13302 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13303 (regexp-quote (nth (1- (prefix-numeric-value arg))
13304 org-todo-keywords-1)))
13305 (t (user-error "Invalid prefix argument: %s" arg)))))
13306 (message "%d TODO entries found"
13307 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13309 (defun org-deadline (arg &optional time)
13310 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13311 With one universal prefix argument, remove any deadline from the item.
13312 With two universal prefix arguments, prompt for a warning delay.
13313 With argument TIME, set the deadline at the corresponding date. TIME
13314 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13315 (interactive "P")
13316 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13317 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13318 'region-start-level 'region))
13319 org-loop-over-headlines-in-active-region)
13320 (org-map-entries
13321 `(org-deadline ',arg ,time)
13322 org-loop-over-headlines-in-active-region
13323 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13324 (let* ((old-date (org-entry-get nil "DEADLINE"))
13325 (old-date-time (if old-date (org-time-string-to-time old-date)))
13326 (repeater (and old-date
13327 (string-match
13328 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13329 old-date)
13330 (match-string 1 old-date))))
13331 (cond
13332 ((equal arg '(4))
13333 (when (and old-date org-log-redeadline)
13334 (org-add-log-setup 'deldeadline nil old-date 'findpos
13335 org-log-redeadline))
13336 (org-remove-timestamp-with-keyword org-deadline-string)
13337 (message "Item no longer has a deadline."))
13338 ((equal arg '(16))
13339 (save-excursion
13340 (org-back-to-heading t)
13341 (if (re-search-forward
13342 org-deadline-time-regexp
13343 (save-excursion (outline-next-heading) (point)) t)
13344 (let* ((rpl0 (match-string 1))
13345 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13346 (replace-match
13347 (concat org-deadline-string
13348 " <" rpl
13349 (format " -%dd"
13350 (abs
13351 (- (time-to-days
13352 (save-match-data
13353 (org-read-date nil t nil "Warn starting from" old-date-time)))
13354 (time-to-days old-date-time))))
13355 ">") t t))
13356 (user-error "No deadline information to update"))))
13358 (org-add-planning-info 'deadline time 'closed)
13359 (when (and old-date
13360 org-log-redeadline
13361 (not (equal old-date org-last-inserted-timestamp)))
13362 (org-add-log-setup
13363 'redeadline org-last-inserted-timestamp old-date 'findpos
13364 org-log-redeadline))
13365 (when repeater
13366 (save-excursion
13367 (org-back-to-heading t)
13368 (when (re-search-forward (concat org-deadline-string " "
13369 org-last-inserted-timestamp)
13370 (save-excursion
13371 (outline-next-heading) (point)) t)
13372 (goto-char (1- (match-end 0)))
13373 (insert " " repeater)
13374 (setq org-last-inserted-timestamp
13375 (concat (substring org-last-inserted-timestamp 0 -1)
13376 " " repeater
13377 (substring org-last-inserted-timestamp -1))))))
13378 (message "Deadline on %s" org-last-inserted-timestamp))))))
13380 (defun org-schedule (arg &optional time)
13381 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13382 With one universal prefix argument, remove any scheduling date from the item.
13383 With two universal prefix arguments, prompt for a delay cookie.
13384 With argument TIME, scheduled at the corresponding date. TIME can
13385 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13386 (interactive "P")
13387 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13388 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13389 'region-start-level 'region))
13390 org-loop-over-headlines-in-active-region)
13391 (org-map-entries
13392 `(org-schedule ',arg ,time)
13393 org-loop-over-headlines-in-active-region
13394 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13395 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13396 (old-date-time (if old-date (org-time-string-to-time old-date)))
13397 (repeater (and old-date
13398 (string-match
13399 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13400 old-date)
13401 (match-string 1 old-date))))
13402 (cond
13403 ((equal arg '(4))
13404 (progn
13405 (when (and old-date org-log-reschedule)
13406 (org-add-log-setup 'delschedule nil old-date 'findpos
13407 org-log-reschedule))
13408 (org-remove-timestamp-with-keyword org-scheduled-string)
13409 (message "Item is no longer scheduled.")))
13410 ((equal arg '(16))
13411 (save-excursion
13412 (org-back-to-heading t)
13413 (if (re-search-forward
13414 org-scheduled-time-regexp
13415 (save-excursion (outline-next-heading) (point)) t)
13416 (let* ((rpl0 (match-string 1))
13417 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13418 (replace-match
13419 (concat org-scheduled-string
13420 " <" rpl
13421 (format " -%dd"
13422 (abs
13423 (- (time-to-days
13424 (save-match-data
13425 (org-read-date nil t nil "Delay until" old-date-time)))
13426 (time-to-days old-date-time))))
13427 ">") t t))
13428 (user-error "No scheduled information to update"))))
13430 (org-add-planning-info 'scheduled time 'closed)
13431 (when (and old-date
13432 org-log-reschedule
13433 (not (equal old-date org-last-inserted-timestamp)))
13434 (org-add-log-setup
13435 'reschedule org-last-inserted-timestamp old-date 'findpos
13436 org-log-reschedule))
13437 (when repeater
13438 (save-excursion
13439 (org-back-to-heading t)
13440 (when (re-search-forward (concat org-scheduled-string " "
13441 org-last-inserted-timestamp)
13442 (save-excursion
13443 (outline-next-heading) (point)) t)
13444 (goto-char (1- (match-end 0)))
13445 (insert " " repeater)
13446 (setq org-last-inserted-timestamp
13447 (concat (substring org-last-inserted-timestamp 0 -1)
13448 " " repeater
13449 (substring org-last-inserted-timestamp -1))))))
13450 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13452 (defun org-get-scheduled-time (pom &optional inherit)
13453 "Get the scheduled time as a time tuple, of a format suitable
13454 for calling org-schedule with, or if there is no scheduling,
13455 returns nil."
13456 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13457 (when time
13458 (apply 'encode-time (org-parse-time-string time)))))
13460 (defun org-get-deadline-time (pom &optional inherit)
13461 "Get the deadline as a time tuple, of a format suitable for
13462 calling org-deadline with, or if there is no scheduling, returns
13463 nil."
13464 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13465 (when time
13466 (apply 'encode-time (org-parse-time-string time)))))
13468 (defun org-remove-timestamp-with-keyword (keyword)
13469 "Remove all time stamps with KEYWORD in the current entry."
13470 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13471 beg)
13472 (save-excursion
13473 (org-back-to-heading t)
13474 (setq beg (point))
13475 (outline-next-heading)
13476 (while (re-search-backward re beg t)
13477 (replace-match "")
13478 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13479 (equal (char-before) ?\ ))
13480 (backward-delete-char 1)
13481 (if (string-match "^[ \t]*$" (buffer-substring
13482 (point-at-bol) (point-at-eol)))
13483 (delete-region (point-at-bol)
13484 (min (point-max) (1+ (point-at-eol))))))))))
13486 (defvar org-time-was-given) ; dynamically scoped parameter
13487 (defvar org-end-time-was-given) ; dynamically scoped parameter
13489 (defun org-at-planning-p ()
13490 "Non-nil when point is on a planning info line."
13491 ;; This is as accurate and faster than `org-element-at-point' since
13492 ;; planning info location is fixed in the section.
13493 (org-with-wide-buffer
13494 (beginning-of-line)
13495 (and (org-looking-at-p org-planning-line-re)
13496 (eq (point)
13497 (ignore-errors
13498 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13499 (org-back-to-heading t)
13500 (org-with-limited-levels (org-back-to-heading t)))
13501 (line-beginning-position 2))))))
13503 (defun org-add-planning-info (what &optional time &rest remove)
13504 "Insert new timestamp with keyword in the planning line.
13505 WHAT indicates what kind of time stamp to add. It is a symbol
13506 among `closed', `deadline', `scheduled' and nil. TIME indicates
13507 the time to use. If none is given, the user is prompted for
13508 a date. REMOVE indicates what kind of entries to remove. An old
13509 WHAT entry will also be removed."
13510 (let (org-time-was-given org-end-time-was-given default-time default-input)
13511 (catch 'exit
13512 (when (and (memq what '(scheduled deadline))
13513 (or (not time)
13514 (and (stringp time)
13515 (string-match "^[-+]+[0-9]" time))))
13516 ;; Try to get a default date/time from existing timestamp
13517 (save-excursion
13518 (org-back-to-heading t)
13519 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13520 (when (re-search-forward (if (eq what 'scheduled)
13521 org-scheduled-time-regexp
13522 org-deadline-time-regexp)
13523 end t)
13524 (setq ts (match-string 1)
13525 default-time (apply 'encode-time (org-parse-time-string ts))
13526 default-input (and ts (org-get-compact-tod ts)))))))
13527 (when what
13528 (setq time
13529 (if (stringp time)
13530 ;; This is a string (relative or absolute), set
13531 ;; proper date.
13532 (apply #'encode-time
13533 (org-read-date-analyze
13534 time default-time (decode-time default-time)))
13535 ;; If necessary, get the time from the user
13536 (or time (org-read-date nil 'to-time nil nil
13537 default-time default-input)))))
13539 (org-with-wide-buffer
13540 (org-back-to-heading t)
13541 (forward-line)
13542 (unless (bolp) (insert "\n"))
13543 (cond ((org-looking-at-p org-planning-line-re)
13544 ;; Move to current indentation.
13545 (skip-chars-forward " \t")
13546 ;; Check if we have to remove something.
13547 (dolist (type (if what (cons what remove) remove))
13548 (save-excursion
13549 (when (re-search-forward
13550 (case type
13551 (closed org-closed-time-regexp)
13552 (deadline org-deadline-time-regexp)
13553 (scheduled org-scheduled-time-regexp)
13554 (otherwise
13555 (error "Invalid planning type: %s" type)))
13556 (line-end-position) t)
13557 ;; Delete until next keyword or end of line.
13558 (delete-region
13559 (match-beginning 0)
13560 (if (re-search-forward org-keyword-time-not-clock-regexp
13561 (line-end-position)
13563 (match-beginning 0)
13564 (line-end-position))))))
13565 ;; If there is nothing more to add and no more keyword
13566 ;; is left, remove the line completely.
13567 (if (and (org-looking-at-p "[ \t]*$") (not what))
13568 (delete-region (line-beginning-position)
13569 (line-beginning-position 2))
13570 ;; If we removed last keyword, do not leave trailing
13571 ;; white space at the end of line.
13572 (let ((p (point)))
13573 (save-excursion
13574 (end-of-line)
13575 (unless (= (skip-chars-backward " \t" p) 0)
13576 (delete-region (point) (line-end-position)))))))
13577 ((not what) (throw 'exit nil)) ; Nothing to do.
13578 (t (insert-before-markers "\n")
13579 (backward-char 1)
13580 (when org-adapt-indentation
13581 (org-indent-to-column (1+ (org-outline-level))))))
13582 (when what
13583 ;; Insert planning keyword.
13584 (insert (case what
13585 (closed org-closed-string)
13586 (deadline org-deadline-string)
13587 (scheduled org-scheduled-string)
13588 (otherwise (error "Invalid planning type: %s" what)))
13589 " ")
13590 ;; Insert associated timestamp.
13591 (let ((ts (org-insert-time-stamp
13592 time
13593 (or org-time-was-given
13594 (and (eq what 'closed) org-log-done-with-time))
13595 (eq what 'closed)
13596 nil nil (list org-end-time-was-given))))
13597 (unless (eolp) (insert " "))
13598 ts))))))
13600 (defvar org-log-note-marker (make-marker))
13601 (defvar org-log-note-purpose nil)
13602 (defvar org-log-note-state nil)
13603 (defvar org-log-note-previous-state nil)
13604 (defvar org-log-note-extra nil)
13605 (defvar org-log-note-window-configuration nil)
13606 (defvar org-log-note-return-to (make-marker))
13607 (defvar org-log-note-effective-time nil
13608 "Remembered current time so that dynamically scoped
13609 `org-extend-today-until' affects tha timestamps in state change
13610 log")
13612 (defvar org-log-post-message nil
13613 "Message to be displayed after a log note has been stored.
13614 The auto-repeater uses this.")
13616 (defun org-add-note ()
13617 "Add a note to the current entry.
13618 This is done in the same way as adding a state change note."
13619 (interactive)
13620 (org-add-log-setup 'note nil nil 'findpos nil))
13622 (defun org-log-beginning (&optional create)
13623 "Return expected start of log notes in current entry.
13624 When optional argument CREATE is non-nil, the function creates
13625 a drawer to store notes, if necessary. Returned position ignores
13626 narrowing."
13627 (org-with-wide-buffer
13628 (org-end-of-meta-data)
13629 (let ((end (if (org-at-heading-p) (point)
13630 (save-excursion (outline-next-heading) (point))))
13631 (drawer (org-log-into-drawer)))
13632 (cond
13633 (drawer
13634 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13635 (case-fold-search t))
13636 (catch 'exit
13637 ;; Try to find existing drawer.
13638 (while (re-search-forward regexp end t)
13639 (let ((element (org-element-at-point)))
13640 (when (eq (org-element-type element) 'drawer)
13641 (let ((cend (org-element-property :contents-end element)))
13642 (when (and (not org-log-states-order-reversed) cend)
13643 (goto-char cend)))
13644 (throw 'exit nil))))
13645 ;; No drawer found. Create one, if permitted.
13646 (when create
13647 (unless (bolp) (insert "\n"))
13648 (let ((beg (point)))
13649 (insert ":" drawer ":\n:END:\n")
13650 (org-indent-region beg (point)))
13651 (end-of-line -1)))))
13652 (org-log-state-notes-insert-after-drawers
13653 (while (and (looking-at org-drawer-regexp)
13654 (progn (goto-char (match-end 0))
13655 (re-search-forward org-property-end-re end t)))
13656 (forward-line)))))
13657 (if (bolp) (point) (line-beginning-position 2))))
13659 (defun org-add-log-setup (&optional purpose state prev-state findpos how extra)
13660 "Set up the post command hook to take a note.
13661 If this is about to TODO state change, the new state is expected in STATE.
13662 When FINDPOS is non-nil, find the correct position for the note in
13663 the current entry. If not, assume that it can be inserted at point.
13664 HOW is an indicator what kind of note should be created.
13665 EXTRA is additional text that will be inserted into the notes buffer."
13666 (org-with-wide-buffer
13667 (when findpos
13668 (goto-char (org-log-beginning t))
13669 (unless org-log-states-order-reversed
13670 (org-skip-over-state-notes)
13671 (skip-chars-backward " \t\n\r")
13672 (forward-line)))
13673 (move-marker org-log-note-marker (point))
13674 ;; Preserve position even if a property drawer is inserted in the
13675 ;; process.
13676 (set-marker-insertion-type org-log-note-marker t)
13677 (setq org-log-note-purpose purpose
13678 org-log-note-state state
13679 org-log-note-previous-state prev-state
13680 org-log-note-how how
13681 org-log-note-extra extra
13682 org-log-note-effective-time (org-current-effective-time))
13683 (add-hook 'post-command-hook 'org-add-log-note 'append)))
13685 (defun org-skip-over-state-notes ()
13686 "Skip past the list of State notes in an entry."
13687 (when (ignore-errors (goto-char (org-in-item-p)))
13688 (let* ((struct (org-list-struct))
13689 (prevs (org-list-prevs-alist struct))
13690 (regexp
13691 (concat "[ \t]*- +"
13692 (replace-regexp-in-string
13693 " +" " +"
13694 (org-replace-escapes
13695 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13696 `(("%d" . ,org-ts-regexp-inactive)
13697 ("%D" . ,org-ts-regexp)
13698 ("%s" . "\"\\S-+\"")
13699 ("%S" . "\"\\S-+\"")
13700 ("%t" . ,org-ts-regexp-inactive)
13701 ("%T" . ,org-ts-regexp)
13702 ("%u" . ".*?")
13703 ("%U" . ".*?")))))))
13704 (while (org-looking-at-p regexp)
13705 (goto-char (or (org-list-get-next-item (point) struct prevs)
13706 (org-list-get-item-end (point) struct)))))))
13708 (defun org-add-log-note (&optional purpose)
13709 "Pop up a window for taking a note, and add this note later at point."
13710 (remove-hook 'post-command-hook 'org-add-log-note)
13711 (setq org-log-note-window-configuration (current-window-configuration))
13712 (delete-other-windows)
13713 (move-marker org-log-note-return-to (point))
13714 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13715 (goto-char org-log-note-marker)
13716 (org-switch-to-buffer-other-window "*Org Note*")
13717 (erase-buffer)
13718 (if (memq org-log-note-how '(time state))
13719 (let (current-prefix-arg) (org-store-log-note))
13720 (let ((org-inhibit-startup t)) (org-mode))
13721 (insert (format "# Insert note for %s.
13722 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13723 (cond
13724 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13725 ((eq org-log-note-purpose 'done) "closed todo item")
13726 ((eq org-log-note-purpose 'state)
13727 (format "state change from \"%s\" to \"%s\""
13728 (or org-log-note-previous-state "")
13729 (or org-log-note-state "")))
13730 ((eq org-log-note-purpose 'reschedule)
13731 "rescheduling")
13732 ((eq org-log-note-purpose 'delschedule)
13733 "no longer scheduled")
13734 ((eq org-log-note-purpose 'redeadline)
13735 "changing deadline")
13736 ((eq org-log-note-purpose 'deldeadline)
13737 "removing deadline")
13738 ((eq org-log-note-purpose 'refile)
13739 "refiling")
13740 ((eq org-log-note-purpose 'note)
13741 "this entry")
13742 (t (error "This should not happen")))))
13743 (if org-log-note-extra (insert org-log-note-extra))
13744 (org-set-local 'org-finish-function 'org-store-log-note)
13745 (run-hooks 'org-log-buffer-setup-hook)))
13747 (defvar org-note-abort nil) ; dynamically scoped
13748 (defun org-store-log-note ()
13749 "Finish taking a log note, and insert it to where it belongs."
13750 (let ((txt (buffer-string)))
13751 (kill-buffer (current-buffer))
13752 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings))) lines)
13753 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13754 (setq txt (replace-match "" t t txt)))
13755 (if (string-match "\\s-+\\'" txt)
13756 (setq txt (replace-match "" t t txt)))
13757 (setq lines (org-split-string txt "\n"))
13758 (when (and note (string-match "\\S-" note))
13759 (setq note
13760 (org-replace-escapes
13761 note
13762 (list (cons "%u" (user-login-name))
13763 (cons "%U" user-full-name)
13764 (cons "%t" (format-time-string
13765 (org-time-stamp-format 'long 'inactive)
13766 org-log-note-effective-time))
13767 (cons "%T" (format-time-string
13768 (org-time-stamp-format 'long nil)
13769 org-log-note-effective-time))
13770 (cons "%d" (format-time-string
13771 (org-time-stamp-format nil 'inactive)
13772 org-log-note-effective-time))
13773 (cons "%D" (format-time-string
13774 (org-time-stamp-format nil nil)
13775 org-log-note-effective-time))
13776 (cons "%s" (cond
13777 ((not org-log-note-state) "")
13778 ((org-string-match-p org-ts-regexp
13779 org-log-note-state)
13780 (format "\"[%s]\""
13781 (substring org-log-note-state 1 -1)))
13782 (t (format "\"%s\"" org-log-note-state))))
13783 (cons "%S"
13784 (cond
13785 ((not org-log-note-previous-state) "")
13786 ((org-string-match-p org-ts-regexp
13787 org-log-note-previous-state)
13788 (format "\"[%s]\""
13789 (substring
13790 org-log-note-previous-state 1 -1)))
13791 (t (format "\"%s\""
13792 org-log-note-previous-state)))))))
13793 (when lines (setq note (concat note " \\\\")))
13794 (push note lines))
13795 (when (or current-prefix-arg org-note-abort)
13796 (when (org-log-into-drawer)
13797 (org-remove-empty-drawer-at org-log-note-marker))
13798 (setq lines nil))
13799 (when lines
13800 (with-current-buffer (marker-buffer org-log-note-marker)
13801 (org-with-wide-buffer
13802 (goto-char org-log-note-marker)
13803 (move-marker org-log-note-marker nil)
13804 ;; Make sure point is at the beginning of an empty line.
13805 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13806 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13807 ;; In an existing list, add a new item at the top level.
13808 ;; Otherwise, indent line like a regular one.
13809 (let ((itemp (org-in-item-p)))
13810 (if itemp
13811 (org-indent-line-to
13812 (let ((struct (save-excursion
13813 (goto-char itemp) (org-list-struct))))
13814 (org-list-get-ind (org-list-get-top-point struct) struct)))
13815 (org-indent-line)))
13816 (insert (org-list-bullet-string "-") (pop lines))
13817 (let ((ind (org-list-item-body-column (line-beginning-position))))
13818 (dolist (line lines)
13819 (insert "\n")
13820 (org-indent-line-to ind)
13821 (insert line)))
13822 (message "Note stored")
13823 (org-back-to-heading t)
13824 (org-cycle-hide-drawers 'children))
13825 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13826 ;; from within `org-add-log-note' because `buffer-undo-list'
13827 ;; is then modified outside of `org-with-remote-undo'.
13828 (when (eq this-command 'org-agenda-todo)
13829 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13830 ;; Don't add undo information when called from `org-agenda-todo'
13831 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13832 (set-window-configuration org-log-note-window-configuration)
13833 (with-current-buffer (marker-buffer org-log-note-return-to)
13834 (goto-char org-log-note-return-to))
13835 (move-marker org-log-note-return-to nil)
13836 (and org-log-post-message (message "%s" org-log-post-message))))
13838 (defun org-remove-empty-drawer-at (pos)
13839 "Remove an empty drawer at position POS.
13840 POS may also be a marker."
13841 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13842 (org-with-wide-buffer
13843 (goto-char pos)
13844 (let ((drawer (org-element-at-point)))
13845 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13846 (not (org-element-property :contents-begin drawer)))
13847 (delete-region (org-element-property :begin drawer)
13848 (progn (goto-char (org-element-property :end drawer))
13849 (skip-chars-backward " \r\t\n")
13850 (forward-line)
13851 (point))))))))
13853 (defvar org-ts-type nil)
13854 (defun org-sparse-tree (&optional arg type)
13855 "Create a sparse tree, prompt for the details.
13856 This command can create sparse trees. You first need to select the type
13857 of match used to create the tree:
13859 t Show all TODO entries.
13860 T Show entries with a specific TODO keyword.
13861 m Show entries selected by a tags/property match.
13862 p Enter a property name and its value (both with completion on existing
13863 names/values) and show entries with that property.
13864 r Show entries matching a regular expression (`/' can be used as well).
13865 b Show deadlines and scheduled items before a date.
13866 a Show deadlines and scheduled items after a date.
13867 d Show deadlines due within `org-deadline-warning-days'.
13868 D Show deadlines and scheduled items between a date range."
13869 (interactive "P")
13870 (setq type (or type org-sparse-tree-default-date-type))
13871 (setq org-ts-type type)
13872 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13873 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13874 [c]ycle through date types: %s"
13875 (case type
13876 (all "all timestamps")
13877 (scheduled "only scheduled")
13878 (deadline "only deadline")
13879 (active "only active timestamps")
13880 (inactive "only inactive timestamps")
13881 (closed "with a closed time-stamp")
13882 (otherwise "scheduled/deadline")))
13883 (let ((answer (read-char-exclusive)))
13884 (case answer
13886 (org-sparse-tree
13888 (cadr
13889 (memq type '(nil all scheduled deadline active inactive closed)))))
13890 (?d (call-interactively 'org-check-deadlines))
13891 (?b (call-interactively 'org-check-before-date))
13892 (?a (call-interactively 'org-check-after-date))
13893 (?D (call-interactively 'org-check-dates-range))
13894 (?t (call-interactively 'org-show-todo-tree))
13895 (?T (org-show-todo-tree '(4)))
13896 (?m (call-interactively 'org-match-sparse-tree))
13897 ((?p ?P)
13898 (let* ((kwd (org-icompleting-read
13899 "Property: " (mapcar 'list (org-buffer-property-keys))))
13900 (value (org-icompleting-read
13901 "Value: " (mapcar 'list (org-property-values kwd)))))
13902 (unless (string-match "\\`{.*}\\'" value)
13903 (setq value (concat "\"" value "\"")))
13904 (org-match-sparse-tree arg (concat kwd "=" value))))
13905 ((?r ?R ?/) (call-interactively 'org-occur))
13906 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13908 (defvar org-occur-highlights nil
13909 "List of overlays used for occur matches.")
13910 (make-variable-buffer-local 'org-occur-highlights)
13911 (defvar org-occur-parameters nil
13912 "Parameters of the active org-occur calls.
13913 This is a list, each call to org-occur pushes as cons cell,
13914 containing the regular expression and the callback, onto the list.
13915 The list can contain several entries if `org-occur' has been called
13916 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13917 will only contain one set of parameters. When the highlights are
13918 removed (for example with `C-c C-c', or with the next edit (depending
13919 on `org-remove-highlights-with-change'), this variable is emptied
13920 as well.")
13921 (make-variable-buffer-local 'org-occur-parameters)
13923 (defun org-occur (regexp &optional keep-previous callback)
13924 "Make a compact tree which shows all matches of REGEXP.
13925 The tree will show the lines where the regexp matches, and all higher
13926 headlines above the match. It will also show the heading after the match,
13927 to make sure editing the matching entry is easy.
13928 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13929 call to `org-occur' will be kept, to allow stacking of calls to this
13930 command.
13931 If CALLBACK is non-nil, it is a function which is called to confirm
13932 that the match should indeed be shown."
13933 (interactive "sRegexp: \nP")
13934 (when (equal regexp "")
13935 (user-error "Regexp cannot be empty"))
13936 (unless keep-previous
13937 (org-remove-occur-highlights nil nil t))
13938 (push (cons regexp callback) org-occur-parameters)
13939 (let ((cnt 0))
13940 (save-excursion
13941 (goto-char (point-min))
13942 (if (or (not keep-previous) ; do not want to keep
13943 (not org-occur-highlights)) ; no previous matches
13944 ;; hide everything
13945 (org-overview))
13946 (while (re-search-forward regexp nil t)
13947 (backward-char) ;; FIXME: Match timestamps at the end of a headline
13948 (when (or (not callback)
13949 (save-match-data (funcall callback)))
13950 (setq cnt (1+ cnt))
13951 (when org-highlight-sparse-tree-matches
13952 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13953 (org-show-context 'occur-tree))))
13954 (when org-remove-highlights-with-change
13955 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13956 nil 'local))
13957 (unless org-sparse-tree-open-archived-trees
13958 (org-hide-archived-subtrees (point-min) (point-max)))
13959 (run-hooks 'org-occur-hook)
13960 (if (org-called-interactively-p 'interactive)
13961 (message "%d match(es) for regexp %s" cnt regexp))
13962 cnt))
13964 (defun org-occur-next-match (&optional n reset)
13965 "Function for `next-error-function' to find sparse tree matches.
13966 N is the number of matches to move, when negative move backwards.
13967 RESET is entirely ignored - this function always goes back to the
13968 starting point when no match is found."
13969 (let* ((limit (if (< n 0) (point-min) (point-max)))
13970 (search-func (if (< n 0)
13971 'previous-single-char-property-change
13972 'next-single-char-property-change))
13973 (n (abs n))
13974 (pos (point))
13976 (catch 'exit
13977 (while (setq p1 (funcall search-func (point) 'org-type))
13978 (when (equal p1 limit)
13979 (goto-char pos)
13980 (user-error "No more matches"))
13981 (when (equal (get-char-property p1 'org-type) 'org-occur)
13982 (setq n (1- n))
13983 (when (= n 0)
13984 (goto-char p1)
13985 (throw 'exit (point))))
13986 (goto-char p1))
13987 (goto-char p1)
13988 (user-error "No more matches"))))
13990 (defun org-show-context (&optional key)
13991 "Make sure point and context are visible.
13992 Optional argument KEY, when non-nil, is a symbol. See
13993 `org-show-context-detail' for allowed values and how much is to
13994 be shown."
13995 (org-show-set-visibility
13996 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13997 ((cdr (assq key org-show-context-detail)))
13998 (t (cdr (assq 'default org-show-context-detail))))))
14000 (defun org-show-set-visibility (detail)
14001 "Set visibility around point according to DETAIL.
14002 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14003 `tree', `canonical' or t. See `org-show-context-detail' for more
14004 information."
14005 (unless (org-before-first-heading-p)
14006 ;; Show current heading and possibly its entry, following headline
14007 ;; or all children.
14008 (if (and (org-at-heading-p) (not (eq detail 'local)))
14009 (org-flag-heading nil)
14010 (org-show-entry)
14011 (org-with-limited-levels
14012 (case detail
14013 ((tree canonical t) (org-show-children))
14014 ((nil minimal ancestors))
14015 (t (save-excursion
14016 (outline-next-heading)
14017 (org-flag-heading nil))))))
14018 ;; Show all siblings.
14019 (when (eq detail 'lineage) (org-show-siblings))
14020 ;; Show ancestors, possibly with their children.
14021 (when (memq detail '(ancestors lineage tree canonical t))
14022 (save-excursion
14023 (while (org-up-heading-safe)
14024 (org-flag-heading nil)
14025 (when (memq detail '(canonical t)) (org-show-entry))
14026 (when (memq detail '(tree canonical t)) (org-show-children)))))))
14028 (defvar org-reveal-start-hook nil
14029 "Hook run before revealing a location.")
14031 (defun org-reveal (&optional siblings)
14032 "Show current entry, hierarchy above it, and the following headline.
14034 This can be used to show a consistent set of context around
14035 locations exposed with `org-show-context'.
14037 With optional argument SIBLINGS, on each level of the hierarchy all
14038 siblings are shown. This repairs the tree structure to what it would
14039 look like when opened with hierarchical calls to `org-cycle'.
14041 With double optional argument \\[universal-argument] \\[universal-argument], \
14042 go to the parent and show the
14043 entire tree."
14044 (interactive "P")
14045 (run-hooks 'org-reveal-start-hook)
14046 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14047 ((equal siblings '(16))
14048 (save-excursion
14049 (when (org-up-heading-safe)
14050 (org-show-subtree)
14051 (run-hook-with-args 'org-cycle-hook 'subtree))))
14052 (t (org-show-set-visibility 'lineage))))
14054 (defun org-highlight-new-match (beg end)
14055 "Highlight from BEG to END and mark the highlight is an occur headline."
14056 (let ((ov (make-overlay beg end)))
14057 (overlay-put ov 'face 'secondary-selection)
14058 (overlay-put ov 'org-type 'org-occur)
14059 (push ov org-occur-highlights)))
14061 (defun org-remove-occur-highlights (&optional beg end noremove)
14062 "Remove the occur highlights from the buffer.
14063 BEG and END are ignored. If NOREMOVE is nil, remove this function
14064 from the `before-change-functions' in the current buffer."
14065 (interactive)
14066 (unless org-inhibit-highlight-removal
14067 (mapc 'delete-overlay org-occur-highlights)
14068 (setq org-occur-highlights nil)
14069 (setq org-occur-parameters nil)
14070 (unless noremove
14071 (remove-hook 'before-change-functions
14072 'org-remove-occur-highlights 'local))))
14074 ;;;; Priorities
14076 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14077 "Regular expression matching the priority indicator.")
14079 (defvar org-remove-priority-next-time nil)
14081 (defun org-priority-up ()
14082 "Increase the priority of the current item."
14083 (interactive)
14084 (org-priority 'up))
14086 (defun org-priority-down ()
14087 "Decrease the priority of the current item."
14088 (interactive)
14089 (org-priority 'down))
14091 (defun org-priority (&optional action show)
14092 "Change the priority of an item.
14093 ACTION can be `set', `up', `down', or a character."
14094 (interactive "P")
14095 (if (equal action '(4))
14096 (org-show-priority)
14097 (unless org-enable-priority-commands
14098 (user-error "Priority commands are disabled"))
14099 (setq action (or action 'set))
14100 (let (current new news have remove)
14101 (save-excursion
14102 (org-back-to-heading t)
14103 (if (looking-at org-priority-regexp)
14104 (setq current (string-to-char (match-string 2))
14105 have t))
14106 (cond
14107 ((eq action 'remove)
14108 (setq remove t new ?\ ))
14109 ((or (eq action 'set)
14110 (if (featurep 'xemacs) (characterp action) (integerp action)))
14111 (if (not (eq action 'set))
14112 (setq new action)
14113 (message "Priority %c-%c, SPC to remove: "
14114 org-highest-priority org-lowest-priority)
14115 (save-match-data
14116 (setq new (read-char-exclusive))))
14117 (if (and (= (upcase org-highest-priority) org-highest-priority)
14118 (= (upcase org-lowest-priority) org-lowest-priority))
14119 (setq new (upcase new)))
14120 (cond ((equal new ?\ ) (setq remove t))
14121 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14122 (user-error "Priority must be between `%c' and `%c'"
14123 org-highest-priority org-lowest-priority))))
14124 ((eq action 'up)
14125 (setq new (if have
14126 (1- current) ; normal cycling
14127 ;; last priority was empty
14128 (if (eq last-command this-command)
14129 org-lowest-priority ; wrap around empty to lowest
14130 ;; default
14131 (if org-priority-start-cycle-with-default
14132 org-default-priority
14133 (1- org-default-priority))))))
14134 ((eq action 'down)
14135 (setq new (if have
14136 (1+ current) ; normal cycling
14137 ;; last priority was empty
14138 (if (eq last-command this-command)
14139 org-highest-priority ; wrap around empty to highest
14140 ;; default
14141 (if org-priority-start-cycle-with-default
14142 org-default-priority
14143 (1+ org-default-priority))))))
14144 (t (user-error "Invalid action")))
14145 (if (or (< (upcase new) org-highest-priority)
14146 (> (upcase new) org-lowest-priority))
14147 (if (and (memq action '(up down))
14148 (not have) (not (eq last-command this-command)))
14149 ;; `new' is from default priority
14150 (error
14151 "The default can not be set, see `org-default-priority' why")
14152 ;; normal cycling: `new' is beyond highest/lowest priority
14153 ;; and is wrapped around to the empty priority
14154 (setq remove t)))
14155 (setq news (format "%c" new))
14156 (if have
14157 (if remove
14158 (replace-match "" t t nil 1)
14159 (replace-match news t t nil 2))
14160 (if remove
14161 (user-error "No priority cookie found in line")
14162 (let ((case-fold-search nil))
14163 (looking-at org-todo-line-regexp))
14164 (if (match-end 2)
14165 (progn
14166 (goto-char (match-end 2))
14167 (insert " [#" news "]"))
14168 (goto-char (match-beginning 3))
14169 (insert "[#" news "] "))))
14170 (org-set-tags nil 'align))
14171 (if remove
14172 (message "Priority removed")
14173 (message "Priority of current item set to %s" news)))))
14175 (defun org-show-priority ()
14176 "Show the priority of the current item.
14177 This priority is composed of the main priority given with the [#A] cookies,
14178 and by additional input from the age of a schedules or deadline entry."
14179 (interactive)
14180 (let ((pri (if (eq major-mode 'org-agenda-mode)
14181 (org-get-at-bol 'priority)
14182 (save-excursion
14183 (save-match-data
14184 (beginning-of-line)
14185 (and (looking-at org-heading-regexp)
14186 (org-get-priority (match-string 0))))))))
14187 (message "Priority is %d" (if pri pri -1000))))
14189 (defun org-get-priority (s)
14190 "Find priority cookie and return priority."
14191 (save-match-data
14192 (if (functionp org-get-priority-function)
14193 (funcall org-get-priority-function)
14194 (if (not (string-match org-priority-regexp s))
14195 (* 1000 (- org-lowest-priority org-default-priority))
14196 (* 1000 (- org-lowest-priority
14197 (string-to-char (match-string 2 s))))))))
14199 ;;;; Tags
14201 (defvar org-agenda-archives-mode)
14202 (defvar org-map-continue-from nil
14203 "Position from where mapping should continue.
14204 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14206 (defvar org-scanner-tags nil
14207 "The current tag list while the tags scanner is running.")
14208 (defvar org-trust-scanner-tags nil
14209 "Should `org-get-tags-at' use the tags for the scanner.
14210 This is for internal dynamical scoping only.
14211 When this is non-nil, the function `org-get-tags-at' will return the value
14212 of `org-scanner-tags' instead of building the list by itself. This
14213 can lead to large speed-ups when the tags scanner is used in a file with
14214 many entries, and when the list of tags is retrieved, for example to
14215 obtain a list of properties. Building the tags list for each entry in such
14216 a file becomes an N^2 operation - but with this variable set, it scales
14217 as N.")
14219 (defun org-scan-tags (action matcher todo-only &optional start-level)
14220 "Scan headline tags with inheritance and produce output ACTION.
14222 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14223 or `agenda' to produce an entry list for an agenda view. It can also be
14224 a Lisp form or a function that should be called at each matched headline, in
14225 this case the return value is a list of all return values from these calls.
14227 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
14228 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
14229 only lines with a not-done TODO keyword are included in the output.
14230 This should be the same variable that was scoped into
14231 and set by `org-make-tags-matcher' when it constructed MATCHER.
14233 START-LEVEL can be a string with asterisks, reducing the scope to
14234 headlines matching this string."
14235 (require 'org-agenda)
14236 (let* ((re (concat "^"
14237 (if start-level
14238 ;; Get the correct level to match
14239 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14240 org-outline-regexp)
14241 " *\\(\\<\\("
14242 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14243 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14244 (props (list 'face 'default
14245 'done-face 'org-agenda-done
14246 'undone-face 'default
14247 'mouse-face 'highlight
14248 'org-not-done-regexp org-not-done-regexp
14249 'org-todo-regexp org-todo-regexp
14250 'org-complex-heading-regexp org-complex-heading-regexp
14251 'help-echo
14252 (format "mouse-2 or RET jump to org file %s"
14253 (abbreviate-file-name
14254 (or (buffer-file-name (buffer-base-buffer))
14255 (buffer-name (buffer-base-buffer)))))))
14256 (org-map-continue-from nil)
14257 lspos tags tags-list
14258 (tags-alist (list (cons 0 org-file-tags)))
14259 (llast 0) rtn rtn1 level category i txt
14260 todo marker entry priority
14261 ts-date ts-date-type ts-date-pair)
14262 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
14263 (setq action (list 'lambda nil action)))
14264 (save-excursion
14265 (goto-char (point-min))
14266 (when (eq action 'sparse-tree)
14267 (org-overview)
14268 (org-remove-occur-highlights))
14269 (while (let (case-fold-search)
14270 (re-search-forward re nil t))
14271 (setq org-map-continue-from nil)
14272 (catch :skip
14273 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14274 tags (if (match-end 4) (org-match-string-no-properties 4)))
14275 (goto-char (setq lspos (match-beginning 0)))
14276 (setq level (org-reduced-level (org-outline-level))
14277 category (org-get-category))
14278 (when (eq action 'agenda)
14279 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14280 ts-date (car ts-date-pair)
14281 ts-date-type (cdr ts-date-pair)))
14282 (setq i llast llast level)
14283 ;; remove tag lists from same and sublevels
14284 (while (>= i level)
14285 (when (setq entry (assoc i tags-alist))
14286 (setq tags-alist (delete entry tags-alist)))
14287 (setq i (1- i)))
14288 ;; add the next tags
14289 (when tags
14290 (setq tags (org-split-string tags ":")
14291 tags-alist
14292 (cons (cons level tags) tags-alist)))
14293 ;; compile tags for current headline
14294 (setq tags-list
14295 (if org-use-tag-inheritance
14296 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14297 tags)
14298 org-scanner-tags tags-list)
14299 (when org-use-tag-inheritance
14300 (setcdr (car tags-alist)
14301 (mapcar (lambda (x)
14302 (setq x (copy-sequence x))
14303 (org-add-prop-inherited x))
14304 (cdar tags-alist))))
14305 (when (and tags org-use-tag-inheritance
14306 (or (not (eq t org-use-tag-inheritance))
14307 org-tags-exclude-from-inheritance))
14308 ;; selective inheritance, remove uninherited ones
14309 (setcdr (car tags-alist)
14310 (org-remove-uninherited-tags (cdar tags-alist))))
14311 (when (and
14313 ;; eval matcher only when the todo condition is OK
14314 (and (or (not todo-only) (member todo org-not-done-keywords))
14315 (let ((case-fold-search t) (org-trust-scanner-tags t))
14316 (eval matcher)))
14318 ;; Call the skipper, but return t if it does not skip,
14319 ;; so that the `and' form continues evaluating
14320 (progn
14321 (unless (eq action 'sparse-tree) (org-agenda-skip))
14324 ;; Check if timestamps are deselecting this entry
14325 (or (not todo-only)
14326 (and (member todo org-not-done-keywords)
14327 (or (not org-agenda-tags-todo-honor-ignore-options)
14328 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14330 ;; select this headline
14331 (cond
14332 ((eq action 'sparse-tree)
14333 (and org-highlight-sparse-tree-matches
14334 (org-get-heading) (match-end 0)
14335 (org-highlight-new-match
14336 (match-beginning 1) (match-end 1)))
14337 (org-show-context 'tags-tree))
14338 ((eq action 'agenda)
14339 (setq txt (org-agenda-format-item
14341 (concat
14342 (if (eq org-tags-match-list-sublevels 'indented)
14343 (make-string (1- level) ?.) "")
14344 (org-get-heading))
14345 (make-string level ?\s)
14346 category
14347 tags-list)
14348 priority (org-get-priority txt))
14349 (goto-char lspos)
14350 (setq marker (org-agenda-new-marker))
14351 (org-add-props txt props
14352 'org-marker marker 'org-hd-marker marker 'org-category category
14353 'todo-state todo
14354 'ts-date ts-date
14355 'priority priority
14356 'type (concat "tagsmatch" ts-date-type))
14357 (push txt rtn))
14358 ((functionp action)
14359 (setq org-map-continue-from nil)
14360 (save-excursion
14361 (setq rtn1 (funcall action))
14362 (push rtn1 rtn)))
14363 (t (user-error "Invalid action")))
14365 ;; if we are to skip sublevels, jump to end of subtree
14366 (unless org-tags-match-list-sublevels
14367 (org-end-of-subtree t)
14368 (backward-char 1))))
14369 ;; Get the correct position from where to continue
14370 (if org-map-continue-from
14371 (goto-char org-map-continue-from)
14372 (and (= (point) lspos) (end-of-line 1)))))
14373 (when (and (eq action 'sparse-tree)
14374 (not org-sparse-tree-open-archived-trees))
14375 (org-hide-archived-subtrees (point-min) (point-max)))
14376 (nreverse rtn)))
14378 (defun org-remove-uninherited-tags (tags)
14379 "Remove all tags that are not inherited from the list TAGS."
14380 (cond
14381 ((eq org-use-tag-inheritance t)
14382 (if org-tags-exclude-from-inheritance
14383 (org-delete-all org-tags-exclude-from-inheritance tags)
14384 tags))
14385 ((not org-use-tag-inheritance) nil)
14386 ((stringp org-use-tag-inheritance)
14387 (delq nil (mapcar
14388 (lambda (x)
14389 (if (and (string-match org-use-tag-inheritance x)
14390 (not (member x org-tags-exclude-from-inheritance)))
14391 x nil))
14392 tags)))
14393 ((listp org-use-tag-inheritance)
14394 (delq nil (mapcar
14395 (lambda (x)
14396 (if (member x org-use-tag-inheritance) x nil))
14397 tags)))))
14399 (defun org-match-sparse-tree (&optional todo-only match)
14400 "Create a sparse tree according to tags string MATCH.
14401 MATCH can contain positive and negative selection of tags, like
14402 \"+WORK+URGENT-WITHBOSS\".
14403 If optional argument TODO-ONLY is non-nil, only select lines that are
14404 also TODO lines."
14405 (interactive "P")
14406 (org-agenda-prepare-buffers (list (current-buffer)))
14407 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14409 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14411 (defvar org-cached-props nil)
14412 (defun org-cached-entry-get (pom property)
14413 (if (or (eq t org-use-property-inheritance)
14414 (and (stringp org-use-property-inheritance)
14415 (let ((case-fold-search t))
14416 (org-string-match-p org-use-property-inheritance property)))
14417 (and (listp org-use-property-inheritance)
14418 (member-ignore-case property org-use-property-inheritance)))
14419 ;; Caching is not possible, check it directly.
14420 (org-entry-get pom property 'inherit)
14421 ;; Get all properties, so we can do complicated checks easily.
14422 (cdr (assoc-string property
14423 (or org-cached-props
14424 (setq org-cached-props (org-entry-properties pom)))
14425 t))))
14427 (defun org-global-tags-completion-table (&optional files)
14428 "Return the list of all tags in all agenda buffer/files.
14429 Optional FILES argument is a list of files which can be used
14430 instead of the agenda files."
14431 (save-excursion
14432 (org-uniquify
14433 (delq nil
14434 (apply 'append
14435 (mapcar
14436 (lambda (file)
14437 (set-buffer (find-file-noselect file))
14438 (append (org-get-buffer-tags)
14439 (mapcar (lambda (x) (if (stringp (car-safe x))
14440 (list (car-safe x)) nil))
14441 org-tag-alist)))
14442 (if (and files (car files))
14443 files
14444 (org-agenda-files))))))))
14446 (defun org-make-tags-matcher (match)
14447 "Create the TAGS/TODO matcher form for the selection string MATCH.
14449 The variable `todo-only' is scoped dynamically into this function.
14450 It will be set to t if the matcher restricts matching to TODO entries,
14451 otherwise will not be touched.
14453 Returns a cons of the selection string MATCH and the constructed
14454 lisp form implementing the matcher. The matcher is to be evaluated
14455 at an Org entry, with point on the headline, and returns t if the
14456 entry matches the selection string MATCH. The returned lisp form
14457 references two variables with information about the entry, which
14458 must be bound around the form's evaluation: todo, the TODO keyword
14459 at the entry (or nil of none); and tags-list, the list of all tags
14460 at the entry including inherited ones. Additionally, the category
14461 of the entry (if any) must be specified as the text property
14462 `org-category' on the headline.
14464 See also `org-scan-tags'.
14466 (declare (special todo-only))
14467 (unless (boundp 'todo-only)
14468 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14469 (unless match
14470 ;; Get a new match request, with completion against the global
14471 ;; tags table and the local tags in current buffer
14472 (let ((org-last-tags-completion-table
14473 (org-uniquify
14474 (delq nil (append (org-get-buffer-tags)
14475 (org-global-tags-completion-table))))))
14476 (setq match (org-completing-read-no-i
14477 "Match: " 'org-tags-completion-function nil nil nil
14478 'org-tags-history))))
14480 ;; Parse the string and create a lisp form
14481 (let ((match0 match)
14482 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14483 minus tag mm
14484 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14485 orterms term orlist re-p str-p level-p level-op time-p
14486 prop-p pn pv po gv rest (start 0) (ss 0))
14487 ;; Expand group tags
14488 (setq match (org-tags-expand match))
14490 ;; Check if there is a TODO part of this match, which would be the
14491 ;; part after a "/". TO make sure that this slash is not part of
14492 ;; a property value to be matched against, we also check that there
14493 ;; is no " after that slash.
14494 ;; First, find the last slash
14495 (while (string-match "/+" match ss)
14496 (setq start (match-beginning 0) ss (match-end 0)))
14497 (if (and (string-match "/+" match start)
14498 (not (save-match-data (string-match "\"" match start))))
14499 ;; match contains also a todo-matching request
14500 (progn
14501 (setq tagsmatch (substring match 0 (match-beginning 0))
14502 todomatch (substring match (match-end 0)))
14503 (if (string-match "^!" todomatch)
14504 (setq todo-only t todomatch (substring todomatch 1)))
14505 (if (string-match "^\\s-*$" todomatch)
14506 (setq todomatch nil)))
14507 ;; only matching tags
14508 (setq tagsmatch match todomatch nil))
14510 ;; Make the tags matcher
14511 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14512 (setq tagsmatcher t)
14513 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14514 (while (setq term (pop orterms))
14515 (while (and (equal (substring term -1) "\\") orterms)
14516 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14517 (while (string-match re term)
14518 (setq rest (substring term (match-end 0))
14519 minus (and (match-end 1)
14520 (equal (match-string 1 term) "-"))
14521 tag (save-match-data (replace-regexp-in-string
14522 "\\\\-" "-"
14523 (match-string 2 term)))
14524 re-p (equal (string-to-char tag) ?{)
14525 level-p (match-end 4)
14526 prop-p (match-end 5)
14527 mm (cond
14528 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14529 (level-p
14530 (setq level-op (org-op-to-function (match-string 3 term)))
14531 `(,level-op level ,(string-to-number
14532 (match-string 4 term))))
14533 (prop-p
14534 (setq pn (match-string 5 term)
14535 po (match-string 6 term)
14536 pv (match-string 7 term)
14537 re-p (equal (string-to-char pv) ?{)
14538 str-p (equal (string-to-char pv) ?\")
14539 time-p (save-match-data
14540 (string-match "^\"[[<].*[]>]\"$" pv))
14541 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14542 (if time-p (setq pv (org-matcher-time pv)))
14543 (setq po (org-op-to-function po (if time-p 'time str-p)))
14544 (cond
14545 ((equal pn "CATEGORY")
14546 (setq gv '(get-text-property (point) 'org-category)))
14547 ((equal pn "TODO")
14548 (setq gv 'todo))
14550 (setq gv `(org-cached-entry-get nil ,pn))))
14551 (if re-p
14552 (if (eq po 'org<>)
14553 `(not (string-match ,pv (or ,gv "")))
14554 `(string-match ,pv (or ,gv "")))
14555 (if str-p
14556 `(,po (or ,gv "") ,pv)
14557 `(,po (string-to-number (or ,gv ""))
14558 ,(string-to-number pv) ))))
14559 (t `(member ,tag tags-list)))
14560 mm (if minus (list 'not mm) mm)
14561 term rest)
14562 (push mm tagsmatcher))
14563 (push (if (> (length tagsmatcher) 1)
14564 (cons 'and tagsmatcher)
14565 (car tagsmatcher))
14566 orlist)
14567 (setq tagsmatcher nil))
14568 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14569 (setq tagsmatcher
14570 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14571 ;; Make the todo matcher
14572 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14573 (setq todomatcher t)
14574 (setq orterms (org-split-string todomatch "|") orlist nil)
14575 (dolist (term orterms)
14576 (while (string-match re term)
14577 (setq minus (and (match-end 1)
14578 (equal (match-string 1 term) "-"))
14579 kwd (match-string 2 term)
14580 re-p (equal (string-to-char kwd) ?{)
14581 term (substring term (match-end 0))
14582 mm (if re-p
14583 `(string-match ,(substring kwd 1 -1) todo)
14584 (list 'equal 'todo kwd))
14585 mm (if minus (list 'not mm) mm))
14586 (push mm todomatcher))
14587 (push (if (> (length todomatcher) 1)
14588 (cons 'and todomatcher)
14589 (car todomatcher))
14590 orlist)
14591 (setq todomatcher nil))
14592 (setq todomatcher (if (> (length orlist) 1)
14593 (cons 'or orlist) (car orlist))))
14595 ;; Return the string and lisp forms of the matcher
14596 (setq matcher (if todomatcher
14597 (list 'and tagsmatcher todomatcher)
14598 tagsmatcher))
14599 (when todo-only
14600 (setq matcher (list 'and '(member todo org-not-done-keywords)
14601 matcher)))
14602 (cons match0 matcher)))
14604 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14605 "Expand group tags in MATCH.
14607 This replaces every group tag in MATCH with a regexp tag search.
14608 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14609 will be replaced like this:
14611 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14612 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14613 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14615 Replacing by a regexp preserves the structure of the match.
14616 E.g., this expansion
14618 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14620 will match anything tagged with \"Lab\" and \"Home\", or tagged
14621 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14623 A group tag in MATCH can contain regular expressions of its own.
14624 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14625 will be replaced like this:
14627 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14629 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14630 assumed to be a single group tag, and the function will return
14631 the list of tags in this group.
14633 When DOWNCASE is non-nil, expand downcased TAGS."
14634 (if org-group-tags
14635 (let* ((case-fold-search t)
14636 (stable org-mode-syntax-table)
14637 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14638 (taggroups (if downcased
14639 (mapcar (lambda (tg) (mapcar #'downcase tg))
14640 taggroups)
14641 taggroups))
14642 (taggroups-keys (mapcar #'car taggroups))
14643 (return-match (if downcased (downcase match) match))
14644 (count 0)
14645 (work-already-expanded tags-already-expanded)
14646 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14647 ;; @ and _ are allowed as word-components in tags.
14648 (modify-syntax-entry ?@ "w" stable)
14649 (modify-syntax-entry ?_ "w" stable)
14650 ;; Temporarily replace regexp-expressions in the match-expression.
14651 (while (string-match "{.+?}" return-match)
14652 (incf count)
14653 (push (match-string 0 return-match) regexps-in-match)
14654 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14655 (while (and taggroups-keys
14656 (with-syntax-table stable
14657 (string-match
14658 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14659 (regexp-opt taggroups-keys) "\\>\\)")
14660 return-match)))
14661 (let* ((dir (match-string 1 return-match))
14662 (tag (match-string 2 return-match))
14663 (tag (if downcased (downcase tag) tag)))
14664 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14665 (member tag work-already-expanded))
14666 (setq tags-in-group (assoc tag taggroups))
14667 (push tag work-already-expanded)
14668 ;; Recursively expand each tag in the group, if the tag hasn't
14669 ;; already been expanded. Restore the match-data after all recursive calls.
14670 (save-match-data
14671 (let (tags-expanded)
14672 (dolist (x (cdr tags-in-group))
14673 (if (and (member x taggroups-keys)
14674 (not (member x work-already-expanded)))
14675 (setq tags-expanded
14676 (delete-dups
14677 (append
14678 (org-tags-expand x t downcased
14679 work-already-expanded)
14680 tags-expanded)))
14681 (setq tags-expanded
14682 (append (list x) tags-expanded)))
14683 (setq work-already-expanded
14684 (delete-dups
14685 (append tags-expanded
14686 work-already-expanded))))
14687 (setq tags-in-group
14688 (delete-dups (cons (car tags-in-group)
14689 tags-expanded)))))
14690 ;; Filter tag-regexps from tags.
14691 (setq regexp-in-group-escaped
14692 (delq nil (mapcar (lambda (x)
14693 (if (stringp x)
14694 (and (equal "{" (substring x 0 1))
14695 (equal "}" (substring x -1))
14698 tags-in-group))
14699 regexp-in-group
14700 (mapcar (lambda (x)
14701 (substring x 1 -1))
14702 regexp-in-group-escaped)
14703 tags-in-group
14704 (delq nil (mapcar (lambda (x)
14705 (if (stringp x)
14706 (and (not (equal "{" (substring x 0 1)))
14707 (not (equal "}" (substring x -1)))
14710 tags-in-group)))
14711 ;; If single-as-list, do no more in the while-loop.
14712 (if (not single-as-list)
14713 (progn
14714 (when regexp-in-group
14715 (setq regexp-in-group
14716 (concat "\\|"
14717 (mapconcat 'identity regexp-in-group
14718 "\\|"))))
14719 (setq tags-in-group
14720 (concat dir
14721 "{\\<"
14722 (regexp-opt tags-in-group)
14723 "\\>"
14724 regexp-in-group
14725 "}"))
14726 (when (stringp tags-in-group)
14727 (org-add-props tags-in-group '(grouptag t)))
14728 (setq return-match
14729 (replace-match tags-in-group t t return-match)))
14730 (setq tags-in-group
14731 (append regexp-in-group-escaped tags-in-group))))
14732 (setq taggroups-keys (delete tag taggroups-keys))))
14733 ;; Add the regular expressions back into the match-expression again.
14734 (while regexps-in-match
14735 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14736 (pop regexps-in-match)
14737 return-match t t))
14738 (decf count))
14739 (if single-as-list
14740 (if tags-in-group tags-in-group (list return-match))
14741 return-match))
14742 (if single-as-list
14743 (list (if downcased (downcase match) match))
14744 match)))
14746 (defun org-op-to-function (op &optional stringp)
14747 "Turn an operator into the appropriate function."
14748 (setq op
14749 (cond
14750 ((equal op "<" ) '(< string< org-time<))
14751 ((equal op ">" ) '(> org-string> org-time>))
14752 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14753 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14754 ((member op '("=" "==")) '(= string= org-time=))
14755 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14756 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14758 (defun org<> (a b) (not (= a b)))
14759 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14760 (defun org-string>= (a b) (not (string< a b)))
14761 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14762 (defun org-string<> (a b) (not (string= a b)))
14763 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14764 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14765 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14766 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14767 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14768 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14769 (defun org-2ft (s)
14770 "Convert S to a floating point time.
14771 If S is already a number, just return it. If it is a string, parse
14772 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14773 (cond
14774 ((numberp s) s)
14775 ((stringp s)
14776 (condition-case nil
14777 (float-time (apply 'encode-time (org-parse-time-string s)))
14778 (error 0.)))
14779 (t 0.)))
14781 (defun org-time-today ()
14782 "Time in seconds today at 0:00.
14783 Returns the float number of seconds since the beginning of the
14784 epoch to the beginning of today (00:00)."
14785 (float-time (apply 'encode-time
14786 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14788 (defun org-matcher-time (s)
14789 "Interpret a time comparison value."
14790 (save-match-data
14791 (cond
14792 ((string= s "<now>") (float-time))
14793 ((string= s "<today>") (org-time-today))
14794 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14795 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14796 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14797 (+ (org-time-today)
14798 (* (string-to-number (match-string 1 s))
14799 (cdr (assoc (match-string 2 s)
14800 '(("d" . 86400.0) ("w" . 604800.0)
14801 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14802 (t (org-2ft s)))))
14804 (defun org-match-any-p (re list)
14805 "Does re match any element of list?"
14806 (setq list (mapcar (lambda (x) (string-match re x)) list))
14807 (delq nil list))
14809 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14810 (defvar org-tags-overlay (make-overlay 1 1))
14811 (org-detach-overlay org-tags-overlay)
14813 (defun org-get-local-tags-at (&optional pos)
14814 "Get a list of tags defined in the current headline."
14815 (org-get-tags-at pos 'local))
14817 (defun org-get-local-tags ()
14818 "Get a list of tags defined in the current headline."
14819 (org-get-tags-at nil 'local))
14821 (defun org-get-tags-at (&optional pos local)
14822 "Get a list of all headline tags applicable at POS.
14823 POS defaults to point. If tags are inherited, the list contains
14824 the targets in the same sequence as the headlines appear, i.e.
14825 the tags of the current headline come last.
14826 When LOCAL is non-nil, only return tags from the current headline,
14827 ignore inherited ones."
14828 (interactive)
14829 (if (and org-trust-scanner-tags
14830 (or (not pos) (equal pos (point)))
14831 (not local))
14832 org-scanner-tags
14833 (let (tags ltags lastpos parent)
14834 (save-excursion
14835 (save-restriction
14836 (widen)
14837 (goto-char (or pos (point)))
14838 (save-match-data
14839 (catch 'done
14840 (condition-case nil
14841 (progn
14842 (org-back-to-heading t)
14843 (while (not (equal lastpos (point)))
14844 (setq lastpos (point))
14845 (when (looking-at
14846 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14847 (setq ltags (org-split-string
14848 (org-match-string-no-properties 1) ":"))
14849 (when parent
14850 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14851 (setq tags (append
14852 (if parent
14853 (org-remove-uninherited-tags ltags)
14854 ltags)
14855 tags)))
14856 (or org-use-tag-inheritance (throw 'done t))
14857 (if local (throw 'done t))
14858 (or (org-up-heading-safe) (error nil))
14859 (setq parent t)))
14860 (error nil)))))
14861 (if local
14862 tags
14863 (reverse (delete-dups
14864 (reverse (append
14865 (org-remove-uninherited-tags
14866 org-file-tags)
14867 tags)))))))))
14869 (defun org-add-prop-inherited (s)
14870 (add-text-properties 0 (length s) '(inherited t) s)
14873 (defun org-toggle-tag (tag &optional onoff)
14874 "Toggle the tag TAG for the current line.
14875 If ONOFF is `on' or `off', don't toggle but set to this state."
14876 (let (res current)
14877 (save-excursion
14878 (org-back-to-heading t)
14879 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14880 (point-at-eol) t)
14881 (progn
14882 (setq current (match-string 1))
14883 (replace-match ""))
14884 (setq current ""))
14885 (setq current (nreverse (org-split-string current ":")))
14886 (cond
14887 ((eq onoff 'on)
14888 (setq res t)
14889 (or (member tag current) (push tag current)))
14890 ((eq onoff 'off)
14891 (or (not (member tag current)) (setq current (delete tag current))))
14892 (t (if (member tag current)
14893 (setq current (delete tag current))
14894 (setq res t)
14895 (push tag current))))
14896 (end-of-line 1)
14897 (if current
14898 (progn
14899 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14900 (org-set-tags nil t))
14901 (delete-horizontal-space))
14902 (run-hooks 'org-after-tags-change-hook))
14903 res))
14905 (defun org-align-tags-here (to-col)
14906 ;; Assumes that this is a headline
14907 "Align tags on the current headline to TO-COL."
14908 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14909 (beginning-of-line 1)
14910 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14911 (< pos (match-beginning 2)))
14912 (progn
14913 (setq tags-l (- (match-end 2) (match-beginning 2)))
14914 (goto-char (match-beginning 1))
14915 (insert " ")
14916 (delete-region (point) (1+ (match-beginning 2)))
14917 (setq ncol (max (current-column)
14918 (1+ col)
14919 (if (> to-col 0)
14920 to-col
14921 (- (abs to-col) tags-l))))
14922 (setq p (point))
14923 (insert (make-string (- ncol (current-column)) ?\ ))
14924 (setq ncol (current-column))
14925 (when indent-tabs-mode (tabify p (point-at-eol)))
14926 (org-move-to-column (min ncol col)))
14927 (goto-char pos))))
14929 (defun org-set-tags-command (&optional arg just-align)
14930 "Call the set-tags command for the current entry."
14931 (interactive "P")
14932 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14933 (org-set-tags arg just-align)
14934 (save-excursion
14935 (unless (and (org-region-active-p)
14936 org-loop-over-headlines-in-active-region)
14937 (org-back-to-heading t))
14938 (org-set-tags arg just-align))))
14940 (defun org-set-tags-to (data)
14941 "Set the tags of the current entry to DATA, replacing the current tags.
14942 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14943 If DATA is nil or the empty string, any tags will be removed."
14944 (interactive "sTags: ")
14945 (setq data
14946 (cond
14947 ((eq data nil) "")
14948 ((equal data "") "")
14949 ((stringp data)
14950 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14951 ":"))
14952 ((listp data)
14953 (concat ":" (mapconcat 'identity data ":") ":"))))
14954 (when data
14955 (save-excursion
14956 (org-back-to-heading t)
14957 (when (looking-at org-complex-heading-regexp)
14958 (if (match-end 5)
14959 (progn
14960 (goto-char (match-beginning 5))
14961 (insert data)
14962 (delete-region (point) (point-at-eol))
14963 (org-set-tags nil 'align))
14964 (goto-char (point-at-eol))
14965 (insert " " data)
14966 (org-set-tags nil 'align)))
14967 (beginning-of-line 1)
14968 (if (looking-at ".*?\\([ \t]+\\)$")
14969 (delete-region (match-beginning 1) (match-end 1))))))
14971 (defun org-align-all-tags ()
14972 "Align the tags i all headings."
14973 (interactive)
14974 (save-excursion
14975 (or (ignore-errors (org-back-to-heading t))
14976 (outline-next-heading))
14977 (if (org-at-heading-p)
14978 (org-set-tags t)
14979 (message "No headings"))))
14981 (defvar org-indent-indentation-per-level)
14982 (defun org-set-tags (&optional arg just-align)
14983 "Set the tags for the current headline.
14984 With prefix ARG, realign all tags in headings in the current buffer.
14985 When JUST-ALIGN is non-nil, only align tags."
14986 (interactive "P")
14987 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14988 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14989 'region-start-level
14990 'region))
14991 org-loop-over-headlines-in-active-region)
14992 (org-map-entries
14993 ;; We don't use ARG and JUST-ALIGN here because these args
14994 ;; are not useful when looping over headlines.
14995 #'org-set-tags
14996 org-loop-over-headlines-in-active-region
14998 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
14999 (let ((org-setting-tags t))
15000 (if arg
15001 (save-excursion
15002 (goto-char (point-min))
15003 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15004 (while (re-search-forward org-outline-regexp-bol nil t)
15005 (org-set-tags nil t)
15006 (end-of-line)))
15007 (message "All tags realigned to column %d" org-tags-column))
15008 (let* ((current (org-get-tags-string))
15009 (col (current-column))
15010 (tags
15011 (if just-align current
15012 ;; Get a new set of tags from the user.
15013 (save-excursion
15014 (let* ((table
15015 (setq
15016 org-last-tags-completion-table
15017 (append
15018 org-tag-persistent-alist
15019 (or org-tag-alist (org-get-buffer-tags))
15020 (and
15021 org-complete-tags-always-offer-all-agenda-tags
15022 (org-global-tags-completion-table
15023 (org-agenda-files))))))
15024 (current-tags (org-split-string current ":"))
15025 (inherited-tags
15026 (nreverse (nthcdr (length current-tags)
15027 (nreverse (org-get-tags-at))))))
15028 (replace-regexp-in-string
15029 "\\([-+&]+\\|,\\)"
15031 (if (or (eq t org-use-fast-tag-selection)
15032 (and org-use-fast-tag-selection
15033 (delq nil (mapcar #'cdr table))))
15034 (org-fast-tag-selection
15035 current-tags inherited-tags table
15036 (and org-fast-tag-selection-include-todo
15037 org-todo-key-alist))
15038 (let ((org-add-colon-after-tag-completion
15039 (< 1 (length table))))
15040 (org-trim
15041 (completing-read
15042 "Tags: "
15043 #'org-tags-completion-function
15044 nil nil current 'org-tags-history))))))))))
15046 (when org-tags-sort-function
15047 (setq tags
15048 (mapconcat
15049 #'identity
15050 (sort (org-split-string tags (org-re "[^[:alnum:]_@#%]+"))
15051 org-tags-sort-function)
15052 ":")))
15054 (if (not (org-string-nw-p tags)) (setq tags "")
15055 (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
15056 (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
15058 ;; Insert new tags at the correct column
15059 (beginning-of-line)
15060 (let ((level (if (looking-at org-outline-regexp)
15061 (- (match-end 0) (point) 1)
15062 1)))
15063 (cond
15064 ((and (equal current "") (equal tags "")))
15065 ((re-search-forward
15066 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15067 (line-end-position)
15069 (if (equal tags "") (replace-match "" t t)
15070 (goto-char (match-beginning 0))
15071 (let* ((c0 (current-column))
15072 ;; Compute offset for the case of org-indent-mode
15073 ;; active.
15074 (di (if (org-bound-and-true-p org-indent-mode)
15075 (* (1- org-indent-indentation-per-level)
15076 (1- level))
15078 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
15079 (tc (+ org-tags-column
15080 (if (> org-tags-column 0) (- di) di)))
15081 (c1 (max (1+ c0)
15082 (if (> tc 0) tc
15083 (- (- tc) (string-width tags)))))
15084 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
15085 (replace-match rpl t t)
15086 (when (and (not (featurep 'xemacs)) indent-tabs-mode)
15087 (tabify p0 (point))))))
15088 (t (error "Tags alignment failed"))))
15089 (org-move-to-column col))
15090 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15092 (defun org-change-tag-in-region (beg end tag off)
15093 "Add or remove TAG for each entry in the region.
15094 This works in the agenda, and also in an org-mode buffer."
15095 (interactive
15096 (list (region-beginning) (region-end)
15097 (let ((org-last-tags-completion-table
15098 (if (derived-mode-p 'org-mode)
15099 (org-uniquify
15100 (delq nil (append (org-get-buffer-tags)
15101 (org-global-tags-completion-table))))
15102 (org-global-tags-completion-table))))
15103 (org-icompleting-read
15104 "Tag: " 'org-tags-completion-function nil nil nil
15105 'org-tags-history))
15106 (progn
15107 (message "[s]et or [r]emove? ")
15108 (equal (read-char-exclusive) ?r))))
15109 (if (fboundp 'deactivate-mark) (deactivate-mark))
15110 (let ((agendap (equal major-mode 'org-agenda-mode))
15111 l1 l2 m buf pos newhead (cnt 0))
15112 (goto-char end)
15113 (setq l2 (1- (org-current-line)))
15114 (goto-char beg)
15115 (setq l1 (org-current-line))
15116 (loop for l from l1 to l2 do
15117 (org-goto-line l)
15118 (setq m (get-text-property (point) 'org-hd-marker))
15119 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15120 (and agendap m))
15121 (setq buf (if agendap (marker-buffer m) (current-buffer))
15122 pos (if agendap m (point)))
15123 (with-current-buffer buf
15124 (save-excursion
15125 (save-restriction
15126 (goto-char pos)
15127 (setq cnt (1+ cnt))
15128 (org-toggle-tag tag (if off 'off 'on))
15129 (setq newhead (org-get-heading)))))
15130 (and agendap (org-agenda-change-all-lines newhead m))))
15131 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15133 (defun org-tags-completion-function (string predicate &optional flag)
15134 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15135 (confirm (lambda (x) (stringp (car x)))))
15136 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15137 (setq s1 (match-string 1 string)
15138 s2 (match-string 2 string))
15139 (setq s1 "" s2 string))
15140 (cond
15141 ((eq flag nil)
15142 ;; try completion
15143 (setq rtn (try-completion s2 ctable confirm))
15144 (if (stringp rtn)
15145 (setq rtn
15146 (concat s1 s2 (substring rtn (length s2))
15147 (if (and org-add-colon-after-tag-completion
15148 (assoc rtn ctable))
15149 ":" ""))))
15150 rtn)
15151 ((eq flag t)
15152 ;; all-completions
15153 (all-completions s2 ctable confirm))
15154 ((eq flag 'lambda)
15155 ;; exact match?
15156 (assoc s2 ctable)))))
15158 (defun org-fast-tag-insert (kwd tags face &optional end)
15159 "Insert KDW, and the TAGS, the latter with face FACE.
15160 Also insert END."
15161 (insert (format "%-12s" (concat kwd ":"))
15162 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15163 (or end "")))
15165 (defun org-fast-tag-show-exit (flag)
15166 (save-excursion
15167 (org-goto-line 3)
15168 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15169 (replace-match ""))
15170 (when flag
15171 (end-of-line 1)
15172 (org-move-to-column (- (window-width) 19) t)
15173 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15175 (defun org-set-current-tags-overlay (current prefix)
15176 "Add an overlay to CURRENT tag with PREFIX."
15177 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15178 (if (featurep 'xemacs)
15179 (org-overlay-display org-tags-overlay (concat prefix s)
15180 'secondary-selection)
15181 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15182 (org-overlay-display org-tags-overlay (concat prefix s)))))
15184 (defvar org-last-tag-selection-key nil)
15185 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15186 "Fast tag selection with single keys.
15187 CURRENT is the current list of tags in the headline, INHERITED is the
15188 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15189 possibly with grouping information. TODO-TABLE is a similar table with
15190 TODO keywords, should these have keys assigned to them.
15191 If the keys are nil, a-z are automatically assigned.
15192 Returns the new tags string, or nil to not change the current settings."
15193 (let* ((fulltable (append table todo-table))
15194 (maxlen (apply 'max (mapcar
15195 (lambda (x)
15196 (if (stringp (car x)) (string-width (car x)) 0))
15197 fulltable)))
15198 (buf (current-buffer))
15199 (expert (eq org-fast-tag-selection-single-key 'expert))
15200 (buffer-tags nil)
15201 (fwidth (+ maxlen 3 1 3))
15202 (ncol (/ (- (window-width) 4) fwidth))
15203 (i-face 'org-done)
15204 (c-face 'org-todo)
15205 tg cnt e c char c1 c2 ntable tbl rtn
15206 ov-start ov-end ov-prefix
15207 (exit-after-next org-fast-tag-selection-single-key)
15208 (done-keywords org-done-keywords)
15209 groups ingroup intaggroup)
15210 (save-excursion
15211 (beginning-of-line 1)
15212 (if (looking-at
15213 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15214 (setq ov-start (match-beginning 1)
15215 ov-end (match-end 1)
15216 ov-prefix "")
15217 (setq ov-start (1- (point-at-eol))
15218 ov-end (1+ ov-start))
15219 (skip-chars-forward "^\n\r")
15220 (setq ov-prefix
15221 (concat
15222 (buffer-substring (1- (point)) (point))
15223 (if (> (current-column) org-tags-column)
15225 (make-string (- org-tags-column (current-column)) ?\ ))))))
15226 (move-overlay org-tags-overlay ov-start ov-end)
15227 (save-window-excursion
15228 (if expert
15229 (set-buffer (get-buffer-create " *Org tags*"))
15230 (delete-other-windows)
15231 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15232 (org-switch-to-buffer-other-window " *Org tags*"))
15233 (erase-buffer)
15234 (org-set-local 'org-done-keywords done-keywords)
15235 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15236 (org-fast-tag-insert "Current" current c-face "\n\n")
15237 (org-fast-tag-show-exit exit-after-next)
15238 (org-set-current-tags-overlay current ov-prefix)
15239 (setq tbl fulltable char ?a cnt 0)
15240 (while (setq e (pop tbl))
15241 (cond
15242 ((eq (car e) :startgroup)
15243 (push '() groups) (setq ingroup t)
15244 (unless (zerop cnt)
15245 (setq cnt 0)
15246 (insert "\n"))
15247 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15248 ((eq (car e) :endgroup)
15249 (setq ingroup nil cnt 0)
15250 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15251 ((eq (car e) :startgrouptag)
15252 (setq intaggroup t)
15253 (unless (zerop cnt)
15254 (setq cnt 0)
15255 (insert "\n"))
15256 (insert "[ "))
15257 ((eq (car e) :endgrouptag)
15258 (setq intaggroup nil cnt 0)
15259 (insert "]\n"))
15260 ((equal e '(:newline))
15261 (unless (zerop cnt)
15262 (setq cnt 0)
15263 (insert "\n")
15264 (setq e (car tbl))
15265 (while (equal (car tbl) '(:newline))
15266 (insert "\n")
15267 (setq tbl (cdr tbl)))))
15268 ((equal e '(:grouptags)) (insert " : "))
15270 (setq tg (copy-sequence (car e)) c2 nil)
15271 (if (cdr e)
15272 (setq c (cdr e))
15273 ;; automatically assign a character.
15274 (setq c1 (string-to-char
15275 (downcase (substring
15276 tg (if (= (string-to-char tg) ?@) 1 0)))))
15277 (if (or (rassoc c1 ntable) (rassoc c1 table))
15278 (while (or (rassoc char ntable) (rassoc char table))
15279 (setq char (1+ char)))
15280 (setq c2 c1))
15281 (setq c (or c2 char)))
15282 (when ingroup (push tg (car groups)))
15283 (setq tg (org-add-props tg nil 'face
15284 (cond
15285 ((not (assoc tg table))
15286 (org-get-todo-face tg))
15287 ((member tg current) c-face)
15288 ((member tg inherited) i-face))))
15289 (when (equal (caar tbl) :grouptags)
15290 (org-add-props tg nil 'face 'org-tag-group))
15291 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15292 (insert "[" c "] " tg (make-string
15293 (- fwidth 4 (length tg)) ?\ ))
15294 (push (cons tg c) ntable)
15295 (when (= (incf cnt) ncol)
15296 (insert "\n")
15297 (when (or ingroup intaggroup) (insert " "))
15298 (setq cnt 0)))))
15299 (setq ntable (nreverse ntable))
15300 (insert "\n")
15301 (goto-char (point-min))
15302 (unless expert (org-fit-window-to-buffer))
15303 (setq rtn
15304 (catch 'exit
15305 (while t
15306 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15307 (if (not groups) "no " "")
15308 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15309 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15310 (setq org-last-tag-selection-key c)
15311 (cond
15312 ((= c ?\r) (throw 'exit t))
15313 ((= c ?!)
15314 (setq groups (not groups))
15315 (goto-char (point-min))
15316 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15317 ((= c ?\C-c)
15318 (if (not expert)
15319 (org-fast-tag-show-exit
15320 (setq exit-after-next (not exit-after-next)))
15321 (setq expert nil)
15322 (delete-other-windows)
15323 (set-window-buffer (split-window-vertically) " *Org tags*")
15324 (org-switch-to-buffer-other-window " *Org tags*")
15325 (org-fit-window-to-buffer)))
15326 ((or (= c ?\C-g)
15327 (and (= c ?q) (not (rassoc c ntable))))
15328 (org-detach-overlay org-tags-overlay)
15329 (setq quit-flag t))
15330 ((= c ?\ )
15331 (setq current nil)
15332 (when exit-after-next (setq exit-after-next 'now)))
15333 ((= c ?\t)
15334 (condition-case nil
15335 (setq tg (org-icompleting-read
15336 "Tag: "
15337 (or buffer-tags
15338 (with-current-buffer buf
15339 (setq buffer-tags
15340 (org-get-buffer-tags))))))
15341 (quit (setq tg "")))
15342 (when (string-match "\\S-" tg)
15343 (add-to-list 'buffer-tags (list tg))
15344 (if (member tg current)
15345 (setq current (delete tg current))
15346 (push tg current)))
15347 (when exit-after-next (setq exit-after-next 'now)))
15348 ((setq e (rassoc c todo-table) tg (car e))
15349 (with-current-buffer buf
15350 (save-excursion (org-todo tg)))
15351 (when exit-after-next (setq exit-after-next 'now)))
15352 ((setq e (rassoc c ntable) tg (car e))
15353 (if (member tg current)
15354 (setq current (delete tg current))
15355 (loop for g in groups do
15356 (when (member tg g)
15357 (dolist (x g) (setq current (delete x current)))))
15358 (push tg current))
15359 (when exit-after-next (setq exit-after-next 'now))))
15361 ;; Create a sorted list
15362 (setq current
15363 (sort current
15364 (lambda (a b)
15365 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15366 (when (eq exit-after-next 'now) (throw 'exit t))
15367 (goto-char (point-min))
15368 (beginning-of-line 2)
15369 (delete-region (point) (point-at-eol))
15370 (org-fast-tag-insert "Current" current c-face)
15371 (org-set-current-tags-overlay current ov-prefix)
15372 (while (re-search-forward
15373 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15374 (setq tg (match-string 1))
15375 (add-text-properties
15376 (match-beginning 1) (match-end 1)
15377 (list 'face
15378 (cond
15379 ((member tg current) c-face)
15380 ((member tg inherited) i-face)
15381 (t (get-text-property (match-beginning 1) 'face))))))
15382 (goto-char (point-min)))))
15383 (org-detach-overlay org-tags-overlay)
15384 (if rtn
15385 (mapconcat 'identity current ":")
15386 nil))))
15388 (defun org-get-tags-string ()
15389 "Get the TAGS string in the current headline."
15390 (unless (org-at-heading-p t)
15391 (user-error "Not on a heading"))
15392 (save-excursion
15393 (beginning-of-line 1)
15394 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15395 (org-match-string-no-properties 1)
15396 "")))
15398 (defun org-get-tags ()
15399 "Get the list of tags specified in the current headline."
15400 (org-split-string (org-get-tags-string) ":"))
15402 (defun org-get-buffer-tags ()
15403 "Get a table of all tags used in the buffer, for completion."
15404 (org-with-wide-buffer
15405 (goto-char (point-min))
15406 (let ((tag-re (concat org-outline-regexp-bol
15407 "\\(?:.*?[ \t]\\)?"
15408 (org-re ":\\([[:alnum:]_@#%:]+\\):[ \t]*$")))
15409 tags)
15410 (while (re-search-forward tag-re nil t)
15411 (dolist (tag (org-split-string (org-match-string-no-properties 1) ":"))
15412 (push tag tags)))
15413 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15415 ;;;; The mapping API
15417 (defun org-map-entries (func &optional match scope &rest skip)
15418 "Call FUNC at each headline selected by MATCH in SCOPE.
15420 FUNC is a function or a lisp form. The function will be called without
15421 arguments, with the cursor positioned at the beginning of the headline.
15422 The return values of all calls to the function will be collected and
15423 returned as a list.
15425 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15426 does not need to preserve point. After evaluation, the cursor will be
15427 moved to the end of the line (presumably of the headline of the
15428 processed entry) and search continues from there. Under some
15429 circumstances, this may not produce the wanted results. For example,
15430 if you have removed (e.g. archived) the current (sub)tree it could
15431 mean that the next entry will be skipped entirely. In such cases, you
15432 can specify the position from where search should continue by making
15433 FUNC set the variable `org-map-continue-from' to the desired buffer
15434 position.
15436 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15437 Only headlines that are matched by this query will be considered during
15438 the iteration. When MATCH is nil or t, all headlines will be
15439 visited by the iteration.
15441 SCOPE determines the scope of this command. It can be any of:
15443 nil The current buffer, respecting the restriction if any
15444 tree The subtree started with the entry at point
15445 region The entries within the active region, if any
15446 region-start-level
15447 The entries within the active region, but only those at
15448 the same level than the first one.
15449 file The current buffer, without restriction
15450 file-with-archives
15451 The current buffer, and any archives associated with it
15452 agenda All agenda files
15453 agenda-with-archives
15454 All agenda files with any archive files associated with them
15455 \(file1 file2 ...)
15456 If this is a list, all files in the list will be scanned
15458 The remaining args are treated as settings for the skipping facilities of
15459 the scanner. The following items can be given here:
15461 archive skip trees with the archive tag
15462 comment skip trees with the COMMENT keyword
15463 function or Emacs Lisp form:
15464 will be used as value for `org-agenda-skip-function', so
15465 whenever the function returns a position, FUNC will not be
15466 called for that entry and search will continue from the
15467 position returned
15469 If your function needs to retrieve the tags including inherited tags
15470 at the *current* entry, you can use the value of the variable
15471 `org-scanner-tags' which will be much faster than getting the value
15472 with `org-get-tags-at'. If your function gets properties with
15473 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15474 to t around the call to `org-entry-properties' to get the same speedup.
15475 Note that if your function moves around to retrieve tags and properties at
15476 a *different* entry, you cannot use these techniques."
15477 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15478 (not (org-region-active-p)))
15479 (let* ((org-agenda-archives-mode nil) ; just to make sure
15480 (org-agenda-skip-archived-trees (memq 'archive skip))
15481 (org-agenda-skip-comment-trees (memq 'comment skip))
15482 (org-agenda-skip-function
15483 (car (org-delete-all '(comment archive) skip)))
15484 (org-tags-match-list-sublevels t)
15485 (start-level (eq scope 'region-start-level))
15486 matcher file res
15487 org-todo-keywords-for-agenda
15488 org-done-keywords-for-agenda
15489 org-todo-keyword-alist-for-agenda
15490 org-tag-alist-for-agenda
15491 todo-only)
15493 (cond
15494 ((eq match t) (setq matcher t))
15495 ((eq match nil) (setq matcher t))
15496 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15498 (save-excursion
15499 (save-restriction
15500 (cond ((eq scope 'tree)
15501 (org-back-to-heading t)
15502 (org-narrow-to-subtree)
15503 (setq scope nil))
15504 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15505 (org-region-active-p))
15506 ;; If needed, set start-level to a string like "2"
15507 (when start-level
15508 (save-excursion
15509 (goto-char (region-beginning))
15510 (unless (org-at-heading-p) (outline-next-heading))
15511 (setq start-level (org-current-level))))
15512 (narrow-to-region (region-beginning)
15513 (save-excursion
15514 (goto-char (region-end))
15515 (unless (and (bolp) (org-at-heading-p))
15516 (outline-next-heading))
15517 (point)))
15518 (setq scope nil)))
15520 (if (not scope)
15521 (progn
15522 (org-agenda-prepare-buffers
15523 (and buffer-file-name (list buffer-file-name)))
15524 (setq res (org-scan-tags func matcher todo-only start-level)))
15525 ;; Get the right scope
15526 (cond
15527 ((and scope (listp scope) (symbolp (car scope)))
15528 (setq scope (eval scope)))
15529 ((eq scope 'agenda)
15530 (setq scope (org-agenda-files t)))
15531 ((eq scope 'agenda-with-archives)
15532 (setq scope (org-agenda-files t))
15533 (setq scope (org-add-archive-files scope)))
15534 ((eq scope 'file)
15535 (setq scope (and buffer-file-name (list buffer-file-name))))
15536 ((eq scope 'file-with-archives)
15537 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15538 (org-agenda-prepare-buffers scope)
15539 (dolist (file scope)
15540 (with-current-buffer (org-find-base-buffer-visiting file)
15541 (save-excursion
15542 (save-restriction
15543 (widen)
15544 (goto-char (point-min))
15545 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15546 res)))
15548 ;;; Properties API
15550 (defconst org-special-properties
15551 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15552 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15553 "The special properties valid in Org mode.
15554 These are properties that are not defined in the property drawer,
15555 but in some other way.")
15557 (defconst org-default-properties
15558 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15559 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15560 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15561 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15562 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15563 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15564 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15565 "Some properties that are used by Org mode for various purposes.
15566 Being in this list makes sure that they are offered for completion.")
15568 (defun org--update-property-plist (key val props)
15569 "Associate KEY to VAL in alist PROPS.
15570 Modifications are made by side-effect. Return new alist."
15571 (let* ((appending (string= (substring key -1) "+"))
15572 (key (if appending (substring key 0 -1) key))
15573 (old (assoc-string key props t)))
15574 (if (not old) (cons (cons key val) props)
15575 (setcdr old (if appending (concat (cdr old) " " val) val))
15576 props)))
15578 (defun org-get-property-block (&optional beg force)
15579 "Return the (beg . end) range of the body of the property drawer.
15580 BEG is the beginning of the current subtree, or of the part
15581 before the first headline. If it is not given, it will be found.
15582 If the drawer does not exist, create it if FORCE is non-nil, or
15583 return nil."
15584 (org-with-wide-buffer
15585 (when beg (goto-char beg))
15586 (unless (org-before-first-heading-p)
15587 (let ((beg (cond (beg)
15588 ((or (not (featurep 'org-inlinetask))
15589 (org-inlinetask-in-task-p))
15590 (org-back-to-heading t))
15591 (t (org-with-limited-levels (org-back-to-heading t))))))
15592 (forward-line)
15593 (when (org-looking-at-p org-planning-line-re) (forward-line))
15594 (cond ((looking-at org-property-drawer-re)
15595 (forward-line)
15596 (cons (point) (progn (goto-char (match-end 0))
15597 (line-beginning-position))))
15598 (force
15599 (goto-char beg)
15600 (org-insert-property-drawer)
15601 (let ((pos (save-excursion (search-forward ":END:")
15602 (line-beginning-position))))
15603 (cons pos pos))))))))
15605 (defun org-at-property-p ()
15606 "Non-nil when point is inside a property drawer.
15607 See `org-property-re' for match data, if applicable."
15608 (save-excursion
15609 (beginning-of-line)
15610 (and (looking-at org-property-re)
15611 (let ((property-drawer (save-match-data (org-get-property-block))))
15612 (and property-drawer
15613 (>= (point) (car property-drawer))
15614 (< (point) (cdr property-drawer)))))))
15616 (defun org-property-action ()
15617 "Do an action on properties."
15618 (interactive)
15619 (unless (org-at-property-p) (user-error "Not at a property"))
15620 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15621 (let ((c (read-char-exclusive)))
15622 (case c
15623 (?s (call-interactively #'org-set-property))
15624 (?d (call-interactively #'org-delete-property))
15625 (?D (call-interactively #'org-delete-property-globally))
15626 (?c (call-interactively #'org-compute-property-at-point))
15627 (otherwise (user-error "No such property action %c" c)))))
15629 (defun org-inc-effort ()
15630 "Increment the value of the effort property in the current entry."
15631 (interactive)
15632 (org-set-effort nil t))
15634 (defvar org-clock-effort) ; Defined in org-clock.el.
15635 (defvar org-clock-current-task) ; Defined in org-clock.el.
15636 (defun org-set-effort (&optional value increment)
15637 "Set the effort property of the current entry.
15638 With numerical prefix arg, use the nth allowed value, 0 stands for the
15639 10th allowed value.
15641 When INCREMENT is non-nil, set the property to the next allowed value."
15642 (interactive "P")
15643 (if (equal value 0) (setq value 10))
15644 (let* ((completion-ignore-case t)
15645 (prop org-effort-property)
15646 (cur (org-entry-get nil prop))
15647 (allowed (org-property-get-allowed-values nil prop 'table))
15648 (existing (mapcar 'list (org-property-values prop)))
15649 (heading (nth 4 (org-heading-components)))
15651 (val (cond
15652 ((stringp value) value)
15653 ((and allowed (integerp value))
15654 (or (car (nth (1- value) allowed))
15655 (car (org-last allowed))))
15656 ((and allowed increment)
15657 (or (caadr (member (list cur) allowed))
15658 (user-error "Allowed effort values are not set")))
15659 (allowed
15660 (message "Select 1-9,0, [RET%s]: %s"
15661 (if cur (concat "=" cur) "")
15662 (mapconcat 'car allowed " "))
15663 (setq rpl (read-char-exclusive))
15664 (if (equal rpl ?\r)
15666 (setq rpl (- rpl ?0))
15667 (if (equal rpl 0) (setq rpl 10))
15668 (if (and (> rpl 0) (<= rpl (length allowed)))
15669 (car (nth (1- rpl) allowed))
15670 (org-completing-read "Effort: " allowed nil))))
15672 (let (org-completion-use-ido org-completion-use-iswitchb)
15673 (org-completing-read
15674 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15675 (concat "[" cur "]") "")
15676 ": ")
15677 existing nil nil "" nil cur))))))
15678 (unless (equal (org-entry-get nil prop) val)
15679 (org-entry-put nil prop val))
15680 (org-refresh-property
15681 '((effort . identity)
15682 (effort-minutes . org-duration-string-to-minutes))
15683 val)
15684 (when (string= heading org-clock-current-task)
15685 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15686 (org-clock-update-mode-line))
15687 (message "%s is now %s" prop val)))
15689 (defun org-entry-properties (&optional pom which)
15690 "Get all properties of the current entry.
15692 When POM is a buffer position, get all properties from the entry
15693 there instead.
15695 This includes the TODO keyword, the tags, time strings for
15696 deadline, scheduled, and clocking, and any additional properties
15697 defined in the entry.
15699 If WHICH is nil or `all', get all properties. If WHICH is
15700 `special' or `standard', only get that subclass. If WHICH is
15701 a string, only get that property.
15703 Return value is an alist. Keys are properties, as upcased
15704 strings."
15705 (org-with-point-at pom
15706 (when (and (derived-mode-p 'org-mode)
15707 (ignore-errors (org-back-to-heading t)))
15708 (catch 'exit
15709 (let* ((beg (point))
15710 (specific (and (stringp which) (upcase which)))
15711 (which (cond ((not specific) which)
15712 ((member specific org-special-properties) 'special)
15713 (t 'standard)))
15714 props)
15715 ;; Get the special properties, like TODO and TAGS.
15716 (when (memq which '(nil all special))
15717 (when (or (not specific) (string= specific "CLOCKSUM"))
15718 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15719 (when clocksum
15720 (push (cons "CLOCKSUM"
15721 (org-columns-number-to-string
15722 (/ (float clocksum) 60.) 'add_times))
15723 props)))
15724 (when specific (throw 'exit props)))
15725 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15726 (let ((clocksumt (get-text-property (point)
15727 :org-clock-minutes-today)))
15728 (when clocksumt
15729 (push (cons "CLOCKSUM_T"
15730 (org-columns-number-to-string
15731 (/ (float clocksumt) 60.) 'add_times))
15732 props)))
15733 (when specific (throw 'exit props)))
15734 (when (or (not specific) (string= specific "ITEM"))
15735 (when (looking-at org-complex-heading-regexp)
15736 (push (cons "ITEM"
15737 (concat
15738 (org-match-string-no-properties 1)
15739 (let ((title (org-match-string-no-properties 4)))
15740 (when (org-string-nw-p title)
15741 (concat " " (org-remove-tabs title))))))
15742 props))
15743 (when specific (throw 'exit props)))
15744 (when (or (not specific) (string= specific "TODO"))
15745 (let ((case-fold-search nil))
15746 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15747 (push (cons "TODO" (org-match-string-no-properties 2)) props)))
15748 (when specific (throw 'exit props)))
15749 (when (or (not specific) (string= specific "PRIORITY"))
15750 (push (cons "PRIORITY"
15751 (if (looking-at org-priority-regexp)
15752 (org-match-string-no-properties 2)
15753 (char-to-string org-default-priority)))
15754 props)
15755 (when specific (throw 'exit props)))
15756 (when (or (not specific) (string= specific "FILE"))
15757 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15758 props)
15759 (when specific (throw 'exit props)))
15760 (when (or (not specific) (string= specific "TAGS"))
15761 (let ((value (org-string-nw-p (org-get-tags-string))))
15762 (when value (push (cons "TAGS" value) props)))
15763 (when specific (throw 'exit props)))
15764 (when (or (not specific) (string= specific "ALLTAGS"))
15765 (let ((value (org-get-tags-at)))
15766 (when value
15767 (push (cons "ALLTAGS"
15768 (format ":%s:" (mapconcat #'identity value ":")))
15769 props)))
15770 (when specific (throw 'exit props)))
15771 (when (or (not specific) (string= specific "BLOCKED"))
15772 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15773 (when specific (throw 'exit props)))
15774 (when (or (not specific)
15775 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15776 (forward-line)
15777 (when (org-looking-at-p org-planning-line-re)
15778 (end-of-line)
15779 (let ((bol (line-beginning-position))
15780 ;; Backward compatibility: time keywords used to
15781 ;; be configurable (before 8.3). Make sure we
15782 ;; get the correct keyword.
15783 (key-assoc `(("CLOSED" . ,org-closed-string)
15784 ("DEADLINE" . ,org-deadline-string)
15785 ("SCHEDULED" . ,org-scheduled-string))))
15786 (dolist (pair (if specific (list (assoc specific key-assoc))
15787 key-assoc))
15788 (save-excursion
15789 (when (search-backward (cdr pair) bol t)
15790 (goto-char (match-end 0))
15791 (skip-chars-forward " \t")
15792 (and (looking-at org-ts-regexp-both)
15793 (push (cons (car pair)
15794 (org-match-string-no-properties 0))
15795 props)))))))
15796 (when specific (throw 'exit props)))
15797 (when (or (not specific)
15798 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15799 (let ((find-ts
15800 (lambda (end ts)
15801 (let ((regexp (cond
15802 ((string= specific "TIMESTAMP")
15803 org-ts-regexp)
15804 ((string= specific "TIMESTAMP_IA")
15805 org-ts-regexp-inactive)
15806 ((assoc "TIMESTAMP_IA" ts)
15807 org-ts-regexp)
15808 ((assoc "TIMESTAMP" ts)
15809 org-ts-regexp-inactive)
15810 (t org-ts-regexp-both))))
15811 (catch 'next
15812 (while (re-search-forward regexp end t)
15813 (backward-char)
15814 (let ((object (org-element-context)))
15815 ;; Accept to match timestamps in node
15816 ;; properties, too.
15817 (when (memq (org-element-type object)
15818 '(node-property timestamp))
15819 (let ((type
15820 (org-element-property :type object)))
15821 (cond
15822 ((and (memq type '(active active-range))
15823 (not (equal specific "TIMESTAMP_IA")))
15824 (unless (assoc "TIMESTAMP" ts)
15825 (push (cons "TIMESTAMP"
15826 (org-element-property
15827 :raw-value object))
15829 (when specific (throw 'exit ts))))
15830 ((and (memq type '(inactive inactive-range))
15831 (not (string= specific "TIMESTAMP")))
15832 (unless (assoc "TIMESTAMP_IA" ts)
15833 (push (cons "TIMESTAMP_IA"
15834 (org-element-property
15835 :raw-value object))
15837 (when specific (throw 'exit ts))))))
15838 ;; Both timestamp types are found,
15839 ;; move to next part.
15840 (when (= (length ts) 2) (throw 'next ts)))))
15841 ts)))))
15842 (goto-char beg)
15843 ;; First look for timestamps within headline.
15844 (let ((ts (funcall find-ts (line-end-position) nil)))
15845 (if (= (length ts) 2) (setq props (nconc ts props))
15846 (forward-line)
15847 ;; Then find timestamps in the section, skipping
15848 ;; planning line.
15849 (when (org-looking-at-p org-planning-line-re)
15850 (forward-line))
15851 (let ((end (save-excursion (outline-next-heading))))
15852 (setq props (nconc (funcall find-ts end ts) props))))))))
15853 ;; Get the standard properties, like :PROP:.
15854 (when (memq which '(nil all standard))
15855 ;; If we are looking after a specific property, delegate
15856 ;; to `org-entry-get', which is faster. However, make an
15857 ;; exception for "CATEGORY", since it can be also set
15858 ;; through keywords (i.e. #+CATEGORY).
15859 (if (and specific (not (equal specific "CATEGORY")))
15860 (let ((value (org-entry-get beg specific nil t)))
15861 (throw 'exit (and value (list (cons specific value)))))
15862 (let ((range (org-get-property-block beg)))
15863 (when range
15864 (let ((end (cdr range)) seen-base)
15865 (goto-char (car range))
15866 ;; Unlike to `org--update-property-plist', we
15867 ;; handle the case where base values is found
15868 ;; after its extension. We also forbid standard
15869 ;; properties to be named as special properties.
15870 (while (re-search-forward org-property-re end t)
15871 (let* ((key (upcase (org-match-string-no-properties 2)))
15872 (extendp (org-string-match-p "\\+\\'" key))
15873 (key-base (if extendp (substring key 0 -1) key))
15874 (value (org-match-string-no-properties 3)))
15875 (cond
15876 ((member-ignore-case key-base org-special-properties))
15877 (extendp
15878 (setq props
15879 (org--update-property-plist key value props)))
15880 ((member key seen-base))
15881 (t (push key seen-base)
15882 (let ((p (assoc-string key props t)))
15883 (if p (setcdr p (concat value " " (cdr p)))
15884 (push (cons key value) props))))))))))))
15885 (unless (assoc "CATEGORY" props)
15886 (push (cons "CATEGORY" (org-get-category beg)) props)
15887 (when (string= specific "CATEGORY") (throw 'exit props)))
15888 ;; Return value.
15889 props)))))
15891 (defun org-property--local-values (property literal-nil)
15892 "Return value for PROPERTY in current entry.
15893 Value is a list whose care is the base value for PROPERTY and cdr
15894 a list of accumulated values. Return nil if neither is found in
15895 the entry. Also return nil when PROPERTY is set to \"nil\",
15896 unless LITERAL-NIL is non-nil."
15897 (let ((range (org-get-property-block)))
15898 (when range
15899 (goto-char (car range))
15900 (let* ((case-fold-search t)
15901 (end (cdr range))
15902 (value
15903 ;; Base value.
15904 (save-excursion
15905 (let ((v (and (re-search-forward
15906 (org-re-property property nil t) end t)
15907 (org-match-string-no-properties 3))))
15908 (list (if literal-nil v (org-not-nil v)))))))
15909 ;; Find additional values.
15910 (let* ((property+ (org-re-property (concat property "+") nil t)))
15911 (while (re-search-forward property+ end t)
15912 (push (org-match-string-no-properties 3) value)))
15913 ;; Return final values.
15914 (and (not (equal value '(nil))) (nreverse value))))))
15916 (defun org-entry-get (pom property &optional inherit literal-nil)
15917 "Get value of PROPERTY for entry or content at point-or-marker POM.
15919 If INHERIT is non-nil and the entry does not have the property,
15920 then also check higher levels of the hierarchy. If INHERIT is
15921 the symbol `selective', use inheritance only if the setting in
15922 `org-use-property-inheritance' selects PROPERTY for inheritance.
15924 If the property is present but empty, the return value is the
15925 empty string. If the property is not present at all, nil is
15926 returned. In any other case, return the value as a string.
15927 Search is case-insensitive.
15929 If LITERAL-NIL is set, return the string value \"nil\" as
15930 a string, do not interpret it as the list atom nil. This is used
15931 for inheritance when a \"nil\" value can supersede a non-nil
15932 value higher up the hierarchy."
15933 (org-with-point-at pom
15934 (cond
15935 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15936 ;; We need a special property. Use `org-entry-properties' to
15937 ;; retrieve it, but specify the wanted property.
15938 (cdr (assoc-string property (org-entry-properties nil property))))
15939 ((and inherit
15940 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15941 (org-entry-get-with-inheritance property literal-nil))
15943 (let* ((local (org-property--local-values property literal-nil))
15944 (value (and local (mapconcat #'identity (delq nil local) " "))))
15945 (if literal-nil value (org-not-nil value)))))))
15947 (defun org-property-or-variable-value (var &optional inherit)
15948 "Check if there is a property fixing the value of VAR.
15949 If yes, return this value. If not, return the current value of the variable."
15950 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15951 (if (and prop (stringp prop) (string-match "\\S-" prop))
15952 (read prop)
15953 (symbol-value var))))
15955 (defun org-entry-delete (pom property)
15956 "Delete PROPERTY from entry at point-or-marker POM.
15957 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15958 non-nil when a property was removed."
15959 (unless (member property org-special-properties)
15960 (org-with-point-at pom
15961 (let ((range (org-get-property-block)))
15962 (when range
15963 (let* ((begin (car range))
15964 (origin (cdr range))
15965 (end (copy-marker origin))
15966 (re (org-re-property
15967 (concat (regexp-quote property) "\\+?") t t)))
15968 (goto-char begin)
15969 (while (re-search-forward re end t)
15970 (delete-region (match-beginning 0) (line-beginning-position 2)))
15971 ;; If drawer is empty, remove it altogether.
15972 (when (= begin end)
15973 (delete-region (line-beginning-position 0)
15974 (line-beginning-position 2)))
15975 ;; Return non-nil if some property was removed.
15976 (prog1 (/= end origin) (set-marker end nil))))))))
15978 ;; Multi-values properties are properties that contain multiple values
15979 ;; These values are assumed to be single words, separated by whitespace.
15980 (defun org-entry-add-to-multivalued-property (pom property value)
15981 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15982 (let* ((old (org-entry-get pom property))
15983 (values (and old (org-split-string old "[ \t]"))))
15984 (setq value (org-entry-protect-space value))
15985 (unless (member value values)
15986 (setq values (append values (list value)))
15987 (org-entry-put pom property
15988 (mapconcat 'identity values " ")))))
15990 (defun org-entry-remove-from-multivalued-property (pom property value)
15991 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15992 (let* ((old (org-entry-get pom property))
15993 (values (and old (org-split-string old "[ \t]"))))
15994 (setq value (org-entry-protect-space value))
15995 (when (member value values)
15996 (setq values (delete value values))
15997 (org-entry-put pom property
15998 (mapconcat 'identity values " ")))))
16000 (defun org-entry-member-in-multivalued-property (pom property value)
16001 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16002 (let* ((old (org-entry-get pom property))
16003 (values (and old (org-split-string old "[ \t]"))))
16004 (setq value (org-entry-protect-space value))
16005 (member value values)))
16007 (defun org-entry-get-multivalued-property (pom property)
16008 "Return a list of values in a multivalued property."
16009 (let* ((value (org-entry-get pom property))
16010 (values (and value (org-split-string value "[ \t]"))))
16011 (mapcar 'org-entry-restore-space values)))
16013 (defun org-entry-put-multivalued-property (pom property &rest values)
16014 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16015 VALUES should be a list of strings. Spaces will be protected."
16016 (org-entry-put pom property
16017 (mapconcat 'org-entry-protect-space values " "))
16018 (let* ((value (org-entry-get pom property))
16019 (values (and value (org-split-string value "[ \t]"))))
16020 (mapcar 'org-entry-restore-space values)))
16022 (defun org-entry-protect-space (s)
16023 "Protect spaces and newline in string S."
16024 (while (string-match " " s)
16025 (setq s (replace-match "%20" t t s)))
16026 (while (string-match "\n" s)
16027 (setq s (replace-match "%0A" t t s)))
16030 (defun org-entry-restore-space (s)
16031 "Restore spaces and newline in string S."
16032 (while (string-match "%20" s)
16033 (setq s (replace-match " " t t s)))
16034 (while (string-match "%0A" s)
16035 (setq s (replace-match "\n" t t s)))
16038 (defvar org-entry-property-inherited-from (make-marker)
16039 "Marker pointing to the entry from where a property was inherited.
16040 Each call to `org-entry-get-with-inheritance' will set this marker to the
16041 location of the entry where the inheritance search matched. If there was
16042 no match, the marker will point nowhere.
16043 Note that also `org-entry-get' calls this function, if the INHERIT flag
16044 is set.")
16046 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16047 "Get PROPERTY of entry or content at point, search higher levels if needed.
16048 The search will stop at the first ancestor which has the property defined.
16049 If the value found is \"nil\", return nil to show that the property
16050 should be considered as undefined (this is the meaning of nil here).
16051 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16052 (move-marker org-entry-property-inherited-from nil)
16053 (org-with-wide-buffer
16054 (let (value)
16055 (catch 'exit
16056 (while t
16057 (let ((v (org-property--local-values property literal-nil)))
16058 (when v
16059 (setq value
16060 (concat (mapconcat #'identity (delq nil v) " ")
16061 (and value " ")
16062 value)))
16063 (cond
16064 ((car v)
16065 (org-back-to-heading t)
16066 (move-marker org-entry-property-inherited-from (point))
16067 (throw 'exit nil))
16068 ((org-up-heading-safe))
16070 (let ((global
16071 (cdr (or (assoc-string property org-file-properties t)
16072 (assoc-string property org-global-properties t)
16073 (assoc-string property org-global-properties-fixed t)))))
16074 (cond ((not global))
16075 (value (setq value (concat global " " value)))
16076 (t (setq value global))))
16077 (throw 'exit nil))))))
16078 (if literal-nil value (org-not-nil value)))))
16080 (defvar org-property-changed-functions nil
16081 "Hook called when the value of a property has changed.
16082 Each hook function should accept two arguments, the name of the property
16083 and the new value.")
16085 (defun org-entry-put (pom property value)
16086 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16088 If the value is nil, it is converted to the empty string. If
16089 it is not a string, an error is raised.
16091 PROPERTY can be any regular property (see
16092 `org-special-properties'). It can also be \"TODO\",
16093 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16095 For the last two properties, VALUE may have any of the special
16096 values \"earlier\" and \"later\". The function then increases or
16097 decreases scheduled or deadline date by one day."
16098 (cond ((null value) (setq value ""))
16099 ((not (stringp value)) (error "Properties values should be strings")))
16100 (org-with-point-at pom
16101 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16102 (org-back-to-heading t)
16103 (org-with-limited-levels (org-back-to-heading t)))
16104 (let ((beg (point)))
16105 (cond
16106 ((equal property "TODO")
16107 (cond ((not (org-string-nw-p value)) (setq value 'none))
16108 ((not (member value org-todo-keywords-1))
16109 (user-error "\"%s\" is not a valid TODO state" value)))
16110 (org-todo value)
16111 (org-set-tags nil 'align))
16112 ((equal property "PRIORITY")
16113 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16114 (org-set-tags nil 'align))
16115 ((equal property "SCHEDULED")
16116 (forward-line)
16117 (if (and (org-looking-at-p org-planning-line-re)
16118 (re-search-forward
16119 org-scheduled-time-regexp (line-end-position) t))
16120 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16121 ((string= value "later") (org-timestamp-change 1 'day))
16122 ((string= value "") (org-schedule '(4)))
16123 (t (org-schedule nil value)))
16124 (if (member value '("earlier" "later" ""))
16125 (call-interactively #'org-schedule)
16126 (org-schedule nil value))))
16127 ((equal property "DEADLINE")
16128 (forward-line)
16129 (if (and (org-looking-at-p org-planning-line-re)
16130 (re-search-forward
16131 org-deadline-time-regexp (line-end-position) t))
16132 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16133 ((string= value "later") (org-timestamp-change 1 'day))
16134 ((string= value "") (org-deadline '(4)))
16135 (t (org-deadline nil value)))
16136 (if (member value '("earlier" "later" ""))
16137 (call-interactively #'org-deadline)
16138 (org-deadline nil value))))
16139 ((member property org-special-properties)
16140 (error "The %s property cannot be set with `org-entry-put'" property))
16142 (let* ((range (org-get-property-block beg 'force))
16143 (end (cdr range))
16144 (case-fold-search t))
16145 (goto-char (car range))
16146 (if (re-search-forward (org-re-property property nil t) end t)
16147 (progn (delete-region (match-beginning 0) (match-end 0))
16148 (goto-char (match-beginning 0)))
16149 (goto-char end)
16150 (insert "\n")
16151 (backward-char))
16152 (insert ":" property ":")
16153 (when value (insert " " value))
16154 (org-indent-line)))))
16155 (run-hook-with-args 'org-property-changed-functions property value)))
16157 (defun org-buffer-property-keys (&optional specials defaults columns)
16158 "Get all property keys in the current buffer.
16160 When SPECIALS is non-nil, also list the special properties that
16161 reflect things like tags and TODO state.
16163 When DEFAULTS is non-nil, also include properties that has
16164 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16165 DESCRIPTION, LOCATION, and LOGGING and others.
16167 When COLUMNS in non-nil, also include property names given in
16168 COLUMN formats in the current buffer."
16169 (let ((case-fold-search t)
16170 (props (append
16171 (and specials org-special-properties)
16172 (and defaults (cons org-effort-property org-default-properties))
16173 nil)))
16174 (org-with-wide-buffer
16175 (goto-char (point-min))
16176 (while (re-search-forward org-property-start-re nil t)
16177 (let ((range (org-get-property-block)))
16178 (catch 'skip
16179 (unless range
16180 (when (and (not (org-before-first-heading-p))
16181 (y-or-n-p (format "Malformed drawer at %d, repair?"
16182 (line-beginning-position))))
16183 (org-get-property-block nil t))
16184 (throw 'skip nil))
16185 (goto-char (car range))
16186 (let ((begin (car range))
16187 (end (cdr range)))
16188 ;; Make sure that found property block is not located
16189 ;; before current point, as it would generate an infloop.
16190 ;; It can happen, for example, in the following
16191 ;; situation:
16193 ;; * Headline
16194 ;; :PROPERTIES:
16195 ;; ...
16196 ;; :END:
16197 ;; *************** Inlinetask
16198 ;; #+BEGIN_EXAMPLE
16199 ;; :PROPERTIES:
16200 ;; #+END_EXAMPLE
16202 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16203 (while (< (point) end)
16204 (let ((p (progn (looking-at org-property-re)
16205 (org-match-string-no-properties 2))))
16206 ;; Only add true property name, not extension symbol.
16207 (add-to-list 'props
16208 (if (not (org-string-match-p "\\+\\'" p)) p
16209 (substring p 0 -1))))
16210 (forward-line))))
16211 (outline-next-heading)))
16212 (when columns
16213 (goto-char (point-min))
16214 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16215 (let ((element (org-element-at-point)))
16216 (when (memq (org-element-type element) '(keyword node-property))
16217 (let ((value (org-element-property :value element))
16218 (start 0))
16219 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16220 (setq start (match-end 0))
16221 (let ((p (org-match-string-no-properties 1 value)))
16222 (unless (member-ignore-case p org-special-properties)
16223 (add-to-list 'props p))))))))))
16224 (sort props (lambda (a b) (string< (upcase a) (upcase b))))))
16226 (defun org-property-values (key)
16227 "List all non-nil values of property KEY in current buffer."
16228 (org-with-wide-buffer
16229 (goto-char (point-min))
16230 (let ((case-fold-search t)
16231 (re (org-re-property key))
16232 values)
16233 (while (re-search-forward re nil t)
16234 (add-to-list 'values (org-entry-get (point) key)))
16235 values)))
16237 (defun org-insert-property-drawer ()
16238 "Insert a property drawer into the current entry."
16239 (org-with-wide-buffer
16240 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16241 (org-back-to-heading t)
16242 (org-with-limited-levels (org-back-to-heading t)))
16243 (forward-line)
16244 (when (org-looking-at-p org-planning-line-re) (forward-line))
16245 (unless (org-looking-at-p org-property-drawer-re)
16246 ;; Make sure we start editing a line from current entry, not from
16247 ;; next one. It prevents extending text properties or overlays
16248 ;; belonging to the latter.
16249 (when (bolp) (backward-char))
16250 (let ((begin (1+ (point)))
16251 (inhibit-read-only t))
16252 (insert "\n:PROPERTIES:\n:END:")
16253 (when (eobp) (insert "\n"))
16254 (org-indent-region begin (point))))))
16256 (defun org-insert-drawer (&optional arg drawer)
16257 "Insert a drawer at point.
16259 When optional argument ARG is non-nil, insert a property drawer.
16261 Optional argument DRAWER, when non-nil, is a string representing
16262 drawer's name. Otherwise, the user is prompted for a name.
16264 If a region is active, insert the drawer around that region
16265 instead.
16267 Point is left between drawer's boundaries."
16268 (interactive "P")
16269 (let* ((drawer (if arg "PROPERTIES"
16270 (or drawer (read-from-minibuffer "Drawer: ")))))
16271 (cond
16272 ;; With C-u, fall back on `org-insert-property-drawer'
16273 (arg (org-insert-property-drawer))
16274 ;; Check validity of suggested drawer's name.
16275 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
16276 (user-error "Invalid drawer name"))
16277 ;; With an active region, insert a drawer at point.
16278 ((not (org-region-active-p))
16279 (progn
16280 (unless (bolp) (insert "\n"))
16281 (insert (format ":%s:\n\n:END:\n" drawer))
16282 (forward-line -2)))
16283 ;; Otherwise, insert the drawer at point
16285 (let ((rbeg (region-beginning))
16286 (rend (copy-marker (region-end))))
16287 (unwind-protect
16288 (progn
16289 (goto-char rbeg)
16290 (beginning-of-line)
16291 (when (save-excursion
16292 (re-search-forward org-outline-regexp-bol rend t))
16293 (user-error "Drawers cannot contain headlines"))
16294 ;; Position point at the beginning of the first
16295 ;; non-blank line in region. Insert drawer's opening
16296 ;; there, then indent it.
16297 (org-skip-whitespace)
16298 (beginning-of-line)
16299 (insert ":" drawer ":\n")
16300 (forward-line -1)
16301 (indent-for-tab-command)
16302 ;; Move point to the beginning of the first blank line
16303 ;; after the last non-blank line in region. Insert
16304 ;; drawer's closing, then indent it.
16305 (goto-char rend)
16306 (skip-chars-backward " \r\t\n")
16307 (insert "\n:END:")
16308 (deactivate-mark t)
16309 (indent-for-tab-command)
16310 (unless (eolp) (insert "\n")))
16311 ;; Clear marker, whatever the outcome of insertion is.
16312 (set-marker rend nil)))))))
16314 (defvar org-property-set-functions-alist nil
16315 "Property set function alist.
16316 Each entry should have the following format:
16318 (PROPERTY . READ-FUNCTION)
16320 The read function will be called with the same argument as
16321 `org-completing-read'.")
16323 (defun org-set-property-function (property)
16324 "Get the function that should be used to set PROPERTY.
16325 This is computed according to `org-property-set-functions-alist'."
16326 (or (cdr (assoc property org-property-set-functions-alist))
16327 'org-completing-read))
16329 (defun org-read-property-value (property)
16330 "Read PROPERTY value from user."
16331 (let* ((completion-ignore-case t)
16332 (allowed (org-property-get-allowed-values nil property 'table))
16333 (cur (org-entry-get nil property))
16334 (prompt (concat property " value"
16335 (if (and cur (string-match "\\S-" cur))
16336 (concat " [" cur "]") "") ": "))
16337 (set-function (org-set-property-function property))
16338 (val (if allowed
16339 (funcall set-function prompt allowed nil
16340 (not (get-text-property 0 'org-unrestricted
16341 (caar allowed))))
16342 (let (org-completion-use-ido org-completion-use-iswitchb)
16343 (funcall set-function prompt
16344 (mapcar 'list (org-property-values property))
16345 nil nil "" nil cur)))))
16346 (org-trim val)))
16348 (defvar org-last-set-property nil)
16349 (defvar org-last-set-property-value nil)
16350 (defun org-read-property-name ()
16351 "Read a property name."
16352 (let ((completion-ignore-case t)
16353 (default-prop (or (and (org-at-property-p)
16354 (org-match-string-no-properties 2))
16355 org-last-set-property)))
16356 (org-completing-read
16357 (concat "Property"
16358 (if default-prop (concat " [" default-prop "]") "")
16359 ": ")
16360 (mapcar #'list (org-buffer-property-keys nil t t))
16361 nil nil nil nil default-prop)))
16363 (defun org-set-property-and-value (use-last)
16364 "Allow to set [PROPERTY]: [value] direction from prompt.
16365 When use-default, don't even ask, just use the last
16366 \"[PROPERTY]: [value]\" string from the history."
16367 (interactive "P")
16368 (let* ((completion-ignore-case t)
16369 (pv (or (and use-last org-last-set-property-value)
16370 (org-completing-read
16371 "Enter a \"[Property]: [value]\" pair: "
16372 nil nil nil nil nil
16373 org-last-set-property-value)))
16374 prop val)
16375 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16376 (setq prop (match-string 1 pv)
16377 val (match-string 2 pv))
16378 (org-set-property prop val))))
16380 (defun org-set-property (property value)
16381 "In the current entry, set PROPERTY to VALUE.
16382 When called interactively, this will prompt for a property name, offering
16383 completion on existing and default properties. And then it will prompt
16384 for a value, offering completion either on allowed values (via an inherited
16385 xxx_ALL property) or on existing values in other instances of this property
16386 in the current file."
16387 (interactive (list nil nil))
16388 (let* ((property (or property (org-read-property-name)))
16389 (value (or value (org-read-property-value property)))
16390 (fn (cdr (assoc property org-properties-postprocess-alist))))
16391 (setq org-last-set-property property)
16392 (setq org-last-set-property-value (concat property ": " value))
16393 ;; Possibly postprocess the inserted value:
16394 (when fn (setq value (funcall fn value)))
16395 (unless (equal (org-entry-get nil property) value)
16396 (org-entry-put nil property value))))
16398 (defun org-find-property (property &optional value)
16399 "Find first entry in buffer that sets PROPERTY.
16401 When optional argument VALUE is non-nil, only consider an entry
16402 if it contains PROPERTY set to this value. If PROPERTY should be
16403 explicitly set to nil, use string \"nil\" for VALUE.
16405 Return position where the entry begins, or nil if there is no
16406 such entry. If narrowing is in effect, only search the visible
16407 part of the buffer."
16408 (save-excursion
16409 (goto-char (point-min))
16410 (let ((case-fold-search t)
16411 (re (org-re-property property nil (not value) value)))
16412 (catch 'exit
16413 (while (re-search-forward re nil t)
16414 (when (if value (org-at-property-p)
16415 (org-entry-get (point) property nil t))
16416 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16418 (defun org-delete-property (property)
16419 "In the current entry, delete PROPERTY."
16420 (interactive
16421 (let* ((completion-ignore-case t)
16422 (cat (org-entry-get (point) "CATEGORY"))
16423 (props0 (org-entry-properties nil 'standard))
16424 (props (if cat props0
16425 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16426 (prop (if (< 1 (length props))
16427 (org-icompleting-read "Property: " props nil t)
16428 (caar props))))
16429 (list prop)))
16430 (if (not property)
16431 (message "No property to delete in this entry")
16432 (org-entry-delete nil property)
16433 (message "Property \"%s\" deleted" property)))
16435 (defun org-delete-property-globally (property)
16436 "Remove PROPERTY globally, from all entries.
16437 This function ignores narrowing, if any."
16438 (interactive
16439 (let* ((completion-ignore-case t)
16440 (prop (org-icompleting-read
16441 "Globally remove property: "
16442 (mapcar #'list (org-buffer-property-keys)))))
16443 (list prop)))
16444 (org-with-wide-buffer
16445 (goto-char (point-min))
16446 (let ((count 0)
16447 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16448 (while (re-search-forward re nil t)
16449 (when (org-entry-delete (point) property) (incf count)))
16450 (message "Property \"%s\" removed from %d entries" property count))))
16452 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16454 (defun org-compute-property-at-point ()
16455 "Compute the property at point.
16456 This looks for an enclosing column format, extracts the operator and
16457 then applies it to the property in the column format's scope."
16458 (interactive)
16459 (unless (org-at-property-p)
16460 (user-error "Not at a property"))
16461 (let ((prop (org-match-string-no-properties 2)))
16462 (org-columns-get-format-and-top-level)
16463 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16464 (user-error "No operator defined for property %s" prop))
16465 (org-columns-compute prop)))
16467 (defvar org-property-allowed-value-functions nil
16468 "Hook for functions supplying allowed values for a specific property.
16469 The functions must take a single argument, the name of the property, and
16470 return a flat list of allowed values. If \":ETC\" is one of
16471 the values, this means that these values are intended as defaults for
16472 completion, but that other values should be allowed too.
16473 The functions must return nil if they are not responsible for this
16474 property.")
16476 (defun org-property-get-allowed-values (pom property &optional table)
16477 "Get allowed values for the property PROPERTY.
16478 When TABLE is non-nil, return an alist that can directly be used for
16479 completion."
16480 (let (vals)
16481 (cond
16482 ((equal property "TODO")
16483 (setq vals (org-with-point-at pom
16484 (append org-todo-keywords-1 '("")))))
16485 ((equal property "PRIORITY")
16486 (let ((n org-lowest-priority))
16487 (while (>= n org-highest-priority)
16488 (push (char-to-string n) vals)
16489 (setq n (1- n)))))
16490 ((equal property "CATEGORY"))
16491 ((member property org-special-properties))
16492 ((setq vals (run-hook-with-args-until-success
16493 'org-property-allowed-value-functions property)))
16495 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16496 (when (and vals (string-match "\\S-" vals))
16497 (setq vals (car (read-from-string (concat "(" vals ")"))))
16498 (setq vals (mapcar (lambda (x)
16499 (cond ((stringp x) x)
16500 ((numberp x) (number-to-string x))
16501 ((symbolp x) (symbol-name x))
16502 (t "???")))
16503 vals)))))
16504 (when (member ":ETC" vals)
16505 (setq vals (remove ":ETC" vals))
16506 (org-add-props (car vals) '(org-unrestricted t)))
16507 (if table (mapcar 'list vals) vals)))
16509 (defun org-property-previous-allowed-value (&optional previous)
16510 "Switch to the next allowed value for this property."
16511 (interactive)
16512 (org-property-next-allowed-value t))
16514 (defun org-property-next-allowed-value (&optional previous)
16515 "Switch to the next allowed value for this property."
16516 (interactive)
16517 (unless (org-at-property-p)
16518 (user-error "Not at a property"))
16519 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16520 (key (match-string 2))
16521 (value (match-string 3))
16522 (allowed (or (org-property-get-allowed-values (point) key)
16523 (and (member value '("[ ]" "[-]" "[X]"))
16524 '("[ ]" "[X]"))))
16525 (heading (save-match-data (nth 4 (org-heading-components))))
16526 nval)
16527 (unless allowed
16528 (user-error "Allowed values for this property have not been defined"))
16529 (if previous (setq allowed (reverse allowed)))
16530 (if (member value allowed)
16531 (setq nval (car (cdr (member value allowed)))))
16532 (setq nval (or nval (car allowed)))
16533 (if (equal nval value)
16534 (user-error "Only one allowed value for this property"))
16535 (org-at-property-p)
16536 (replace-match (concat " :" key ": " nval) t t)
16537 (org-indent-line)
16538 (beginning-of-line 1)
16539 (skip-chars-forward " \t")
16540 (when (equal prop org-effort-property)
16541 (org-refresh-property
16542 '((effort . identity)
16543 (effort-minutes . org-duration-string-to-minutes))
16544 nval)
16545 (when (string= org-clock-current-task heading)
16546 (setq org-clock-effort nval)
16547 (org-clock-update-mode-line)))
16548 (run-hook-with-args 'org-property-changed-functions key nval)))
16550 (defun org-find-olp (path &optional this-buffer)
16551 "Return a marker pointing to the entry at outline path OLP.
16552 If anything goes wrong, throw an error.
16553 You can wrap this call to catch the error like this:
16555 (condition-case msg
16556 (org-mobile-locate-entry (match-string 4))
16557 (error (nth 1 msg)))
16559 The return value will then be either a string with the error message,
16560 or a marker if everything is OK.
16562 If THIS-BUFFER is set, the outline path does not contain a file,
16563 only headings."
16564 (let* ((file (if this-buffer buffer-file-name (pop path)))
16565 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16566 (level 1)
16567 (lmin 1)
16568 (lmax 1)
16569 limit re end found pos heading cnt flevel)
16570 (unless buffer (error "File not found :%s" file))
16571 (with-current-buffer buffer
16572 (save-excursion
16573 (save-restriction
16574 (widen)
16575 (setq limit (point-max))
16576 (goto-char (point-min))
16577 (dolist (heading path)
16578 (setq re (format org-complex-heading-regexp-format
16579 (regexp-quote heading)))
16580 (setq cnt 0 pos (point))
16581 (while (re-search-forward re end t)
16582 (setq level (- (match-end 1) (match-beginning 1)))
16583 (if (and (>= level lmin) (<= level lmax))
16584 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16585 (when (= cnt 0) (error "Heading not found on level %d: %s"
16586 lmax heading))
16587 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16588 lmax heading))
16589 (goto-char found)
16590 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16591 (setq end (save-excursion (org-end-of-subtree t t))))
16592 (when (org-at-heading-p)
16593 (point-marker)))))))
16595 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16596 "Find node HEADING in BUFFER.
16597 Return a marker to the heading if it was found, or nil if not.
16598 If POS-ONLY is set, return just the position instead of a marker.
16600 The heading text must match exact, but it may have a TODO keyword,
16601 a priority cookie and tags in the standard locations."
16602 (with-current-buffer (or buffer (current-buffer))
16603 (save-excursion
16604 (save-restriction
16605 (widen)
16606 (goto-char (point-min))
16607 (let (case-fold-search)
16608 (if (re-search-forward
16609 (format org-complex-heading-regexp-format
16610 (regexp-quote heading)) nil t)
16611 (if pos-only
16612 (match-beginning 0)
16613 (move-marker (make-marker) (match-beginning 0)))))))))
16615 (defun org-find-exact-heading-in-directory (heading &optional dir)
16616 "Find Org node headline HEADING in all .org files in directory DIR.
16617 When the target headline is found, return a marker to this location."
16618 (let ((files (directory-files (or dir default-directory)
16619 t "\\`[^.#].*\\.org\\'"))
16620 visiting m buffer)
16621 (catch 'found
16622 (dolist (file files)
16623 (message "trying %s" file)
16624 (setq visiting (org-find-base-buffer-visiting file))
16625 (setq buffer (or visiting (find-file-noselect file)))
16626 (setq m (org-find-exact-headline-in-buffer
16627 heading buffer))
16628 (when (and (not m) (not visiting)) (kill-buffer buffer))
16629 (and m (throw 'found m))))))
16631 (defun org-find-entry-with-id (ident)
16632 "Locate the entry that contains the ID property with exact value IDENT.
16633 IDENT can be a string, a symbol or a number, this function will search for
16634 the string representation of it.
16635 Return the position where this entry starts, or nil if there is no such entry."
16636 (interactive "sID: ")
16637 (let ((id (cond
16638 ((stringp ident) ident)
16639 ((symbolp ident) (symbol-name ident))
16640 ((numberp ident) (number-to-string ident))
16641 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16642 (org-with-wide-buffer (org-find-property "ID" id))))
16644 ;;;; Timestamps
16646 (defvar org-last-changed-timestamp nil)
16647 (defvar org-last-inserted-timestamp nil
16648 "The last time stamp inserted with `org-insert-time-stamp'.")
16649 (defvar org-ts-what) ; dynamically scoped parameter
16651 (defun org-time-stamp (arg &optional inactive)
16652 "Prompt for a date/time and insert a time stamp.
16654 If the user specifies a time like HH:MM or if this command is
16655 called with at least one prefix argument, the time stamp contains
16656 the date and the time. Otherwise, only the date is included.
16658 All parts of a date not specified by the user are filled in from
16659 the timestamp at point, if any, or the current date/time
16660 otherwise.
16662 If there is already a timestamp at the cursor, it is replaced.
16664 With two universal prefix arguments, insert an active timestamp
16665 with the current time without prompting the user.
16667 When called from lisp, the timestamp is inactive if INACTIVE is
16668 non-nil."
16669 (interactive "P")
16670 (let* ((ts (cond
16671 ((org-at-date-range-p t)
16672 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16673 ((org-at-timestamp-p t) (match-string 0))))
16674 ;; Default time is either the timestamp at point or today.
16675 ;; When entering a range, only the range start is considered.
16676 (default-time (if (not ts) (current-time)
16677 (apply #'encode-time (org-parse-time-string ts))))
16678 (default-input (and ts (org-get-compact-tod ts)))
16679 (repeater (and ts
16680 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16681 (match-string 0 ts)))
16682 org-time-was-given
16683 org-end-time-was-given
16684 (time
16685 (and (if (equal arg '(16)) (current-time)
16686 ;; Preserve `this-command' and `last-command'.
16687 (let ((this-command this-command)
16688 (last-command last-command))
16689 (org-read-date
16690 arg 'totime nil nil default-time default-input
16691 inactive))))))
16692 (cond
16693 ((and ts
16694 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16695 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16696 (insert "--")
16697 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16699 ;; Make sure we're on a timestamp. When in the middle of a date
16700 ;; range, move arbitrarily to range end.
16701 (unless (org-at-timestamp-p t)
16702 (skip-chars-forward "-")
16703 (org-at-timestamp-p t))
16704 (replace-match "")
16705 (setq org-last-changed-timestamp
16706 (org-insert-time-stamp
16707 time (or org-time-was-given arg)
16708 inactive nil nil (list org-end-time-was-given)))
16709 (when repeater
16710 (backward-char)
16711 (insert " " repeater)
16712 (setq org-last-changed-timestamp
16713 (concat (substring org-last-inserted-timestamp 0 -1)
16714 " " repeater ">")))
16715 (message "Timestamp updated"))
16716 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16717 (t (org-insert-time-stamp
16718 time (or org-time-was-given arg) inactive nil nil
16719 (list org-end-time-was-given))))))
16721 ;; FIXME: can we use this for something else, like computing time differences?
16722 (defun org-get-compact-tod (s)
16723 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16724 (let* ((t1 (match-string 1 s))
16725 (h1 (string-to-number (match-string 2 s)))
16726 (m1 (string-to-number (match-string 3 s)))
16727 (t2 (and (match-end 4) (match-string 5 s)))
16728 (h2 (and t2 (string-to-number (match-string 6 s))))
16729 (m2 (and t2 (string-to-number (match-string 7 s))))
16730 dh dm)
16731 (if (not t2)
16733 (setq dh (- h2 h1) dm (- m2 m1))
16734 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16735 (concat t1 "+" (number-to-string dh)
16736 (and (/= 0 dm) (format ":%02d" dm)))))))
16738 (defun org-time-stamp-inactive (&optional arg)
16739 "Insert an inactive time stamp.
16740 An inactive time stamp is enclosed in square brackets instead of angle
16741 brackets. It is inactive in the sense that it does not trigger agenda entries,
16742 does not link to the calendar and cannot be changed with the S-cursor keys.
16743 So these are more for recording a certain time/date."
16744 (interactive "P")
16745 (org-time-stamp arg 'inactive))
16747 (defvar org-date-ovl (make-overlay 1 1))
16748 (overlay-put org-date-ovl 'face 'org-date-selected)
16749 (org-detach-overlay org-date-ovl)
16751 (defvar org-ans1) ; dynamically scoped parameter
16752 (defvar org-ans2) ; dynamically scoped parameter
16754 (defvar org-plain-time-of-day-regexp) ; defined below
16756 (defvar org-overriding-default-time nil) ; dynamically scoped
16757 (defvar org-read-date-overlay nil)
16758 (defvar org-dcst nil) ; dynamically scoped
16759 (defvar org-read-date-history nil)
16760 (defvar org-read-date-final-answer nil)
16761 (defvar org-read-date-analyze-futurep nil)
16762 (defvar org-read-date-analyze-forced-year nil)
16763 (defvar org-read-date-inactive)
16765 (defvar org-read-date-minibuffer-local-map
16766 (let* ((map (make-sparse-keymap)))
16767 (set-keymap-parent map minibuffer-local-map)
16768 (org-defkey map (kbd ".")
16769 (lambda () (interactive)
16770 ;; Are we at the beginning of the prompt?
16771 (if (org-looking-back "^[^:]+: " (line-beginning-position))
16772 (org-eval-in-calendar '(calendar-goto-today))
16773 (insert "."))))
16774 (org-defkey map (kbd "C-.")
16775 (lambda () (interactive)
16776 (org-eval-in-calendar '(calendar-goto-today))))
16777 (org-defkey map [(meta shift left)]
16778 (lambda () (interactive)
16779 (org-eval-in-calendar '(calendar-backward-month 1))))
16780 (org-defkey map [(meta shift right)]
16781 (lambda () (interactive)
16782 (org-eval-in-calendar '(calendar-forward-month 1))))
16783 (org-defkey map [(meta shift up)]
16784 (lambda () (interactive)
16785 (org-eval-in-calendar '(calendar-backward-year 1))))
16786 (org-defkey map [(meta shift down)]
16787 (lambda () (interactive)
16788 (org-eval-in-calendar '(calendar-forward-year 1))))
16789 (org-defkey map [?\e (shift left)]
16790 (lambda () (interactive)
16791 (org-eval-in-calendar '(calendar-backward-month 1))))
16792 (org-defkey map [?\e (shift right)]
16793 (lambda () (interactive)
16794 (org-eval-in-calendar '(calendar-forward-month 1))))
16795 (org-defkey map [?\e (shift up)]
16796 (lambda () (interactive)
16797 (org-eval-in-calendar '(calendar-backward-year 1))))
16798 (org-defkey map [?\e (shift down)]
16799 (lambda () (interactive)
16800 (org-eval-in-calendar '(calendar-forward-year 1))))
16801 (org-defkey map [(shift up)]
16802 (lambda () (interactive)
16803 (org-eval-in-calendar '(calendar-backward-week 1))))
16804 (org-defkey map [(shift down)]
16805 (lambda () (interactive)
16806 (org-eval-in-calendar '(calendar-forward-week 1))))
16807 (org-defkey map [(shift left)]
16808 (lambda () (interactive)
16809 (org-eval-in-calendar '(calendar-backward-day 1))))
16810 (org-defkey map [(shift right)]
16811 (lambda () (interactive)
16812 (org-eval-in-calendar '(calendar-forward-day 1))))
16813 (org-defkey map "!"
16814 (lambda () (interactive)
16815 (org-eval-in-calendar '(diary-view-entries))
16816 (message "")))
16817 (org-defkey map ">"
16818 (lambda () (interactive)
16819 (org-eval-in-calendar '(calendar-scroll-left 1))))
16820 (org-defkey map "<"
16821 (lambda () (interactive)
16822 (org-eval-in-calendar '(calendar-scroll-right 1))))
16823 (org-defkey map "\C-v"
16824 (lambda () (interactive)
16825 (org-eval-in-calendar
16826 '(calendar-scroll-left-three-months 1))))
16827 (org-defkey map "\M-v"
16828 (lambda () (interactive)
16829 (org-eval-in-calendar
16830 '(calendar-scroll-right-three-months 1))))
16831 map)
16832 "Keymap for minibuffer commands when using `org-read-date'.")
16834 (defvar org-def)
16835 (defvar org-defdecode)
16836 (defvar org-with-time)
16838 (defun org-read-date (&optional org-with-time to-time from-string prompt
16839 default-time default-input inactive)
16840 "Read a date, possibly a time, and make things smooth for the user.
16841 The prompt will suggest to enter an ISO date, but you can also enter anything
16842 which will at least partially be understood by `parse-time-string'.
16843 Unrecognized parts of the date will default to the current day, month, year,
16844 hour and minute. If this command is called to replace a timestamp at point,
16845 or to enter the second timestamp of a range, the default time is taken
16846 from the existing stamp. Furthermore, the command prefers the future,
16847 so if you are giving a date where the year is not given, and the day-month
16848 combination is already past in the current year, it will assume you
16849 mean next year. For details, see the manual. A few examples:
16851 3-2-5 --> 2003-02-05
16852 feb 15 --> currentyear-02-15
16853 2/15 --> currentyear-02-15
16854 sep 12 9 --> 2009-09-12
16855 12:45 --> today 12:45
16856 22 sept 0:34 --> currentyear-09-22 0:34
16857 12 --> currentyear-currentmonth-12
16858 Fri --> nearest Friday after today
16859 -Tue --> last Tuesday
16860 etc.
16862 Furthermore you can specify a relative date by giving, as the *first* thing
16863 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16864 change in days weeks, months, years.
16865 With a single plus or minus, the date is relative to today. With a double
16866 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16867 +4d --> four days from today
16868 +4 --> same as above
16869 +2w --> two weeks from today
16870 ++5 --> five days from default date
16872 The function understands only English month and weekday abbreviations.
16874 While prompting, a calendar is popped up - you can also select the
16875 date with the mouse (button 1). The calendar shows a period of three
16876 months. To scroll it to other months, use the keys `>' and `<'.
16877 If you don't like the calendar, turn it off with
16878 (setq org-read-date-popup-calendar nil)
16880 With optional argument TO-TIME, the date will immediately be converted
16881 to an internal time.
16882 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16883 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16884 still enter a time, and this function will inform the calling routine
16885 about this change. The calling routine may then choose to change the
16886 format used to insert the time stamp into the buffer to include the time.
16887 With optional argument FROM-STRING, read from this string instead from
16888 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16889 the time/date that is used for everything that is not specified by the
16890 user."
16891 (require 'parse-time)
16892 (let* ((org-time-stamp-rounding-minutes
16893 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16894 (org-dcst org-display-custom-times)
16895 (ct (org-current-time))
16896 (org-def (or org-overriding-default-time default-time ct))
16897 (org-defdecode (decode-time org-def))
16898 (dummy (progn
16899 (when (< (nth 2 org-defdecode) org-extend-today-until)
16900 (setcar (nthcdr 2 org-defdecode) -1)
16901 (setcar (nthcdr 1 org-defdecode) 59)
16902 (setq org-def (apply 'encode-time org-defdecode)
16903 org-defdecode (decode-time org-def)))))
16904 (cur-frame (selected-frame))
16905 (mouse-autoselect-window nil) ; Don't let the mouse jump
16906 (calendar-frame-setup nil)
16907 (calendar-setup (when (eq calendar-setup 'calendar-only) 'calendar-only))
16908 (calendar-move-hook nil)
16909 (calendar-view-diary-initially-flag nil)
16910 (calendar-view-holidays-initially-flag nil)
16911 (timestr (format-time-string
16912 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16913 (prompt (concat (if prompt (concat prompt " ") "")
16914 (format "Date+time [%s]: " timestr)))
16915 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16917 (cond
16918 (from-string (setq ans from-string))
16919 (org-read-date-popup-calendar
16920 (save-excursion
16921 (save-window-excursion
16922 (calendar)
16923 (when (eq calendar-setup 'calendar-only)
16924 (setq cal-frame
16925 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16926 (select-frame cal-frame))
16927 (org-eval-in-calendar '(setq cursor-type nil) t)
16928 (unwind-protect
16929 (progn
16930 (calendar-forward-day (- (time-to-days org-def)
16931 (calendar-absolute-from-gregorian
16932 (calendar-current-date))))
16933 (org-eval-in-calendar nil t)
16934 (let* ((old-map (current-local-map))
16935 (map (copy-keymap calendar-mode-map))
16936 (minibuffer-local-map
16937 (copy-keymap org-read-date-minibuffer-local-map)))
16938 (org-defkey map (kbd "RET") 'org-calendar-select)
16939 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16940 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16941 (unwind-protect
16942 (progn
16943 (use-local-map map)
16944 (setq org-read-date-inactive inactive)
16945 (add-hook 'post-command-hook 'org-read-date-display)
16946 (setq org-ans0 (read-string prompt default-input
16947 'org-read-date-history nil))
16948 ;; org-ans0: from prompt
16949 ;; org-ans1: from mouse click
16950 ;; org-ans2: from calendar motion
16951 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16952 (remove-hook 'post-command-hook 'org-read-date-display)
16953 (use-local-map old-map)
16954 (when org-read-date-overlay
16955 (delete-overlay org-read-date-overlay)
16956 (setq org-read-date-overlay nil)))))
16957 (bury-buffer "*Calendar*")
16958 (when cal-frame
16959 (delete-frame cal-frame)
16960 (select-frame-set-input-focus cur-frame))))))
16962 (t ; Naked prompt only
16963 (unwind-protect
16964 (setq ans (read-string prompt default-input
16965 'org-read-date-history timestr))
16966 (when org-read-date-overlay
16967 (delete-overlay org-read-date-overlay)
16968 (setq org-read-date-overlay nil)))))
16970 (setq final (org-read-date-analyze ans org-def org-defdecode))
16972 (when org-read-date-analyze-forced-year
16973 (message "Year was forced into %s"
16974 (if org-read-date-force-compatible-dates
16975 "compatible range (1970-2037)"
16976 "range representable on this machine"))
16977 (ding))
16979 ;; One round trip to get rid of 34th of August and stuff like that....
16980 (setq final (decode-time (apply 'encode-time final)))
16982 (setq org-read-date-final-answer ans)
16984 (if to-time
16985 (apply 'encode-time final)
16986 (if (and (boundp 'org-time-was-given) org-time-was-given)
16987 (format "%04d-%02d-%02d %02d:%02d"
16988 (nth 5 final) (nth 4 final) (nth 3 final)
16989 (nth 2 final) (nth 1 final))
16990 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16992 (defun org-read-date-display ()
16993 "Display the current date prompt interpretation in the minibuffer."
16994 (when org-read-date-display-live
16995 (when org-read-date-overlay
16996 (delete-overlay org-read-date-overlay))
16997 (when (minibufferp (current-buffer))
16998 (save-excursion
16999 (end-of-line 1)
17000 (while (not (equal (buffer-substring
17001 (max (point-min) (- (point) 4)) (point))
17002 " "))
17003 (insert " ")))
17004 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17005 " " (or org-ans1 org-ans2)))
17006 (org-end-time-was-given nil)
17007 (f (org-read-date-analyze ans org-def org-defdecode))
17008 (fmts (if org-dcst
17009 org-time-stamp-custom-formats
17010 org-time-stamp-formats))
17011 (fmt (if (or org-with-time
17012 (and (boundp 'org-time-was-given) org-time-was-given))
17013 (cdr fmts)
17014 (car fmts)))
17015 (txt (format-time-string fmt (apply 'encode-time f)))
17016 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17017 (txt (concat "=> " txt)))
17018 (when (and org-end-time-was-given
17019 (string-match org-plain-time-of-day-regexp txt))
17020 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17021 org-end-time-was-given
17022 (substring txt (match-end 0)))))
17023 (when org-read-date-analyze-futurep
17024 (setq txt (concat txt " (=>F)")))
17025 (setq org-read-date-overlay
17026 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17027 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17029 (defun org-read-date-analyze (ans org-def org-defdecode)
17030 "Analyze the combined answer of the date prompt."
17031 ;; FIXME: cleanup and comment
17032 ;; Pass `current-time' result to `decode-time' (instead of calling
17033 ;; without arguments) so that only `current-time' has to be
17034 ;; overriden in tests.
17035 (let ((nowdecode (decode-time (current-time)))
17036 delta deltan deltaw deltadef year month day
17037 hour minute second wday pm h2 m2 tl wday1
17038 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
17039 (setq org-read-date-analyze-futurep nil
17040 org-read-date-analyze-forced-year nil)
17041 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17042 (setq ans "+0"))
17044 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17045 (setq ans (replace-match "" t t ans)
17046 deltan (car delta)
17047 deltaw (nth 1 delta)
17048 deltadef (nth 2 delta)))
17050 ;; Check if there is an iso week date in there. If yes, store the
17051 ;; info and postpone interpreting it until the rest of the parsing
17052 ;; is done.
17053 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17054 (setq iso-year (if (match-end 1)
17055 (org-small-year-to-year
17056 (string-to-number (match-string 1 ans))))
17057 iso-weekday (if (match-end 3)
17058 (string-to-number (match-string 3 ans)))
17059 iso-week (string-to-number (match-string 2 ans)))
17060 (setq ans (replace-match "" t t ans)))
17062 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17063 (when (string-match
17064 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17065 (setq year (if (match-end 2)
17066 (string-to-number (match-string 2 ans))
17067 (progn (setq kill-year t)
17068 (string-to-number (format-time-string "%Y"))))
17069 month (string-to-number (match-string 3 ans))
17070 day (string-to-number (match-string 4 ans)))
17071 (if (< year 100) (setq year (+ 2000 year)))
17072 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17073 t nil ans)))
17075 ;; Help matching dotted european dates
17076 (when (string-match
17077 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17078 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17079 (setq kill-year t)
17080 (string-to-number (format-time-string "%Y")))
17081 day (string-to-number (match-string 1 ans))
17082 month (string-to-number (match-string 2 ans))
17083 ans (replace-match (format "%04d-%02d-%02d" year month day)
17084 t nil ans)))
17086 ;; Help matching american dates, like 5/30 or 5/30/7
17087 (when (string-match
17088 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17089 (setq year (if (match-end 4)
17090 (string-to-number (match-string 4 ans))
17091 (progn (setq kill-year t)
17092 (string-to-number (format-time-string "%Y"))))
17093 month (string-to-number (match-string 1 ans))
17094 day (string-to-number (match-string 2 ans)))
17095 (if (< year 100) (setq year (+ 2000 year)))
17096 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17097 t nil ans)))
17098 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17099 ;; If there is a time with am/pm, and *no* time without it, we convert
17100 ;; so that matching will be successful.
17101 (loop for i from 1 to 2 do ; twice, for end time as well
17102 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17103 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17104 (setq hour (string-to-number (match-string 1 ans))
17105 minute (if (match-end 3)
17106 (string-to-number (match-string 3 ans))
17108 pm (equal ?p
17109 (string-to-char (downcase (match-string 4 ans)))))
17110 (if (and (= hour 12) (not pm))
17111 (setq hour 0)
17112 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17113 (setq ans (replace-match (format "%02d:%02d" hour minute)
17114 t t ans))))
17116 ;; Check if a time range is given as a duration
17117 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17118 (setq hour (string-to-number (match-string 1 ans))
17119 h2 (+ hour (string-to-number (match-string 3 ans)))
17120 minute (string-to-number (match-string 2 ans))
17121 m2 (+ minute (if (match-end 5) (string-to-number
17122 (match-string 5 ans))0)))
17123 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17124 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17125 t t ans)))
17127 ;; Check if there is a time range
17128 (when (boundp 'org-end-time-was-given)
17129 (setq org-time-was-given nil)
17130 (when (and (string-match org-plain-time-of-day-regexp ans)
17131 (match-end 8))
17132 (setq org-end-time-was-given (match-string 8 ans))
17133 (setq ans (concat (substring ans 0 (match-beginning 7))
17134 (substring ans (match-end 7))))))
17136 (setq tl (parse-time-string ans)
17137 day (or (nth 3 tl) (nth 3 org-defdecode))
17138 month
17139 (cond ((nth 4 tl))
17140 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17141 ;; Day was specified. Make sure DAY+MONTH
17142 ;; combination happens in the future.
17143 ((nth 3 tl)
17144 (setq futurep t)
17145 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17146 (nth 4 nowdecode)))
17147 (t (nth 4 org-defdecode)))
17148 year
17149 (cond ((and (not kill-year) (nth 5 tl)))
17150 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17151 ;; Month was guessed in the future and is at least
17152 ;; equal to NOWDECODE's. Fix year accordingly.
17153 (futurep
17154 (if (or (> month (nth 4 nowdecode))
17155 (>= day (nth 3 nowdecode)))
17156 (nth 5 nowdecode)
17157 (1+ (nth 5 nowdecode))))
17158 ;; Month was specified. Make sure MONTH+YEAR
17159 ;; combination happens in the future.
17160 ((nth 4 tl)
17161 (setq futurep t)
17162 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17163 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17164 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17165 (t (nth 5 nowdecode))))
17166 (t (nth 5 org-defdecode)))
17167 hour (or (nth 2 tl) (nth 2 org-defdecode))
17168 minute (or (nth 1 tl) (nth 1 org-defdecode))
17169 second (or (nth 0 tl) 0)
17170 wday (nth 6 tl))
17172 (when (and (eq org-read-date-prefer-future 'time)
17173 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17174 (equal day (nth 3 nowdecode))
17175 (equal month (nth 4 nowdecode))
17176 (equal year (nth 5 nowdecode))
17177 (nth 2 tl)
17178 (or (< (nth 2 tl) (nth 2 nowdecode))
17179 (and (= (nth 2 tl) (nth 2 nowdecode))
17180 (nth 1 tl)
17181 (< (nth 1 tl) (nth 1 nowdecode)))))
17182 (setq day (1+ day)
17183 futurep t))
17185 ;; Special date definitions below
17186 (cond
17187 (iso-week
17188 ;; There was an iso week
17189 (require 'cal-iso)
17190 (setq futurep nil)
17191 (setq year (or iso-year year)
17192 day (or iso-weekday wday 1)
17193 wday nil ; to make sure that the trigger below does not match
17194 iso-date (calendar-gregorian-from-absolute
17195 (calendar-iso-to-absolute
17196 (list iso-week day year))))
17197 ; FIXME: Should we also push ISO weeks into the future?
17198 ; (when (and org-read-date-prefer-future
17199 ; (not iso-year)
17200 ; (< (calendar-absolute-from-gregorian iso-date)
17201 ; (time-to-days (current-time))))
17202 ; (setq year (1+ year)
17203 ; iso-date (calendar-gregorian-from-absolute
17204 ; (calendar-iso-to-absolute
17205 ; (list iso-week day year)))))
17206 (setq month (car iso-date)
17207 year (nth 2 iso-date)
17208 day (nth 1 iso-date)))
17209 (deltan
17210 (setq futurep nil)
17211 (unless deltadef
17212 ;; Pass `current-time' result to `decode-time' (instead of
17213 ;; calling without arguments) so that only `current-time' has
17214 ;; to be overriden in tests.
17215 (let ((now (decode-time (current-time))))
17216 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17217 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17218 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17219 ((equal deltaw "m") (setq month (+ month deltan)))
17220 ((equal deltaw "y") (setq year (+ year deltan)))))
17221 ((and wday (not (nth 3 tl)))
17222 ;; Weekday was given, but no day, so pick that day in the week
17223 ;; on or after the derived date.
17224 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17225 (unless (equal wday wday1)
17226 (setq day (+ day (% (- wday wday1 -7) 7))))))
17227 (if (and (boundp 'org-time-was-given)
17228 (nth 2 tl))
17229 (setq org-time-was-given t))
17230 (if (< year 100) (setq year (+ 2000 year)))
17231 ;; Check of the date is representable
17232 (if org-read-date-force-compatible-dates
17233 (progn
17234 (if (< year 1970)
17235 (setq year 1970 org-read-date-analyze-forced-year t))
17236 (if (> year 2037)
17237 (setq year 2037 org-read-date-analyze-forced-year t)))
17238 (condition-case nil
17239 (ignore (encode-time second minute hour day month year))
17240 (error
17241 (setq year (nth 5 org-defdecode))
17242 (setq org-read-date-analyze-forced-year t))))
17243 (setq org-read-date-analyze-futurep futurep)
17244 (list second minute hour day month year)))
17246 (defvar parse-time-weekdays)
17247 (defun org-read-date-get-relative (s today default)
17248 "Check string S for special relative date string.
17249 TODAY and DEFAULT are internal times, for today and for a default.
17250 Return shift list (N what def-flag)
17251 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17252 N is the number of WHATs to shift.
17253 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17254 the DEFAULT date rather than TODAY."
17255 (require 'parse-time)
17256 (when (and
17257 (string-match
17258 (concat
17259 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17260 "\\([0-9]+\\)?"
17261 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17262 "\\([ \t]\\|$\\)") s)
17263 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17264 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17265 (string-to-char (substring (match-string 1 s) -1))
17266 ?+))
17267 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17268 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17269 (what (if (match-end 3) (match-string 3 s) "d"))
17270 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17271 (date (if rel default today))
17272 (wday (nth 6 (decode-time date)))
17273 delta)
17274 (if wday1
17275 (progn
17276 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17277 (if (= delta 0) (setq delta 7))
17278 (if (= dir ?-)
17279 (progn
17280 (setq delta (- delta 7))
17281 (if (= delta 0) (setq delta -7))))
17282 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17283 (list delta "d" rel))
17284 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17286 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17287 "Turn a user-specified date into the internal representation.
17288 The internal representation needed by the calendar is (month day year).
17289 This is a wrapper to handle the brain-dead convention in calendar that
17290 user function argument order change dependent on argument order."
17291 (if (boundp 'calendar-date-style)
17292 (cond
17293 ((eq calendar-date-style 'american)
17294 (list arg1 arg2 arg3))
17295 ((eq calendar-date-style 'european)
17296 (list arg2 arg1 arg3))
17297 ((eq calendar-date-style 'iso)
17298 (list arg2 arg3 arg1)))
17299 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
17300 (if (org-bound-and-true-p european-calendar-style)
17301 (list arg2 arg1 arg3)
17302 (list arg1 arg2 arg3)))))
17304 (defun org-eval-in-calendar (form &optional keepdate)
17305 "Eval FORM in the calendar window and return to current window.
17306 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
17307 otherwise stick to the current value of `org-ans2'."
17308 (let ((sf (selected-frame))
17309 (sw (selected-window)))
17310 (select-window (get-buffer-window "*Calendar*" t))
17311 (eval form)
17312 (when (and (not keepdate) (calendar-cursor-to-date))
17313 (let* ((date (calendar-cursor-to-date))
17314 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17315 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17316 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17317 (select-window sw)
17318 (org-select-frame-set-input-focus sf)))
17320 (defun org-calendar-select ()
17321 "Return to `org-read-date' with the date currently selected.
17322 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17323 (interactive)
17324 (when (calendar-cursor-to-date)
17325 (let* ((date (calendar-cursor-to-date))
17326 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17327 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17328 (if (active-minibuffer-window) (exit-minibuffer))))
17330 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17331 "Insert a date stamp for the date given by the internal TIME.
17332 See `format-time-string' for the format of TIME.
17333 WITH-HM means use the stamp format that includes the time of the day.
17334 INACTIVE means use square brackets instead of angular ones, so that the
17335 stamp will not contribute to the agenda.
17336 PRE and POST are optional strings to be inserted before and after the
17337 stamp.
17338 The command returns the inserted time stamp."
17339 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17340 stamp)
17341 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17342 (insert-before-markers (or pre ""))
17343 (when (listp extra)
17344 (setq extra (car extra))
17345 (if (and (stringp extra)
17346 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17347 (setq extra (format "-%02d:%02d"
17348 (string-to-number (match-string 1 extra))
17349 (string-to-number (match-string 2 extra))))
17350 (setq extra nil)))
17351 (when extra
17352 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17353 (insert-before-markers (setq stamp (format-time-string fmt time)))
17354 (insert-before-markers (or post ""))
17355 (setq org-last-inserted-timestamp stamp)))
17357 (defun org-toggle-time-stamp-overlays ()
17358 "Toggle the use of custom time stamp formats."
17359 (interactive)
17360 (setq org-display-custom-times (not org-display-custom-times))
17361 (unless org-display-custom-times
17362 (let ((p (point-min)) (bmp (buffer-modified-p)))
17363 (while (setq p (next-single-property-change p 'display))
17364 (if (and (get-text-property p 'display)
17365 (eq (get-text-property p 'face) 'org-date))
17366 (remove-text-properties
17367 p (setq p (next-single-property-change p 'display))
17368 '(display t))))
17369 (set-buffer-modified-p bmp)))
17370 (if (featurep 'xemacs)
17371 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17372 (org-restart-font-lock)
17373 (setq org-table-may-need-update t)
17374 (if org-display-custom-times
17375 (message "Time stamps are overlaid with custom format")
17376 (message "Time stamp overlays removed")))
17378 (defun org-display-custom-time (beg end)
17379 "Overlay modified time stamp format over timestamp between BEG and END."
17380 (let* ((ts (buffer-substring beg end))
17381 t1 w1 with-hm tf time str w2 (off 0))
17382 (save-match-data
17383 (setq t1 (org-parse-time-string ts t))
17384 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17385 (setq off (- (match-end 0) (match-beginning 0)))))
17386 (setq end (- end off))
17387 (setq w1 (- end beg)
17388 with-hm (and (nth 1 t1) (nth 2 t1))
17389 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17390 time (org-fix-decoded-time t1)
17391 str (org-add-props
17392 (format-time-string
17393 (substring tf 1 -1) (apply 'encode-time time))
17394 nil 'mouse-face 'highlight)
17395 w2 (length str))
17396 (if (not (= w2 w1))
17397 (add-text-properties (1+ beg) (+ 2 beg)
17398 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17399 (if (featurep 'xemacs)
17400 (progn
17401 (put-text-property beg end 'invisible t)
17402 (put-text-property beg end 'end-glyph (make-glyph str)))
17403 (put-text-property beg end 'display str))))
17405 (defun org-fix-decoded-time (time)
17406 "Set 0 instead of nil for the first 6 elements of time.
17407 Don't touch the rest."
17408 (let ((n 0))
17409 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17411 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17413 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17414 "Difference between TIMESTAMP-STRING and now in days.
17415 If SECONDS is non-nil, return the difference in seconds."
17416 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17417 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17418 (funcall fdiff (current-time)))))
17420 (defun org-deadline-close (timestamp-string &optional ndays)
17421 "Is the time in TIMESTAMP-STRING close to the current date?"
17422 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17423 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17424 (not (org-entry-is-done-p))))
17426 (defun org-get-wdays (ts &optional delay zero-delay)
17427 "Get the deadline lead time appropriate for timestring TS.
17428 When DELAY is non-nil, get the delay time for scheduled items
17429 instead of the deadline lead time. When ZERO-DELAY is non-nil
17430 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17431 don't try to find the delay cookie in the scheduled timestamp."
17432 (let ((tv (if delay org-scheduled-delay-days
17433 org-deadline-warning-days)))
17434 (cond
17435 ((or (and delay (< tv 0))
17436 (and delay zero-delay (<= tv 0))
17437 (and (not delay) (<= tv 0)))
17438 ;; Enforce this value no matter what
17439 (- tv))
17440 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17441 ;; lead time is specified.
17442 (floor (* (string-to-number (match-string 1 ts))
17443 (cdr (assoc (match-string 2 ts)
17444 '(("d" . 1) ("w" . 7)
17445 ("m" . 30.4) ("y" . 365.25)
17446 ("h" . 0.041667)))))))
17447 ;; go for the default.
17448 (t tv))))
17450 (defun org-calendar-select-mouse (ev)
17451 "Return to `org-read-date' with the date currently selected.
17452 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17453 (interactive "e")
17454 (mouse-set-point ev)
17455 (when (calendar-cursor-to-date)
17456 (let* ((date (calendar-cursor-to-date))
17457 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17458 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17459 (if (active-minibuffer-window) (exit-minibuffer))))
17461 (defun org-check-deadlines (ndays)
17462 "Check if there are any deadlines due or past due.
17463 A deadline is considered due if it happens within `org-deadline-warning-days'
17464 days from today's date. If the deadline appears in an entry marked DONE,
17465 it is not shown. The prefix arg NDAYS can be used to test that many
17466 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17467 (interactive "P")
17468 (let* ((org-warn-days
17469 (cond
17470 ((equal ndays '(4)) 100000)
17471 (ndays (prefix-numeric-value ndays))
17472 (t (abs org-deadline-warning-days))))
17473 (case-fold-search nil)
17474 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17475 (callback
17476 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17477 (message "%d deadlines past-due or due within %d days"
17478 (org-occur regexp nil callback)
17479 org-warn-days)))
17481 (defsubst org-re-timestamp (type)
17482 "Return a regexp for timestamp TYPE.
17483 Allowed values for TYPE are:
17485 all: all timestamps
17486 active: only active timestamps (<...>)
17487 inactive: only inactive timestamps ([...])
17488 scheduled: only scheduled timestamps
17489 deadline: only deadline timestamps
17490 closed: only closed time-stamps
17492 When TYPE is nil, fall back on returning a regexp that matches
17493 both scheduled and deadline timestamps."
17494 (case type
17495 (all org-ts-regexp-both)
17496 (active org-ts-regexp)
17497 (inactive org-ts-regexp-inactive)
17498 (scheduled org-scheduled-time-regexp)
17499 (deadline org-deadline-time-regexp)
17500 (closed org-closed-time-regexp)
17501 (otherwise
17502 (concat "\\<"
17503 (regexp-opt (list org-deadline-string org-scheduled-string))
17504 " *<\\([^>]+\\)>"))))
17506 (defun org-check-before-date (date)
17507 "Check if there are deadlines or scheduled entries before DATE."
17508 (interactive (list (org-read-date)))
17509 (let ((case-fold-search nil)
17510 (regexp (org-re-timestamp org-ts-type))
17511 (callback
17512 `(lambda ()
17513 (let ((match (match-string 1)))
17514 (and ,(if (memq org-ts-type '(active inactive all))
17515 '(eq (org-element-type (org-element-context)) 'timestamp)
17516 '(org-at-planning-p))
17517 (time-less-p
17518 (org-time-string-to-time match)
17519 (org-time-string-to-time date)))))))
17520 (message "%d entries before %s"
17521 (org-occur regexp nil callback) date)))
17523 (defun org-check-after-date (date)
17524 "Check if there are deadlines or scheduled entries after DATE."
17525 (interactive (list (org-read-date)))
17526 (let ((case-fold-search nil)
17527 (regexp (org-re-timestamp org-ts-type))
17528 (callback
17529 `(lambda ()
17530 (let ((match (match-string 1)))
17531 (and ,(if (memq org-ts-type '(active inactive all))
17532 '(eq (org-element-type (org-element-context)) 'timestamp)
17533 '(org-at-planning-p))
17534 (not (time-less-p
17535 (org-time-string-to-time match)
17536 (org-time-string-to-time date))))))))
17537 (message "%d entries after %s"
17538 (org-occur regexp nil callback) date)))
17540 (defun org-check-dates-range (start-date end-date)
17541 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17542 (interactive (list (org-read-date nil nil nil "Range starts")
17543 (org-read-date nil nil nil "Range end")))
17544 (let ((case-fold-search nil)
17545 (regexp (org-re-timestamp org-ts-type))
17546 (callback
17547 `(lambda ()
17548 (let ((match (match-string 1)))
17549 (and
17550 ,(if (memq org-ts-type '(active inactive all))
17551 '(eq (org-element-type (org-element-context)) 'timestamp)
17552 '(org-at-planning-p))
17553 (not (time-less-p
17554 (org-time-string-to-time match)
17555 (org-time-string-to-time start-date)))
17556 (time-less-p
17557 (org-time-string-to-time match)
17558 (org-time-string-to-time end-date)))))))
17559 (message "%d entries between %s and %s"
17560 (org-occur regexp nil callback) start-date end-date)))
17562 (defun org-evaluate-time-range (&optional to-buffer)
17563 "Evaluate a time range by computing the difference between start and end.
17564 Normally the result is just printed in the echo area, but with prefix arg
17565 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17566 If the time range is actually in a table, the result is inserted into the
17567 next column.
17568 For time difference computation, a year is assumed to be exactly 365
17569 days in order to avoid rounding problems."
17570 (interactive "P")
17572 (org-clock-update-time-maybe)
17573 (save-excursion
17574 (unless (org-at-date-range-p t)
17575 (goto-char (point-at-bol))
17576 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17577 (if (not (org-at-date-range-p t))
17578 (user-error "Not at a time-stamp range, and none found in current line")))
17579 (let* ((ts1 (match-string 1))
17580 (ts2 (match-string 2))
17581 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17582 (match-end (match-end 0))
17583 (time1 (org-time-string-to-time ts1))
17584 (time2 (org-time-string-to-time ts2))
17585 (t1 (org-float-time time1))
17586 (t2 (org-float-time time2))
17587 (diff (abs (- t2 t1)))
17588 (negative (< (- t2 t1) 0))
17589 ;; (ys (floor (* 365 24 60 60)))
17590 (ds (* 24 60 60))
17591 (hs (* 60 60))
17592 (fy "%dy %dd %02d:%02d")
17593 (fy1 "%dy %dd")
17594 (fd "%dd %02d:%02d")
17595 (fd1 "%dd")
17596 (fh "%02d:%02d")
17597 y d h m align)
17598 (if havetime
17599 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17601 d (floor (/ diff ds)) diff (mod diff ds)
17602 h (floor (/ diff hs)) diff (mod diff hs)
17603 m (floor (/ diff 60)))
17604 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17606 d (floor (+ (/ diff ds) 0.5))
17607 h 0 m 0))
17608 (if (not to-buffer)
17609 (message "%s" (org-make-tdiff-string y d h m))
17610 (if (org-at-table-p)
17611 (progn
17612 (goto-char match-end)
17613 (setq align t)
17614 (and (looking-at " *|") (goto-char (match-end 0))))
17615 (goto-char match-end))
17616 (if (looking-at
17617 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17618 (replace-match ""))
17619 (if negative (insert " -"))
17620 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17621 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17622 (insert " " (format fh h m))))
17623 (if align (org-table-align))
17624 (message "Time difference inserted")))))
17626 (defun org-make-tdiff-string (y d h m)
17627 (let ((fmt "")
17628 (l nil))
17629 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17630 l (push y l)))
17631 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17632 l (push d l)))
17633 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17634 l (push h l)))
17635 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17636 l (push m l)))
17637 (apply 'format fmt (nreverse l))))
17639 (defun org-time-string-to-time (s &optional buffer pos)
17640 "Convert a timestamp string into internal time."
17641 (condition-case errdata
17642 (apply 'encode-time (org-parse-time-string s))
17643 (error (error "Bad timestamp `%s'%s\nError was: %s"
17644 s (if (not (and buffer pos))
17646 (format-message " at %d in buffer `%s'" pos buffer))
17647 (cdr errdata)))))
17649 (defun org-time-string-to-seconds (s)
17650 "Convert a timestamp string to a number of seconds."
17651 (org-float-time (org-time-string-to-time s)))
17653 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17654 "Convert a time stamp to an absolute day number.
17655 If there is a specifier for a cyclic time stamp, get the closest
17656 date to DAYNR.
17657 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17658 The variable `date' is bound by the calendar when this is called."
17659 (cond
17660 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17661 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17662 daynr
17663 (+ daynr 1000)))
17664 ((and daynr (string-match "\\+\\([0-9]+\\)[hdwmy]" s)
17665 (> (string-to-number (match-string 1 s)) 0))
17666 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17667 (time-to-days (current-time))) (match-string 0 s)
17668 prefer show-all))
17669 (t (time-to-days
17670 (condition-case errdata
17671 (apply 'encode-time (org-parse-time-string s))
17672 (error (error "Bad timestamp `%s'%s\nError was: %s"
17673 s (if (not (and buffer pos))
17675 (format-message " at %d in buffer `%s'" pos buffer))
17676 (cdr errdata))))))))
17678 (defun org-days-to-iso-week (days)
17679 "Return the iso week number."
17680 (require 'cal-iso)
17681 (car (calendar-iso-from-absolute days)))
17683 (defun org-small-year-to-year (year)
17684 "Convert 2-digit years into 4-digit years.
17685 YEAR is expanded into one of the 30 next years, if possible, or
17686 into a past one. Any year larger than 99 is returned unchanged."
17687 (if (>= year 100) year
17688 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17689 (century (/ current 100))
17690 (offset (- year (% current 100))))
17691 (cond ((> offset 30) (+ (* (1- century) 100) year))
17692 ((> offset -70) (+ (* century 100) year))
17693 (t (+ (* (1+ century) 100) year))))))
17695 (defun org-time-from-absolute (d)
17696 "Return the time corresponding to date D.
17697 D may be an absolute day number, or a calendar-type list (month day year)."
17698 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17699 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17701 (defun org-calendar-holiday ()
17702 "List of holidays, for Diary display in Org-mode."
17703 (require 'holidays)
17704 (let ((hl (funcall
17705 (if (fboundp 'calendar-check-holidays)
17706 'calendar-check-holidays 'check-calendar-holidays) date)))
17707 (if hl (mapconcat 'identity hl "; "))))
17709 (defun org-diary-sexp-entry (sexp entry date)
17710 "Process a SEXP diary ENTRY for DATE."
17711 (require 'diary-lib)
17712 (let ((result (if calendar-debug-sexp
17713 (let ((stack-trace-on-error t))
17714 (eval (car (read-from-string sexp))))
17715 (condition-case nil
17716 (eval (car (read-from-string sexp)))
17717 (error
17718 (beep)
17719 (message "Bad sexp at line %d in %s: %s"
17720 (org-current-line)
17721 (buffer-file-name) sexp)
17722 (sleep-for 2))))))
17723 (cond ((stringp result) (split-string result "; "))
17724 ((and (consp result)
17725 (not (consp (cdr result)))
17726 (stringp (cdr result))) (cdr result))
17727 ((and (consp result)
17728 (stringp (car result))) result)
17729 (result entry))))
17731 (defun org-diary-to-ical-string (frombuf)
17732 "Get iCalendar entries from diary entries in buffer FROMBUF.
17733 This uses the icalendar.el library."
17734 (let* ((tmpdir (if (featurep 'xemacs)
17735 (temp-directory)
17736 temporary-file-directory))
17737 (tmpfile (make-temp-name
17738 (expand-file-name "orgics" tmpdir)))
17739 buf rtn b e)
17740 (with-current-buffer frombuf
17741 (icalendar-export-region (point-min) (point-max) tmpfile)
17742 (setq buf (find-buffer-visiting tmpfile))
17743 (set-buffer buf)
17744 (goto-char (point-min))
17745 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17746 (setq b (match-beginning 0)))
17747 (goto-char (point-max))
17748 (if (re-search-backward "^END:VEVENT" nil t)
17749 (setq e (match-end 0)))
17750 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17751 (kill-buffer buf)
17752 (delete-file tmpfile)
17753 rtn))
17755 (defun org-closest-date (start current change prefer show-all)
17756 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17757 When PREFER is `past', return a date that is either CURRENT or past.
17758 When PREFER is `future', return a date that is either CURRENT or future.
17759 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17760 ;; Make the proper lists from the dates
17761 (catch 'exit
17762 (let ((a1 '(("h" . hour)
17763 ("d" . day)
17764 ("w" . week)
17765 ("m" . month)
17766 ("y" . year)))
17767 (shour (nth 2 (org-parse-time-string start)))
17768 dn dw sday cday n1 n2 n0
17769 d m y y1 y2 date1 date2 nmonths nm ny m2)
17771 (setq start (org-date-to-gregorian start)
17772 current (org-date-to-gregorian
17773 (if show-all
17774 current
17775 (time-to-days (current-time))))
17776 sday (calendar-absolute-from-gregorian start)
17777 cday (calendar-absolute-from-gregorian current))
17779 (if (<= cday sday) (throw 'exit sday))
17781 (when (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17782 (setq dn (string-to-number (match-string 1 change))
17783 dw (cdr (assoc (match-string 2 change) a1))))
17784 (unless (and dn (> dn 0))
17785 (user-error "Invalid change specifier: %s" change))
17786 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17787 (cond
17788 ((eq dw 'hour)
17789 (let ((missing-hours
17790 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17791 dn)))
17792 (setq n1 (if (zerop missing-hours) cday
17793 (- cday (1+ (floor (/ missing-hours 24)))))
17794 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17795 ((eq dw 'day)
17796 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17797 n2 (+ n1 dn)))
17798 ((eq dw 'year)
17799 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17800 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17801 (setq date1 (list m d y1)
17802 n1 (calendar-absolute-from-gregorian date1)
17803 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17804 n2 (calendar-absolute-from-gregorian date2)))
17805 ((eq dw 'month)
17806 ;; approx number of month between the two dates
17807 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17808 ;; How often does dn fit in there?
17809 (setq d (nth 1 start) m (car start) y (nth 2 start)
17810 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17811 m (+ m nm)
17812 ny (floor (/ m 12))
17813 y (+ y ny)
17814 m (- m (* ny 12)))
17815 (while (> m 12) (setq m (- m 12) y (1+ y)))
17816 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17817 (setq m2 (+ m dn) y2 y)
17818 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17819 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17820 (while (<= n2 cday)
17821 (setq n1 n2 m m2 y y2)
17822 (setq m2 (+ m dn) y2 y)
17823 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17824 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17825 ;; Make sure n1 is the earlier date
17826 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17827 (if show-all
17828 (cond
17829 ((eq prefer 'past) (if (= cday n2) n2 n1))
17830 ((eq prefer 'future) (if (= cday n1) n1 n2))
17831 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17832 (cond
17833 ((eq prefer 'past) (if (= cday n2) n2 n1))
17834 ((eq prefer 'future) (if (= cday n1) n1 n2))
17835 (t (if (= cday n1) n1 n2)))))))
17837 (defun org-date-to-gregorian (date)
17838 "Turn any specification of DATE into a Gregorian date for the calendar."
17839 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17840 ((and (listp date) (= (length date) 3)) date)
17841 ((stringp date)
17842 (setq date (org-parse-time-string date))
17843 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17844 ((listp date)
17845 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17847 (defun org-parse-time-string (s &optional nodefault)
17848 "Parse the standard Org-mode time string.
17849 This should be a lot faster than the normal `parse-time-string'.
17850 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17851 hour and minute fields will be nil if not given."
17852 (cond ((string-match org-ts-regexp0 s)
17853 (list 0
17854 (if (or (match-beginning 8) (not nodefault))
17855 (string-to-number (or (match-string 8 s) "0")))
17856 (if (or (match-beginning 7) (not nodefault))
17857 (string-to-number (or (match-string 7 s) "0")))
17858 (string-to-number (match-string 4 s))
17859 (string-to-number (match-string 3 s))
17860 (string-to-number (match-string 2 s))
17861 nil nil nil))
17862 ((string-match "^<[^>]+>$" s)
17863 (decode-time (seconds-to-time (org-matcher-time s))))
17864 (t (error "Not a standard Org-mode time string: %s" s))))
17866 (defun org-timestamp-up (&optional arg)
17867 "Increase the date item at the cursor by one.
17868 If the cursor is on the year, change the year. If it is on the month,
17869 the day or the time, change that.
17870 With prefix ARG, change by that many units."
17871 (interactive "p")
17872 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17874 (defun org-timestamp-down (&optional arg)
17875 "Decrease the date item at the cursor by one.
17876 If the cursor is on the year, change the year. If it is on the month,
17877 the day or the time, change that.
17878 With prefix ARG, change by that many units."
17879 (interactive "p")
17880 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17882 (defun org-timestamp-up-day (&optional arg)
17883 "Increase the date in the time stamp by one day.
17884 With prefix ARG, change that many days."
17885 (interactive "p")
17886 (if (and (not (org-at-timestamp-p t))
17887 (org-at-heading-p))
17888 (org-todo 'up)
17889 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17891 (defun org-timestamp-down-day (&optional arg)
17892 "Decrease the date in the time stamp by one day.
17893 With prefix ARG, change that many days."
17894 (interactive "p")
17895 (if (and (not (org-at-timestamp-p t))
17896 (org-at-heading-p))
17897 (org-todo 'down)
17898 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17900 (defun org-at-timestamp-p (&optional inactive-ok)
17901 "Non-nil if point is inside a timestamp.
17903 When optional argument INACTIVE-OK is non-nil, also consider
17904 inactive timestamps.
17906 When this function returns a non-nil value, match data is set
17907 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
17908 INACTIVE-OK."
17909 (interactive)
17910 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17911 (pos (point))
17912 (ans (or (looking-at tsr)
17913 (save-excursion
17914 (skip-chars-backward "^[<\n\r\t")
17915 (if (> (point) (point-min)) (backward-char 1))
17916 (and (looking-at tsr)
17917 (> (- (match-end 0) pos) -1))))))
17918 (and ans
17919 (boundp 'org-ts-what)
17920 (setq org-ts-what
17921 (cond
17922 ((= pos (match-beginning 0)) 'bracket)
17923 ;; Point is considered to be "on the bracket" whether
17924 ;; it's really on it or right after it.
17925 ((= pos (1- (match-end 0))) 'bracket)
17926 ((= pos (match-end 0)) 'after)
17927 ((org-pos-in-match-range pos 2) 'year)
17928 ((org-pos-in-match-range pos 3) 'month)
17929 ((org-pos-in-match-range pos 7) 'hour)
17930 ((org-pos-in-match-range pos 8) 'minute)
17931 ((or (org-pos-in-match-range pos 4)
17932 (org-pos-in-match-range pos 5)) 'day)
17933 ((and (> pos (or (match-end 8) (match-end 5)))
17934 (< pos (match-end 0)))
17935 (- pos (or (match-end 8) (match-end 5))))
17936 (t 'day))))
17937 ans))
17939 (defun org-toggle-timestamp-type ()
17940 "Toggle the type (<active> or [inactive]) of a time stamp."
17941 (interactive)
17942 (when (org-at-timestamp-p t)
17943 (let ((beg (match-beginning 0)) (end (match-end 0))
17944 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17945 (save-excursion
17946 (goto-char beg)
17947 (while (re-search-forward "[][<>]" end t)
17948 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17949 t t)))
17950 (message "Timestamp is now %sactive"
17951 (if (equal (char-after beg) ?<) "" "in")))))
17953 (defun org-at-clock-log-p nil
17954 "Is the cursor on the clock log line?"
17955 (save-excursion
17956 (move-beginning-of-line 1)
17957 (looking-at org-clock-line-re)))
17959 (defvar org-clock-history) ; defined in org-clock.el
17960 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17961 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17962 "Change the date in the time stamp at point.
17963 The date will be changed by N times WHAT. WHAT can be `day', `month',
17964 `year', `minute', `second'. If WHAT is not given, the cursor position
17965 in the timestamp determines what will be changed.
17966 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17967 (let ((origin (point)) origin-cat
17968 with-hm inactive
17969 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17970 org-ts-what
17971 extra rem
17972 ts time time0 fixnext clrgx)
17973 (if (not (org-at-timestamp-p t))
17974 (user-error "Not at a timestamp"))
17975 (if (and (not what) (eq org-ts-what 'bracket))
17976 (org-toggle-timestamp-type)
17977 ;; Point isn't on brackets. Remember the part of the time-stamp
17978 ;; the point was in. Indeed, size of time-stamps may change,
17979 ;; but point must be kept in the same category nonetheless.
17980 (setq origin-cat org-ts-what)
17981 (if (and (not what) (not (eq org-ts-what 'day))
17982 org-display-custom-times
17983 (get-text-property (point) 'display)
17984 (not (get-text-property (1- (point)) 'display)))
17985 (setq org-ts-what 'day))
17986 (setq org-ts-what (or what org-ts-what)
17987 inactive (= (char-after (match-beginning 0)) ?\[)
17988 ts (match-string 0))
17989 (replace-match "")
17990 (when (string-match
17991 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17993 (setq extra (match-string 1 ts))
17994 (if suppress-tmp-delay
17995 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17996 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17997 (setq with-hm t))
17998 (setq time0 (org-parse-time-string ts))
17999 (when (and updown
18000 (eq org-ts-what 'minute)
18001 (not current-prefix-arg))
18002 ;; This looks like s-up and s-down. Change by one rounding step.
18003 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18004 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
18005 (setcar (cdr time0) (+ (nth 1 time0)
18006 (if (> n 0) (- rem) (- dm rem))))))
18007 (setq time
18008 (encode-time (or (car time0) 0)
18009 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18010 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18011 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18012 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18013 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18014 (nthcdr 6 time0)))
18015 (when (and (member org-ts-what '(hour minute))
18016 extra
18017 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18018 (setq extra (org-modify-ts-extra
18019 extra
18020 (if (eq org-ts-what 'hour) 2 5)
18021 n dm)))
18022 (when (integerp org-ts-what)
18023 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18024 (if (eq what 'calendar)
18025 (let ((cal-date (org-get-date-from-calendar)))
18026 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18027 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18028 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18029 (setcar time0 (or (car time0) 0))
18030 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18031 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18032 (setq time (apply 'encode-time time0))))
18033 ;; Insert the new time-stamp, and ensure point stays in the same
18034 ;; category as before (i.e. not after the last position in that
18035 ;; category).
18036 (let ((pos (point)))
18037 ;; Stay before inserted string. `save-excursion' is of no use.
18038 (setq org-last-changed-timestamp
18039 (org-insert-time-stamp time with-hm inactive nil nil extra))
18040 (goto-char pos))
18041 (save-match-data
18042 (looking-at org-ts-regexp3)
18043 (goto-char (cond
18044 ;; `day' category ends before `hour' if any, or at
18045 ;; the end of the day name.
18046 ((eq origin-cat 'day)
18047 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18048 ((eq origin-cat 'hour) (min (match-end 7) origin))
18049 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18050 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18051 ;; `year' and `month' have both fixed size: point
18052 ;; couldn't have moved into another part.
18053 (t origin))))
18054 ;; Update clock if on a CLOCK line.
18055 (org-clock-update-time-maybe)
18056 ;; Maybe adjust the closest clock in `org-clock-history'
18057 (when org-clock-adjust-closest
18058 (if (not (and (org-at-clock-log-p)
18059 (< 1 (length (delq nil (mapcar 'marker-position
18060 org-clock-history))))))
18061 (message "No clock to adjust")
18062 (cond ((save-excursion ; fix previous clock?
18063 (re-search-backward org-ts-regexp0 nil t)
18064 (org-looking-back (concat org-clock-string " \\[")
18065 (line-beginning-position)))
18066 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18067 ((save-excursion ; fix next clock?
18068 (re-search-backward org-ts-regexp0 nil t)
18069 (looking-at (concat org-ts-regexp0 "\\] =>")))
18070 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18071 (save-window-excursion
18072 ;; Find closest clock to point, adjust the previous/next one in history
18073 (let* ((p (save-excursion (org-back-to-heading t)))
18074 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18075 (clfixnth
18076 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18077 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
18078 (if (not clfixpos)
18079 (message "No clock to adjust")
18080 (save-excursion
18081 (org-goto-marker-or-bmk clfixpos)
18082 (org-show-subtree)
18083 (when (re-search-forward clrgx nil t)
18084 (goto-char (match-beginning 1))
18085 (let (org-clock-adjust-closest)
18086 (org-timestamp-change n org-ts-what updown))
18087 (message "Clock adjusted in %s for heading: %s"
18088 (file-name-nondirectory (buffer-file-name))
18089 (org-get-heading t t)))))))))
18090 ;; Try to recenter the calendar window, if any.
18091 (if (and org-calendar-follow-timestamp-change
18092 (get-buffer-window "*Calendar*" t)
18093 (memq org-ts-what '(day month year)))
18094 (org-recenter-calendar (time-to-days time))))))
18096 (defun org-modify-ts-extra (s pos n dm)
18097 "Change the different parts of the lead-time and repeat fields in timestamp."
18098 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18099 ng h m new rem)
18100 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18101 (cond
18102 ((or (org-pos-in-match-range pos 2)
18103 (org-pos-in-match-range pos 3))
18104 (setq m (string-to-number (match-string 3 s))
18105 h (string-to-number (match-string 2 s)))
18106 (if (org-pos-in-match-range pos 2)
18107 (setq h (+ h n))
18108 (setq n (* dm (org-no-warnings (signum n))))
18109 (when (not (= 0 (setq rem (% m dm))))
18110 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18111 (setq m (+ m n)))
18112 (if (< m 0) (setq m (+ m 60) h (1- h)))
18113 (if (> m 59) (setq m (- m 60) h (1+ h)))
18114 (setq h (mod h 24))
18115 (setq ng 1 new (format "-%02d:%02d" h m)))
18116 ((org-pos-in-match-range pos 6)
18117 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18118 ((org-pos-in-match-range pos 5)
18119 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18121 ((org-pos-in-match-range pos 9)
18122 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18123 ((org-pos-in-match-range pos 8)
18124 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18126 (when ng
18127 (setq s (concat
18128 (substring s 0 (match-beginning ng))
18130 (substring s (match-end ng))))))
18133 (defun org-recenter-calendar (date)
18134 "If the calendar is visible, recenter it to DATE."
18135 (let ((cwin (get-buffer-window "*Calendar*" t)))
18136 (when cwin
18137 (let ((calendar-move-hook nil))
18138 (with-selected-window cwin
18139 (calendar-goto-date (if (listp date) date
18140 (calendar-gregorian-from-absolute date))))))))
18142 (defun org-goto-calendar (&optional arg)
18143 "Go to the Emacs calendar at the current date.
18144 If there is a time stamp in the current line, go to that date.
18145 A prefix ARG can be used to force the current date."
18146 (interactive "P")
18147 (let ((tsr org-ts-regexp) diff
18148 (calendar-move-hook nil)
18149 (calendar-view-holidays-initially-flag nil)
18150 (calendar-view-diary-initially-flag nil))
18151 (if (or (org-at-timestamp-p)
18152 (save-excursion
18153 (beginning-of-line 1)
18154 (looking-at (concat ".*" tsr))))
18155 (let ((d1 (time-to-days (current-time)))
18156 (d2 (time-to-days
18157 (org-time-string-to-time (match-string 1)))))
18158 (setq diff (- d2 d1))))
18159 (calendar)
18160 (calendar-goto-today)
18161 (if (and diff (not arg)) (calendar-forward-day diff))))
18163 (defun org-get-date-from-calendar ()
18164 "Return a list (month day year) of date at point in calendar."
18165 (with-current-buffer "*Calendar*"
18166 (save-match-data
18167 (calendar-cursor-to-date))))
18169 (defun org-date-from-calendar ()
18170 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18171 If there is already a time stamp at the cursor position, update it."
18172 (interactive)
18173 (if (org-at-timestamp-p t)
18174 (org-timestamp-change 0 'calendar)
18175 (let ((cal-date (org-get-date-from-calendar)))
18176 (org-insert-time-stamp
18177 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18179 (defcustom org-effort-durations
18180 `(("min" . 1)
18181 ("h" . 60)
18182 ("d" . ,(* 60 8))
18183 ("w" . ,(* 60 8 5))
18184 ("m" . ,(* 60 8 5 4))
18185 ("y" . ,(* 60 8 5 40)))
18186 "Conversion factor to minutes for an effort modifier.
18188 Each entry has the form (MODIFIER . MINUTES).
18190 In an effort string, a number followed by MODIFIER is multiplied
18191 by the specified number of MINUTES to obtain an effort in
18192 minutes.
18194 For example, if the value of this variable is ((\"hours\" . 60)), then an
18195 effort string \"2hours\" is equivalent to 120 minutes."
18196 :group 'org-agenda
18197 :version "25.1"
18198 :package-version '(Org . "8.3")
18199 :type '(alist :key-type (string :tag "Modifier")
18200 :value-type (number :tag "Minutes")))
18202 (defun org-minutes-to-clocksum-string (m)
18203 "Format number of minutes as a clocksum string.
18204 The format is determined by `org-time-clocksum-format',
18205 `org-time-clocksum-use-fractional' and
18206 `org-time-clocksum-fractional-format' and
18207 `org-time-clocksum-use-effort-durations'."
18208 (let ((clocksum "")
18209 (m (round m)) ; Don't allow fractions of minutes
18210 h d w mo y fmt n)
18211 (setq h (if org-time-clocksum-use-effort-durations
18212 (cdr (assoc "h" org-effort-durations)) 60)
18213 d (if org-time-clocksum-use-effort-durations
18214 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18215 w (if org-time-clocksum-use-effort-durations
18216 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18217 mo (if org-time-clocksum-use-effort-durations
18218 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18219 y (if org-time-clocksum-use-effort-durations
18220 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18221 ;; fractional format
18222 (if org-time-clocksum-use-fractional
18223 (cond
18224 ;; single format string
18225 ((stringp org-time-clocksum-fractional-format)
18226 (format org-time-clocksum-fractional-format (/ m (float h))))
18227 ;; choice of fractional formats for different time units
18228 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18229 (> (/ (truncate m) (* y d h)) 0))
18230 (format fmt (/ m (* y d (float h)))))
18231 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18232 (> (/ (truncate m) (* mo d h)) 0))
18233 (format fmt (/ m (* mo d (float h)))))
18234 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18235 (> (/ (truncate m) (* w d h)) 0))
18236 (format fmt (/ m (* w d (float h)))))
18237 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18238 (> (/ (truncate m) (* d h)) 0))
18239 (format fmt (/ m (* d (float h)))))
18240 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18241 (> (/ (truncate m) h) 0))
18242 (format fmt (/ m (float h))))
18243 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18244 (format fmt m))
18245 ;; fall back to smallest time unit with a format
18246 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18247 (format fmt (/ m (float h))))
18248 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18249 (format fmt (/ m (* d (float h)))))
18250 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18251 (format fmt (/ m (* w d (float h)))))
18252 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18253 (format fmt (/ m (* mo d (float h)))))
18254 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18255 (format fmt (/ m (* y d (float h))))))
18256 ;; standard (non-fractional) format, with single format string
18257 (if (stringp org-time-clocksum-format)
18258 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18259 ;; separate formats components
18260 (and (setq fmt (plist-get org-time-clocksum-format :years))
18261 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18262 (plist-get org-time-clocksum-format :require-years))
18263 (setq clocksum (concat clocksum (format fmt n))
18264 m (- m (* n y d h))))
18265 (and (setq fmt (plist-get org-time-clocksum-format :months))
18266 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18267 (plist-get org-time-clocksum-format :require-months))
18268 (setq clocksum (concat clocksum (format fmt n))
18269 m (- m (* n mo d h))))
18270 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18271 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18272 (plist-get org-time-clocksum-format :require-weeks))
18273 (setq clocksum (concat clocksum (format fmt n))
18274 m (- m (* n w d h))))
18275 (and (setq fmt (plist-get org-time-clocksum-format :days))
18276 (or (> (setq n (/ (truncate m) (* d h))) 0)
18277 (plist-get org-time-clocksum-format :require-days))
18278 (setq clocksum (concat clocksum (format fmt n))
18279 m (- m (* n d h))))
18280 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18281 (or (> (setq n (/ (truncate m) h)) 0)
18282 (plist-get org-time-clocksum-format :require-hours))
18283 (setq clocksum (concat clocksum (format fmt n))
18284 m (- m (* n h))))
18285 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18286 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18287 (setq clocksum (concat clocksum (format fmt m))))
18288 ;; return formatted time duration
18289 clocksum))))
18291 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18292 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18293 "Org mode version 8.0")
18295 (defun org-hours-to-clocksum-string (n)
18296 (org-minutes-to-clocksum-string (* n 60)))
18298 (defun org-hh:mm-string-to-minutes (s)
18299 "Convert a string H:MM to a number of minutes.
18300 If the string is just a number, interpret it as minutes.
18301 In fact, the first hh:mm or number in the string will be taken,
18302 there can be extra stuff in the string.
18303 If no number is found, the return value is 0."
18304 (cond
18305 ((integerp s) s)
18306 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18307 (+ (* (string-to-number (match-string 1 s)) 60)
18308 (string-to-number (match-string 2 s))))
18309 ((string-match "\\([0-9]+\\)" s)
18310 (string-to-number (match-string 1 s)))
18311 (t 0)))
18313 (defcustom org-image-actual-width t
18314 "Should we use the actual width of images when inlining them?
18316 When set to t, always use the image width.
18318 When set to a number, use imagemagick (when available) to set
18319 the image's width to this value.
18321 When set to a number in a list, try to get the width from any
18322 #+ATTR.* keyword if it matches a width specification like
18324 #+ATTR_HTML: :width 300px
18326 and fall back on that number if none is found.
18328 When set to nil, try to get the width from an #+ATTR.* keyword
18329 and fall back on the original width if none is found.
18331 This requires Emacs >= 24.1, build with imagemagick support."
18332 :group 'org-appearance
18333 :version "24.4"
18334 :package-version '(Org . "8.0")
18335 :type '(choice
18336 (const :tag "Use the image width" t)
18337 (integer :tag "Use a number of pixels")
18338 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18339 (const :tag "Use #+ATTR* or don't resize" nil)))
18341 (defcustom org-agenda-inhibit-startup nil
18342 "Inhibit startup when preparing agenda buffers.
18343 When this variable is t, the initialization of the Org agenda
18344 buffers is inhibited: e.g. the visibility state is not set, the
18345 tables are not re-aligned, etc."
18346 :type 'boolean
18347 :version "24.3"
18348 :group 'org-agenda)
18350 (define-obsolete-variable-alias
18351 'org-agenda-ignore-drawer-properties
18352 'org-agenda-ignore-properties "25.1")
18354 (defcustom org-agenda-ignore-properties nil
18355 "Avoid updating text properties when building the agenda.
18356 Properties are used to prepare buffers for effort estimates,
18357 appointments, statistics and subtree-local categories.
18358 If you don't use these in the agenda, you can add them to this
18359 list and agenda building will be a bit faster.
18360 The value is a list, with zero or more of the symbols `effort', `appt',
18361 `stats' or `category'."
18362 :type '(set :greedy t
18363 (const effort)
18364 (const appt)
18365 (const stats)
18366 (const category))
18367 :version "25.1"
18368 :package-version '(Org . "8.3")
18369 :group 'org-agenda)
18371 (defun org-duration-string-to-minutes (s &optional output-to-string)
18372 "Convert a duration string S to minutes.
18374 A bare number is interpreted as minutes, modifiers can be set by
18375 customizing `org-effort-durations' (which see).
18377 Entries containing a colon are interpreted as H:MM by
18378 `org-hh:mm-string-to-minutes'."
18379 (let ((result 0)
18380 (re (concat "\\([0-9.]+\\) *\\("
18381 (regexp-opt (mapcar 'car org-effort-durations))
18382 "\\)")))
18383 (while (string-match re s)
18384 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18385 (string-to-number (match-string 1 s))))
18386 (setq s (replace-match "" nil t s)))
18387 (setq result (floor result))
18388 (incf result (org-hh:mm-string-to-minutes s))
18389 (if output-to-string (number-to-string result) result)))
18391 ;;;; Files
18393 (defun org-save-all-org-buffers ()
18394 "Save all Org-mode buffers without user confirmation."
18395 (interactive)
18396 (message "Saving all Org-mode buffers...")
18397 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18398 (when (featurep 'org-id) (org-id-locations-save))
18399 (message "Saving all Org-mode buffers... done"))
18401 (defun org-revert-all-org-buffers ()
18402 "Revert all Org-mode buffers.
18403 Prompt for confirmation when there are unsaved changes.
18404 Be sure you know what you are doing before letting this function
18405 overwrite your changes.
18407 This function is useful in a setup where one tracks org files
18408 with a version control system, to revert on one machine after pulling
18409 changes from another. I believe the procedure must be like this:
18411 1. M-x org-save-all-org-buffers
18412 2. Pull changes from the other machine, resolve conflicts
18413 3. M-x org-revert-all-org-buffers"
18414 (interactive)
18415 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18416 (user-error "Abort"))
18417 (save-excursion
18418 (save-window-excursion
18419 (mapc
18420 (lambda (b)
18421 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18422 (with-current-buffer b buffer-file-name))
18423 (org-pop-to-buffer-same-window b)
18424 (revert-buffer t 'no-confirm)))
18425 (buffer-list))
18426 (when (and (featurep 'org-id) org-id-track-globally)
18427 (org-id-locations-load)))))
18429 ;;;; Agenda files
18431 ;;;###autoload
18432 (defun org-switchb (&optional arg)
18433 "Switch between Org buffers.
18434 With one prefix argument, restrict available buffers to files.
18435 With two prefix arguments, restrict available buffers to agenda files.
18437 Defaults to `iswitchb' for buffer name completion.
18438 Set `org-completion-use-ido' to make it use ido instead."
18439 (interactive "P")
18440 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18441 ((equal arg '(16)) (org-buffer-list 'agenda))
18442 (t (org-buffer-list))))
18443 (org-completion-use-iswitchb org-completion-use-iswitchb)
18444 (org-completion-use-ido org-completion-use-ido))
18445 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18446 (setq org-completion-use-iswitchb t))
18447 (org-pop-to-buffer-same-window
18448 (org-icompleting-read "Org buffer: "
18449 (mapcar 'list (mapcar 'buffer-name blist))
18450 nil t))))
18452 ;;; Define some older names previously used for this functionality
18453 ;;;###autoload
18454 (defalias 'org-ido-switchb 'org-switchb)
18455 ;;;###autoload
18456 (defalias 'org-iswitchb 'org-switchb)
18458 (defun org-buffer-list (&optional predicate exclude-tmp)
18459 "Return a list of Org buffers.
18460 PREDICATE can be `export', `files' or `agenda'.
18462 export restrict the list to Export buffers.
18463 files restrict the list to buffers visiting Org files.
18464 agenda restrict the list to buffers visiting agenda files.
18466 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18467 (let* ((bfn nil)
18468 (agenda-files (and (eq predicate 'agenda)
18469 (mapcar 'file-truename (org-agenda-files t))))
18470 (filter
18471 (cond
18472 ((eq predicate 'files)
18473 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18474 ((eq predicate 'export)
18475 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18476 ((eq predicate 'agenda)
18477 (lambda (b)
18478 (with-current-buffer b
18479 (and (derived-mode-p 'org-mode)
18480 (setq bfn (buffer-file-name b))
18481 (member (file-truename bfn) agenda-files)))))
18482 (t (lambda (b) (with-current-buffer b
18483 (or (derived-mode-p 'org-mode)
18484 (string-match "\\*Org .*Export"
18485 (buffer-name b)))))))))
18486 (delq nil
18487 (mapcar
18488 (lambda(b)
18489 (if (and (funcall filter b)
18490 (or (not exclude-tmp)
18491 (not (string-match "tmp" (buffer-name b)))))
18493 nil))
18494 (buffer-list)))))
18496 (defun org-agenda-files (&optional unrestricted archives)
18497 "Get the list of agenda files.
18498 Optional UNRESTRICTED means return the full list even if a restriction
18499 is currently in place.
18500 When ARCHIVES is t, include all archive files that are really being
18501 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18502 `org-agenda-archives-mode' is t."
18503 (let ((files
18504 (cond
18505 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18506 ((stringp org-agenda-files) (org-read-agenda-file-list))
18507 ((listp org-agenda-files) org-agenda-files)
18508 (t (error "Invalid value of `org-agenda-files'")))))
18509 (setq files (apply 'append
18510 (mapcar (lambda (f)
18511 (if (file-directory-p f)
18512 (directory-files
18513 f t org-agenda-file-regexp)
18514 (list f)))
18515 files)))
18516 (when org-agenda-skip-unavailable-files
18517 (setq files (delq nil
18518 (mapcar (function
18519 (lambda (file)
18520 (and (file-readable-p file) file)))
18521 files))))
18522 (when (or (eq archives t)
18523 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18524 (setq files (org-add-archive-files files)))
18525 files))
18527 (defun org-agenda-file-p (&optional file)
18528 "Return non-nil, if FILE is an agenda file.
18529 If FILE is omitted, use the file associated with the current
18530 buffer."
18531 (let ((fname (or file (buffer-file-name))))
18532 (and fname
18533 (member (file-truename fname)
18534 (mapcar #'file-truename (org-agenda-files t))))))
18536 (defun org-edit-agenda-file-list ()
18537 "Edit the list of agenda files.
18538 Depending on setup, this either uses customize to edit the variable
18539 `org-agenda-files', or it visits the file that is holding the list. In the
18540 latter case, the buffer is set up in a way that saving it automatically kills
18541 the buffer and restores the previous window configuration."
18542 (interactive)
18543 (if (stringp org-agenda-files)
18544 (let ((cw (current-window-configuration)))
18545 (find-file org-agenda-files)
18546 (org-set-local 'org-window-configuration cw)
18547 (org-add-hook 'after-save-hook
18548 (lambda ()
18549 (set-window-configuration
18550 (prog1 org-window-configuration
18551 (kill-buffer (current-buffer))))
18552 (org-install-agenda-files-menu)
18553 (message "New agenda file list installed"))
18554 nil 'local)
18555 (message "%s" (substitute-command-keys
18556 "Edit list and finish with \\[save-buffer]")))
18557 (customize-variable 'org-agenda-files)))
18559 (defun org-store-new-agenda-file-list (list)
18560 "Set new value for the agenda file list and save it correctly."
18561 (if (stringp org-agenda-files)
18562 (let ((fe (org-read-agenda-file-list t)) b u)
18563 (while (setq b (find-buffer-visiting org-agenda-files))
18564 (kill-buffer b))
18565 (with-temp-file org-agenda-files
18566 (insert
18567 (mapconcat
18568 (lambda (f) ;; Keep un-expanded entries.
18569 (if (setq u (assoc f fe))
18570 (cdr u)
18572 list "\n")
18573 "\n")))
18574 (let ((org-mode-hook nil) (org-inhibit-startup t)
18575 (org-insert-mode-line-in-empty-file nil))
18576 (setq org-agenda-files list)
18577 (customize-save-variable 'org-agenda-files org-agenda-files))))
18579 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18580 "Read the list of agenda files from a file.
18581 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18582 filenames, used by `org-store-new-agenda-file-list' to write back
18583 un-expanded file names."
18584 (when (file-directory-p org-agenda-files)
18585 (error "`org-agenda-files' cannot be a single directory"))
18586 (when (stringp org-agenda-files)
18587 (with-temp-buffer
18588 (insert-file-contents org-agenda-files)
18589 (mapcar
18590 (lambda (f)
18591 (let ((e (expand-file-name (substitute-in-file-name f)
18592 org-directory)))
18593 (if pair-with-expansion
18594 (cons e f)
18595 e)))
18596 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18598 ;;;###autoload
18599 (defun org-cycle-agenda-files ()
18600 "Cycle through the files in `org-agenda-files'.
18601 If the current buffer visits an agenda file, find the next one in the list.
18602 If the current buffer does not, find the first agenda file."
18603 (interactive)
18604 (let* ((fs (or (org-agenda-files t)
18605 (user-error "No agenda files")))
18606 (files (copy-sequence fs))
18607 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18608 file)
18609 (when tcf
18610 (while (and (setq file (pop files))
18611 (not (equal (file-truename file) tcf)))))
18612 (find-file (car (or files fs)))
18613 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18615 (defun org-agenda-file-to-front (&optional to-end)
18616 "Move/add the current file to the top of the agenda file list.
18617 If the file is not present in the list, it is added to the front. If it is
18618 present, it is moved there. With optional argument TO-END, add/move to the
18619 end of the list."
18620 (interactive "P")
18621 (let ((org-agenda-skip-unavailable-files nil)
18622 (file-alist (mapcar (lambda (x)
18623 (cons (file-truename x) x))
18624 (org-agenda-files t)))
18625 (ctf (file-truename
18626 (or buffer-file-name
18627 (user-error "Please save the current buffer to a file"))))
18628 x had)
18629 (setq x (assoc ctf file-alist) had x)
18631 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18632 (if to-end
18633 (setq file-alist (append (delq x file-alist) (list x)))
18634 (setq file-alist (cons x (delq x file-alist))))
18635 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18636 (org-install-agenda-files-menu)
18637 (message "File %s to %s of agenda file list"
18638 (if had "moved" "added") (if to-end "end" "front"))))
18640 (defun org-remove-file (&optional file)
18641 "Remove current file from the list of files in variable `org-agenda-files'.
18642 These are the files which are being checked for agenda entries.
18643 Optional argument FILE means use this file instead of the current."
18644 (interactive)
18645 (let* ((org-agenda-skip-unavailable-files nil)
18646 (file (or file buffer-file-name
18647 (user-error "Current buffer does not visit a file")))
18648 (true-file (file-truename file))
18649 (afile (abbreviate-file-name file))
18650 (files (delq nil (mapcar
18651 (lambda (x)
18652 (if (equal true-file
18653 (file-truename x))
18654 nil x))
18655 (org-agenda-files t)))))
18656 (if (not (= (length files) (length (org-agenda-files t))))
18657 (progn
18658 (org-store-new-agenda-file-list files)
18659 (org-install-agenda-files-menu)
18660 (message "Removed from Org Agenda list: %s" afile))
18661 (message "File was not in list: %s (not removed)" afile))))
18663 (defun org-file-menu-entry (file)
18664 (vector file (list 'find-file file) t))
18666 (defun org-check-agenda-file (file)
18667 "Make sure FILE exists. If not, ask user what to do."
18668 (when (not (file-exists-p file))
18669 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18670 (abbreviate-file-name file))
18671 (let ((r (downcase (read-char-exclusive))))
18672 (cond
18673 ((equal r ?r)
18674 (org-remove-file file)
18675 (throw 'nextfile t))
18676 (t (user-error "Abort"))))))
18678 (defun org-get-agenda-file-buffer (file)
18679 "Get an agenda buffer visiting FILE.
18680 If the buffer needs to be created, add it to the list of buffers
18681 which might be released later."
18682 (let ((buf (org-find-base-buffer-visiting file)))
18683 (if buf
18684 buf ; just return it
18685 ;; Make a new buffer and remember it
18686 (setq buf (find-file-noselect file))
18687 (if buf (push buf org-agenda-new-buffers))
18688 buf)))
18690 (defun org-release-buffers (blist)
18691 "Release all buffers in list, asking the user for confirmation when needed.
18692 When a buffer is unmodified, it is just killed. When modified, it is saved
18693 \(if the user agrees) and then killed."
18694 (let (file)
18695 (dolist (buf blist)
18696 (setq file (buffer-file-name buf))
18697 (when (and (buffer-modified-p buf)
18698 file
18699 (y-or-n-p (format "Save file %s? " file)))
18700 (with-current-buffer buf (save-buffer)))
18701 (kill-buffer buf))))
18703 (defun org-agenda-prepare-buffers (files)
18704 "Create buffers for all agenda files, protect archived trees and comments."
18705 (interactive)
18706 (let ((pa '(:org-archived t))
18707 (pc '(:org-comment t))
18708 (pall '(:org-archived t :org-comment t))
18709 (inhibit-read-only t)
18710 (org-inhibit-startup org-agenda-inhibit-startup)
18711 (rea (concat ":" org-archive-tag ":"))
18712 file re pos)
18713 (setq org-tag-alist-for-agenda nil
18714 org-tag-groups-alist-for-agenda nil)
18715 (save-excursion
18716 (save-restriction
18717 (dolist (file files)
18718 (catch 'nextfile
18719 (if (bufferp file)
18720 (set-buffer file)
18721 (org-check-agenda-file file)
18722 (set-buffer (org-get-agenda-file-buffer file)))
18723 (widen)
18724 (org-set-regexps-and-options 'tags-only)
18725 (setq pos (point))
18726 (or (memq 'category org-agenda-ignore-properties)
18727 (org-refresh-category-properties))
18728 (or (memq 'stats org-agenda-ignore-properties)
18729 (org-refresh-stats-properties))
18730 (or (memq 'effort org-agenda-ignore-properties)
18731 (org-refresh-effort-properties))
18732 (or (memq 'appt org-agenda-ignore-properties)
18733 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18734 (setq org-todo-keywords-for-agenda
18735 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18736 (setq org-done-keywords-for-agenda
18737 (append org-done-keywords-for-agenda org-done-keywords))
18738 (setq org-todo-keyword-alist-for-agenda
18739 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18740 (setq org-tag-alist-for-agenda
18741 (org-uniquify
18742 (append org-tag-alist-for-agenda
18743 org-tag-alist
18744 org-tag-persistent-alist)))
18745 (if org-group-tags
18746 (setq org-tag-groups-alist-for-agenda
18747 (org-uniquify-alist
18748 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18749 (org-with-silent-modifications
18750 (save-excursion
18751 (remove-text-properties (point-min) (point-max) pall)
18752 (when org-agenda-skip-archived-trees
18753 (goto-char (point-min))
18754 (while (re-search-forward rea nil t)
18755 (if (org-at-heading-p t)
18756 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18757 (goto-char (point-min))
18758 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18759 (while (re-search-forward re nil t)
18760 (when (save-match-data (org-in-commented-heading-p t))
18761 (add-text-properties
18762 (match-beginning 0) (org-end-of-subtree t) pc)))))
18763 (goto-char pos)))))
18764 (setq org-todo-keywords-for-agenda
18765 (org-uniquify org-todo-keywords-for-agenda))
18766 (setq org-todo-keyword-alist-for-agenda
18767 (org-uniquify org-todo-keyword-alist-for-agenda))))
18770 ;;;; CDLaTeX minor mode
18772 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18773 "Keymap for the minor `org-cdlatex-mode'.")
18775 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18776 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18777 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18778 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18779 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18781 (defvar org-cdlatex-texmathp-advice-is-done nil
18782 "Flag remembering if we have applied the advice to texmathp already.")
18784 (define-minor-mode org-cdlatex-mode
18785 "Toggle the minor `org-cdlatex-mode'.
18786 This mode supports entering LaTeX environment and math in LaTeX fragments
18787 in Org-mode.
18788 \\{org-cdlatex-mode-map}"
18789 nil " OCDL" nil
18790 (when org-cdlatex-mode
18791 (require 'cdlatex)
18792 (run-hooks 'cdlatex-mode-hook)
18793 (cdlatex-compute-tables))
18794 (unless org-cdlatex-texmathp-advice-is-done
18795 (setq org-cdlatex-texmathp-advice-is-done t)
18796 (defadvice texmathp (around org-math-always-on activate)
18797 "Always return t in org-mode buffers.
18798 This is because we want to insert math symbols without dollars even outside
18799 the LaTeX math segments. If Orgmode thinks that point is actually inside
18800 an embedded LaTeX fragment, let texmathp do its job.
18801 \\[org-cdlatex-mode-map]"
18802 (interactive)
18803 (let (p)
18804 (cond
18805 ((not (derived-mode-p 'org-mode)) ad-do-it)
18806 ((eq this-command 'cdlatex-math-symbol)
18807 (setq ad-return-value t
18808 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18810 (let ((p (org-inside-LaTeX-fragment-p)))
18811 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18812 (setq ad-return-value t
18813 texmathp-why '("Org-mode embedded math" . 0))
18814 (if p ad-do-it)))))))))
18816 (defun turn-on-org-cdlatex ()
18817 "Unconditionally turn on `org-cdlatex-mode'."
18818 (org-cdlatex-mode 1))
18820 (defun org-try-cdlatex-tab ()
18821 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18822 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18823 - inside a LaTeX fragment, or
18824 - after the first word in a line, where an abbreviation expansion could
18825 insert a LaTeX environment."
18826 (when org-cdlatex-mode
18827 (cond
18828 ;; Before any word on the line: No expansion possible.
18829 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18830 ;; Just after first word on the line: Expand it. Make sure it
18831 ;; cannot happen on headlines, though.
18832 ((save-excursion
18833 (skip-chars-backward "a-zA-Z0-9*")
18834 (skip-chars-backward " \t")
18835 (and (bolp) (not (org-at-heading-p))))
18836 (cdlatex-tab) t)
18837 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18839 (defun org-cdlatex-underscore-caret (&optional arg)
18840 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18841 Revert to the normal definition outside of these fragments."
18842 (interactive "P")
18843 (if (org-inside-LaTeX-fragment-p)
18844 (call-interactively 'cdlatex-sub-superscript)
18845 (let (org-cdlatex-mode)
18846 (call-interactively (key-binding (vector last-input-event))))))
18848 (defun org-cdlatex-math-modify (&optional arg)
18849 "Execute `cdlatex-math-modify' in LaTeX fragments.
18850 Revert to the normal definition outside of these fragments."
18851 (interactive "P")
18852 (if (org-inside-LaTeX-fragment-p)
18853 (call-interactively 'cdlatex-math-modify)
18854 (let (org-cdlatex-mode)
18855 (call-interactively (key-binding (vector last-input-event))))))
18857 (defun org-cdlatex-environment-indent (&optional environment item)
18858 "Execute `cdlatex-environment' and indent the inserted environment.
18860 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18862 The inserted environment is indented to current indentation
18863 unless point is at the beginning of the line, in which the
18864 environment remains unintended."
18865 (interactive)
18866 ;; cdlatex-environment always return nil. Therefore, capture output
18867 ;; first and determine if an environment was selected.
18868 (let* ((beg (point-marker))
18869 (end (copy-marker (point) t))
18870 (inserted (progn
18871 (ignore-errors (cdlatex-environment environment item))
18872 (< beg end)))
18873 ;; Figure out how many lines to move forward after the
18874 ;; environment has been inserted.
18875 (lines (when inserted
18876 (save-excursion
18877 (- (loop while (< beg (point))
18878 with x = 0
18879 do (forward-line -1)
18880 (incf x)
18881 finally return x)
18882 (if (progn (goto-char beg)
18883 (and (progn (skip-chars-forward " \t") (eolp))
18884 (progn (skip-chars-backward " \t") (bolp))))
18885 1 0)))))
18886 (env (org-trim (delete-and-extract-region beg end))))
18887 (when inserted
18888 ;; Get indentation of next line unless at column 0.
18889 (let ((ind (if (bolp) 0
18890 (save-excursion
18891 (org-return-indent)
18892 (prog1 (org-get-indentation)
18893 (when (progn (skip-chars-forward " \t") (eolp))
18894 (delete-region beg (point)))))))
18895 (bol (progn (skip-chars-backward " \t") (bolp))))
18896 ;; Insert a newline before environment unless at column zero
18897 ;; to "escape" the current line. Insert a newline if
18898 ;; something is one the same line as \end{ENVIRONMENT}.
18899 (insert
18900 (concat (unless bol "\n") env
18901 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18902 (unless (zerop ind)
18903 (save-excursion
18904 (goto-char beg)
18905 (while (< (point) end)
18906 (unless (eolp) (org-indent-line-to ind))
18907 (forward-line))))
18908 (goto-char beg)
18909 (forward-line lines)
18910 (org-indent-line-to ind)))
18911 (set-marker beg nil)
18912 (set-marker end nil)))
18915 ;;;; LaTeX fragments
18917 (defun org-inside-LaTeX-fragment-p ()
18918 "Test if point is inside a LaTeX fragment.
18919 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18920 sequence appearing also before point.
18921 Even though the matchers for math are configurable, this function assumes
18922 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18923 delimiters are skipped when they have been removed by customization.
18924 The return value is nil, or a cons cell with the delimiter and the
18925 position of this delimiter.
18927 This function does a reasonably good job, but can locally be fooled by
18928 for example currency specifications. For example it will assume being in
18929 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18930 fragments that are properly closed, but during editing, we have to live
18931 with the uncertainty caused by missing closing delimiters. This function
18932 looks only before point, not after."
18933 (catch 'exit
18934 (let ((pos (point))
18935 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18936 (lim (progn
18937 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18938 (point)))
18939 dd-on str (start 0) m re)
18940 (goto-char pos)
18941 (when dodollar
18942 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18943 re (nth 1 (assoc "$" org-latex-regexps)))
18944 (while (string-match re str start)
18945 (cond
18946 ((= (match-end 0) (length str))
18947 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18948 ((= (match-end 0) (- (length str) 5))
18949 (throw 'exit nil))
18950 (t (setq start (match-end 0))))))
18951 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18952 (goto-char pos)
18953 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18954 (and (match-beginning 2) (throw 'exit nil))
18955 ;; count $$
18956 (while (re-search-backward "\\$\\$" lim t)
18957 (setq dd-on (not dd-on)))
18958 (goto-char pos)
18959 (if dd-on (cons "$$" m))))))
18961 (defun org-inside-latex-macro-p ()
18962 "Is point inside a LaTeX macro or its arguments?"
18963 (save-match-data
18964 (org-in-regexp
18965 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18967 (defvar org-latex-fragment-image-overlays nil
18968 "List of overlays carrying the images of latex fragments.")
18969 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18971 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18972 "Remove all overlays with LaTeX fragment images in current buffer.
18973 When optional arguments BEG and END are non-nil, remove all
18974 overlays between them instead. Return t when some overlays were
18975 removed, nil otherwise."
18976 (let (removedp)
18977 (setq org-latex-fragment-image-overlays
18978 (let ((beg (or beg (point-min)))
18979 (end (or end (point-max))))
18980 (org-remove-if
18981 (lambda (o)
18982 (cond ((not (overlay-buffer o)) (delete-overlay o) t)
18983 ((and (>= (overlay-start o) beg)
18984 (<= (overlay-end o) end))
18985 (delete-overlay o)
18986 (unless removedp (setq removedp t)))
18987 (t nil)))
18988 org-latex-fragment-image-overlays)))
18989 removedp))
18991 (define-obsolete-function-alias
18992 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18993 (defun org-toggle-latex-fragment (&optional arg)
18994 "Preview the LaTeX fragment at point, or all locally or globally.
18996 If the cursor is on a LaTeX fragment, create the image and overlay
18997 it over the source code, if there is none. Remove it otherwise.
18998 If there is no fragment at point, display all fragments in the
18999 current section.
19001 With prefix ARG, preview or clear image for all fragments in the
19002 current subtree or in the whole buffer when used before the first
19003 headline. With a double prefix ARG \\[universal-argument] \
19004 \\[universal-argument] preview or clear images
19005 for all fragments in the buffer."
19006 (interactive "P")
19007 (unless (buffer-file-name (buffer-base-buffer))
19008 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
19009 (when (display-graphic-p)
19010 (catch 'exit
19011 (save-excursion
19012 (let ((window-start (window-start)) msg)
19013 (save-restriction
19014 (cond
19015 ((or (equal arg '(16))
19016 (and (equal arg '(4))
19017 (org-with-limited-levels (org-before-first-heading-p))))
19018 (if (org-remove-latex-fragment-image-overlays)
19019 (progn (message "LaTeX fragments images removed from buffer")
19020 (throw 'exit nil))
19021 (setq msg "Creating images for buffer...")))
19022 ((equal arg '(4))
19023 (org-with-limited-levels (org-back-to-heading t))
19024 (let ((beg (point))
19025 (end (progn (org-end-of-subtree t) (point))))
19026 (if (org-remove-latex-fragment-image-overlays beg end)
19027 (progn
19028 (message "LaTeX fragment images removed from subtree")
19029 (throw 'exit nil))
19030 (setq msg "Creating images for subtree...")
19031 (narrow-to-region beg end))))
19032 ((let ((datum (org-element-context)))
19033 (when (memq (org-element-type datum)
19034 '(latex-environment latex-fragment))
19035 (let* ((beg (org-element-property :begin datum))
19036 (end (org-element-property :end datum)))
19037 (if (org-remove-latex-fragment-image-overlays beg end)
19038 (progn (message "LaTeX fragment image removed")
19039 (throw 'exit nil))
19040 (narrow-to-region beg end)
19041 (setq msg "Creating image..."))))))
19043 (org-with-limited-levels
19044 (let ((beg (if (org-at-heading-p) (line-beginning-position)
19045 (outline-previous-heading)
19046 (point)))
19047 (end (progn (outline-next-heading) (point))))
19048 (if (org-remove-latex-fragment-image-overlays beg end)
19049 (progn
19050 (message "LaTeX fragment images removed from section")
19051 (throw 'exit nil))
19052 (setq msg "Creating images for section...")
19053 (narrow-to-region beg end))))))
19054 (let ((file (buffer-file-name (buffer-base-buffer))))
19055 (org-format-latex
19056 (concat org-latex-preview-ltxpng-directory
19057 (file-name-sans-extension (file-name-nondirectory file)))
19058 ;; Emacs cannot overlay images from remote hosts.
19059 ;; Create it in `temporary-file-directory' instead.
19060 (if (file-remote-p file) temporary-file-directory
19061 default-directory)
19062 'overlays msg 'forbuffer
19063 org-latex-create-formula-image-program)))
19064 ;; Work around a bug that doesn't restore window's start
19065 ;; when widening back the buffer.
19066 (set-window-start nil window-start)
19067 (message (concat msg "done")))))))
19069 (defun org-format-latex
19070 (prefix &optional dir overlays msg forbuffer processing-type)
19071 "Replace LaTeX fragments with links to an image, and produce images.
19073 When optional argument OVERLAYS is non-nil, display the image on
19074 top of the fragment instead of replacing it.
19076 PROCESSING-TYPE is the conversion method to use, as a symbol.
19078 Some of the options can be changed using the variable
19079 `org-format-latex-options', which see."
19080 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19081 (unless (eq processing-type 'verbatim)
19082 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19083 (cnt 0)
19084 checkdir-flag)
19085 (goto-char (point-min))
19086 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19087 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19088 (overlay-recenter (point-max)))
19089 (while (re-search-forward math-regexp nil t)
19090 (unless (and overlays
19091 (eq (get-char-property (point) 'org-overlay-type)
19092 'org-latex-overlay))
19093 (let* ((context (org-element-context))
19094 (type (org-element-type context)))
19095 (when (memq type '(latex-environment latex-fragment))
19096 (let ((block-type (eq type 'latex-environment))
19097 (value (org-element-property :value context))
19098 (beg (org-element-property :begin context))
19099 (end (save-excursion
19100 (goto-char (org-element-property :end context))
19101 (skip-chars-backward " \r\t\n")
19102 (point))))
19103 (case processing-type
19104 (mathjax
19105 ;; Prepare for MathJax processing.
19106 (if (eq (char-after beg) ?$)
19107 (save-excursion
19108 (delete-region beg end)
19109 (insert "\\(" (substring value 1 -1) "\\)"))
19110 (goto-char end)))
19111 ((dvipng imagemagick)
19112 ;; Process to an image.
19113 (incf cnt)
19114 (goto-char beg)
19115 (let* ((face (face-at-point))
19116 ;; Get the colors from the face at point.
19118 (let ((color (plist-get org-format-latex-options
19119 :foreground)))
19120 (if (and forbuffer (eq color 'auto))
19121 (face-attribute face :foreground nil 'default)
19122 color)))
19124 (let ((color (plist-get org-format-latex-options
19125 :background)))
19126 (if (and forbuffer (eq color 'auto))
19127 (face-attribute face :background nil 'default)
19128 color)))
19129 (hash (sha1 (prin1-to-string
19130 (list org-format-latex-header
19131 org-latex-default-packages-alist
19132 org-latex-packages-alist
19133 org-format-latex-options
19134 forbuffer value fg bg))))
19135 (absprefix (expand-file-name prefix dir))
19136 (linkfile (format "%s_%s.png" prefix hash))
19137 (movefile (format "%s_%s.png" absprefix hash))
19138 (sep (and block-type "\n\n"))
19139 (link (concat sep "[[file:" linkfile "]]" sep))
19140 (options
19141 (org-combine-plists
19142 org-format-latex-options
19143 `(:foreground ,fg :background ,bg))))
19144 (when msg (message msg cnt))
19145 (unless checkdir-flag ; Ensure the directory exists.
19146 (setq checkdir-flag t)
19147 (let ((todir (file-name-directory absprefix)))
19148 (unless (file-directory-p todir)
19149 (make-directory todir t))))
19150 (unless (file-exists-p movefile)
19151 (org-create-formula-image
19152 value movefile options forbuffer processing-type))
19153 (if overlays
19154 (progn
19155 (dolist (o (overlays-in beg end))
19156 (when (eq (overlay-get o 'org-overlay-type)
19157 'org-latex-overlay)
19158 (delete-overlay o)))
19159 (let ((ov (make-overlay beg end)))
19160 (overlay-put ov
19161 'org-overlay-type
19162 'org-latex-overlay)
19163 (overlay-put ov 'evaporate t)
19164 (if (featurep 'xemacs)
19165 (progn
19166 (overlay-put ov 'invisible t)
19167 (overlay-put
19168 ov 'end-glyph
19169 (make-glyph
19170 (vector 'png :file movefile))))
19171 (overlay-put
19172 ov 'display
19173 (list 'image
19174 :type 'png
19175 :file movefile
19176 :ascent 'center)))
19177 (push ov org-latex-fragment-image-overlays))
19178 (goto-char end))
19179 (delete-region beg end)
19180 (insert
19181 (org-add-props link
19182 (list 'org-latex-src
19183 (replace-regexp-in-string "\"" "" value)
19184 'org-latex-src-embed-type
19185 (if block-type 'paragraph 'character)))))))
19186 (mathml
19187 ;; Process to MathML.
19188 (unless (org-format-latex-mathml-available-p)
19189 (user-error "LaTeX to MathML converter not configured"))
19190 (incf cnt)
19191 (when msg (message msg cnt))
19192 (goto-char beg)
19193 (delete-region beg end)
19194 (insert (org-format-latex-as-mathml
19195 value block-type prefix dir)))
19196 (otherwise
19197 (error "Unknown conversion type %s for LaTeX fragments"
19198 processing-type)))))))))))
19200 (defun org-create-math-formula (latex-frag &optional mathml-file)
19201 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19202 Use `org-latex-to-mathml-convert-command'. If the conversion is
19203 sucessful, return the portion between \"<math...> </math>\"
19204 elements otherwise return nil. When MATHML-FILE is specified,
19205 write the results in to that file. When invoked as an
19206 interactive command, prompt for LATEX-FRAG, with initial value
19207 set to the current active region and echo the results for user
19208 inspection."
19209 (interactive (list (let ((frag (when (org-region-active-p)
19210 (buffer-substring-no-properties
19211 (region-beginning) (region-end)))))
19212 (read-string "LaTeX Fragment: " frag nil frag))))
19213 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19214 (let* ((tmp-in-file (file-relative-name
19215 (make-temp-name (expand-file-name "ltxmathml-in"))))
19216 (ignore (write-region latex-frag nil tmp-in-file))
19217 (tmp-out-file (file-relative-name
19218 (make-temp-name (expand-file-name "ltxmathml-out"))))
19219 (cmd (format-spec
19220 org-latex-to-mathml-convert-command
19221 `((?j . ,(and org-latex-to-mathml-jar-file
19222 (shell-quote-argument
19223 (expand-file-name
19224 org-latex-to-mathml-jar-file))))
19225 (?I . ,(shell-quote-argument tmp-in-file))
19226 (?i . ,latex-frag)
19227 (?o . ,(shell-quote-argument tmp-out-file)))))
19228 mathml shell-command-output)
19229 (when (org-called-interactively-p 'any)
19230 (unless (org-format-latex-mathml-available-p)
19231 (user-error "LaTeX to MathML converter not configured")))
19232 (message "Running %s" cmd)
19233 (setq shell-command-output (shell-command-to-string cmd))
19234 (setq mathml
19235 (when (file-readable-p tmp-out-file)
19236 (with-current-buffer (find-file-noselect tmp-out-file t)
19237 (goto-char (point-min))
19238 (when (re-search-forward
19239 (concat
19240 (regexp-quote
19241 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19242 "[^>]*?>"
19243 "\\(.\\|\n\\)*"
19244 "</math>")
19245 nil t)
19246 (prog1 (match-string 0) (kill-buffer))))))
19247 (cond
19248 (mathml
19249 (setq mathml
19250 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19251 (when mathml-file
19252 (write-region mathml nil mathml-file))
19253 (when (org-called-interactively-p 'any)
19254 (message mathml)))
19255 ((message "LaTeX to MathML conversion failed")
19256 (message shell-command-output)))
19257 (delete-file tmp-in-file)
19258 (when (file-exists-p tmp-out-file)
19259 (delete-file tmp-out-file))
19260 mathml))
19262 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19263 prefix &optional dir)
19264 "Use `org-create-math-formula' but check local cache first."
19265 (let* ((absprefix (expand-file-name prefix dir))
19266 (print-length nil) (print-level nil)
19267 (formula-id (concat
19268 "formula-"
19269 (sha1
19270 (prin1-to-string
19271 (list latex-frag
19272 org-latex-to-mathml-convert-command)))))
19273 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19274 (formula-cache-dir (file-name-directory formula-cache)))
19276 (unless (file-directory-p formula-cache-dir)
19277 (make-directory formula-cache-dir t))
19279 (unless (file-exists-p formula-cache)
19280 (org-create-math-formula latex-frag formula-cache))
19282 (if (file-exists-p formula-cache)
19283 ;; Successful conversion. Return the link to MathML file.
19284 (org-add-props
19285 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19286 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19287 'org-latex-src-embed-type (if latex-frag-type
19288 'paragraph 'character)))
19289 ;; Failed conversion. Return the LaTeX fragment verbatim
19290 latex-frag)))
19292 (defun org-create-formula-image (string tofile options buffer &optional type)
19293 "Create an image from LaTeX source using dvipng or convert.
19294 This function calls either `org-create-formula-image-with-dvipng'
19295 or `org-create-formula-image-with-imagemagick' depending on the
19296 value of `org-latex-create-formula-image-program' or on the value
19297 of the optional TYPE variable.
19299 Note: ultimately these two function should be combined as they
19300 share a good deal of logic."
19301 (org-check-external-command
19302 "latex" "needed to convert LaTeX fragments to images")
19303 (funcall
19304 (case (or type org-latex-create-formula-image-program)
19305 (dvipng
19306 (org-check-external-command
19307 "dvipng" "needed to convert LaTeX fragments to images")
19308 #'org-create-formula-image-with-dvipng)
19309 (imagemagick
19310 (org-check-external-command
19311 "convert" "you need to install imagemagick")
19312 #'org-create-formula-image-with-imagemagick)
19313 (t (error
19314 "Invalid value of `org-latex-create-formula-image-program'")))
19315 string tofile options buffer))
19317 (declare-function org-export-get-backend "ox" (name))
19318 (declare-function org-export--get-global-options "ox" (&optional backend))
19319 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19320 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19321 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19322 (defun org-create-formula--latex-header ()
19323 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19324 (let ((info (org-combine-plists (org-export--get-global-options
19325 (org-export-get-backend 'latex))
19326 (org-export--get-inbuffer-options
19327 (org-export-get-backend 'latex)))))
19328 (org-latex-guess-babel-language
19329 (org-latex-guess-inputenc
19330 (org-splice-latex-header
19331 org-format-latex-header
19332 org-latex-default-packages-alist
19333 org-latex-packages-alist t
19334 (plist-get info :latex-header)))
19335 info)))
19337 (defun org--get-display-dpi ()
19338 "Get the DPI of the display.
19340 Assumes that the display has the same pixel width in the
19341 horizontal and vertical directions."
19342 (if (display-graphic-p)
19343 (round (/ (display-pixel-height)
19344 (/ (display-mm-height) 25.4)))
19345 (error "Attempt to calculate the dpi of a non-graphic display")))
19347 ;; This function borrows from Ganesh Swami's latex2png.el
19348 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
19349 "This calls dvipng."
19350 (require 'ox-latex)
19351 (let* ((tmpdir (if (featurep 'xemacs)
19352 (temp-directory)
19353 temporary-file-directory))
19354 (texfilebase (make-temp-name
19355 (expand-file-name "orgtex" tmpdir)))
19356 (texfile (concat texfilebase ".tex"))
19357 (dvifile (concat texfilebase ".dvi"))
19358 (pngfile (concat texfilebase ".png"))
19359 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19360 ;; This assumes that the display has the same pixel width in
19361 ;; the horizontal and vertical directions
19362 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19363 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19364 "Black"))
19365 (bg (or (plist-get options (if buffer :background :html-background))
19366 "Transparent")))
19367 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
19368 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
19369 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
19370 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
19371 (let ((latex-header (org-create-formula--latex-header)))
19372 (with-temp-file texfile
19373 (insert latex-header)
19374 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19375 (let ((dir default-directory))
19376 (ignore-errors
19377 (cd tmpdir)
19378 (call-process "latex" nil nil nil texfile))
19379 (cd dir))
19380 (if (not (file-exists-p dvifile))
19381 (progn (message "Failed to create dvi file from %s" texfile) nil)
19382 (ignore-errors
19383 (if (featurep 'xemacs)
19384 (call-process "dvipng" nil nil nil
19385 "-fg" fg "-bg" bg
19386 "-T" "tight"
19387 "-o" pngfile
19388 dvifile)
19389 (call-process "dvipng" nil nil nil
19390 "-fg" fg "-bg" bg
19391 "-D" dpi
19392 ;;"-x" scale "-y" scale
19393 "-T" "tight"
19394 "-o" pngfile
19395 dvifile)))
19396 (if (not (file-exists-p pngfile))
19397 (if org-format-latex-signal-error
19398 (error "Failed to create png file from %s" texfile)
19399 (message "Failed to create png file from %s" texfile)
19400 nil)
19401 ;; Use the requested file name and clean up
19402 (copy-file pngfile tofile 'replace)
19403 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
19404 (if (file-exists-p (concat texfilebase e))
19405 (delete-file (concat texfilebase e))))
19406 pngfile))))
19408 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
19409 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
19410 "This calls convert, which is included into imagemagick."
19411 (require 'ox-latex)
19412 (let* ((tmpdir (if (featurep 'xemacs)
19413 (temp-directory)
19414 temporary-file-directory))
19415 (texfilebase (make-temp-name
19416 (expand-file-name "orgtex" tmpdir)))
19417 (texfile (concat texfilebase ".tex"))
19418 (pdffile (concat texfilebase ".pdf"))
19419 (pngfile (concat texfilebase ".png"))
19420 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19421 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19422 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19423 "black"))
19424 (bg (or (plist-get options (if buffer :background :html-background))
19425 "white")))
19426 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
19427 (setq fg (org-latex-color-format fg)))
19428 (if (eq bg 'default) (setq bg (org-latex-color :background))
19429 (setq bg (org-latex-color-format
19430 (if (string= bg "Transparent") "white" bg))))
19431 (let ((latex-header (org-create-formula--latex-header)))
19432 (with-temp-file texfile
19433 (insert latex-header)
19434 (insert "\n\\begin{document}\n"
19435 "\\definecolor{fg}{rgb}{" fg "}\n"
19436 "\\definecolor{bg}{rgb}{" bg "}\n"
19437 "\n\\pagecolor{bg}\n"
19438 "\n{\\color{fg}\n"
19439 string
19440 "\n}\n"
19441 "\n\\end{document}\n")))
19442 (org-latex-compile texfile t)
19443 (if (not (file-exists-p pdffile))
19444 (progn (message "Failed to create pdf file from %s" texfile) nil)
19445 (ignore-errors
19446 (if (featurep 'xemacs)
19447 (call-process "convert" nil nil nil
19448 "-density" "96"
19449 "-trim"
19450 "-antialias"
19451 pdffile
19452 "-quality" "100"
19453 ;; "-sharpen" "0x1.0"
19454 pngfile)
19455 (call-process "convert" nil nil nil
19456 "-density" dpi
19457 "-trim"
19458 "-antialias"
19459 pdffile
19460 "-quality" "100"
19461 ;; "-sharpen" "0x1.0"
19462 pngfile)))
19463 (if (not (file-exists-p pngfile))
19464 (if org-format-latex-signal-error
19465 (error "Failed to create png file from %s" texfile)
19466 (message "Failed to create png file from %s" texfile)
19467 nil)
19468 ;; Use the requested file name and clean up
19469 (copy-file pngfile tofile 'replace)
19470 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
19471 (if (file-exists-p (concat texfilebase e))
19472 (delete-file (concat texfilebase e))))
19473 pngfile))))
19475 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19476 "Fill a LaTeX header template TPL.
19477 In the template, the following place holders will be recognized:
19479 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19480 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19481 [PACKAGES] \\usepackage statements for PKG
19482 [NO-PACKAGES] do not include PKG
19483 [EXTRA] the string EXTRA
19484 [NO-EXTRA] do not include EXTRA
19486 For backward compatibility, if both the positive and the negative place
19487 holder is missing, the positive one (without the \"NO-\") will be
19488 assumed to be present at the end of the template.
19489 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19490 EXTRA is a string.
19491 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19492 (let (rpl (end ""))
19493 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19494 (setq rpl (if (or (match-end 1) (not def-pkg))
19495 "" (org-latex-packages-to-string def-pkg snippets-p t))
19496 tpl (replace-match rpl t t tpl))
19497 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19499 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19500 (setq rpl (if (or (match-end 1) (not pkg))
19501 "" (org-latex-packages-to-string pkg snippets-p t))
19502 tpl (replace-match rpl t t tpl))
19503 (if pkg (setq end
19504 (concat end "\n"
19505 (org-latex-packages-to-string pkg snippets-p)))))
19507 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19508 (setq rpl (if (or (match-end 1) (not extra))
19509 "" (concat extra "\n"))
19510 tpl (replace-match rpl t t tpl))
19511 (if (and extra (string-match "\\S-" extra))
19512 (setq end (concat end "\n" extra))))
19514 (if (string-match "\\S-" end)
19515 (concat tpl "\n" end)
19516 tpl)))
19518 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19519 "Turn an alist of packages into a string with the \\usepackage macros."
19520 (setq pkg (mapconcat (lambda(p)
19521 (cond
19522 ((stringp p) p)
19523 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19524 (format "%% Package %s omitted" (cadr p)))
19525 ((equal "" (car p))
19526 (format "\\usepackage{%s}" (cadr p)))
19528 (format "\\usepackage[%s]{%s}"
19529 (car p) (cadr p)))))
19531 "\n"))
19532 (if newline (concat pkg "\n") pkg))
19534 (defun org-dvipng-color (attr)
19535 "Return a RGB color specification for dvipng."
19536 (apply 'format "rgb %s %s %s"
19537 (mapcar 'org-normalize-color
19538 (if (featurep 'xemacs)
19539 (color-rgb-components
19540 (face-property 'default
19541 (cond ((eq attr :foreground) 'foreground)
19542 ((eq attr :background) 'background))))
19543 (color-values (face-attribute 'default attr nil))))))
19545 (defun org-dvipng-color-format (color-name)
19546 "Convert COLOR-NAME to a RGB color value for dvipng."
19547 (apply 'format "rgb %s %s %s"
19548 (mapcar 'org-normalize-color
19549 (color-values color-name))))
19551 (defun org-latex-color (attr)
19552 "Return a RGB color for the LaTeX color package."
19553 (apply 'format "%s,%s,%s"
19554 (mapcar 'org-normalize-color
19555 (if (featurep 'xemacs)
19556 (color-rgb-components
19557 (face-property 'default
19558 (cond ((eq attr :foreground) 'foreground)
19559 ((eq attr :background) 'background))))
19560 (color-values (face-attribute 'default attr nil))))))
19562 (defun org-latex-color-format (color-name)
19563 "Convert COLOR-NAME to a RGB color value."
19564 (apply 'format "%s,%s,%s"
19565 (mapcar 'org-normalize-color
19566 (color-values color-name))))
19568 (defun org-normalize-color (value)
19569 "Return string to be used as color value for an RGB component."
19570 (format "%g" (/ value 65535.0)))
19574 ;; Image display
19576 (defvar org-inline-image-overlays nil)
19577 (make-variable-buffer-local 'org-inline-image-overlays)
19579 (defun org-toggle-inline-images (&optional include-linked)
19580 "Toggle the display of inline images.
19581 INCLUDE-LINKED is passed to `org-display-inline-images'."
19582 (interactive "P")
19583 (if org-inline-image-overlays
19584 (progn
19585 (org-remove-inline-images)
19586 (when (org-called-interactively-p 'interactive)
19587 (message "Inline image display turned off")))
19588 (org-display-inline-images include-linked)
19589 (when (org-called-interactively-p 'interactive)
19590 (message (if org-inline-image-overlays
19591 (format "%d images displayed inline"
19592 (length org-inline-image-overlays))
19593 "No images to display inline")))))
19595 (defun org-redisplay-inline-images ()
19596 "Refresh the display of inline images."
19597 (interactive)
19598 (if (not org-inline-image-overlays)
19599 (org-toggle-inline-images)
19600 (org-toggle-inline-images)
19601 (org-toggle-inline-images)))
19603 (defun org-display-inline-images (&optional include-linked refresh beg end)
19604 "Display inline images.
19606 An inline image is a link which follows either of these
19607 conventions:
19609 1. Its path is a file with an extension matching return value
19610 from `image-file-name-regexp' and it has no contents.
19612 2. Its description consists in a single link of the previous
19613 type.
19615 When optional argument INCLUDE-LINKED is non-nil, also links with
19616 a text description part will be inlined. This can be nice for
19617 a quick look at those images, but it does not reflect what
19618 exported files will look like.
19620 When optional argument REFRESH is non-nil, refresh existing
19621 images between BEG and END. This will create new image displays
19622 only if necessary. BEG and END default to the buffer
19623 boundaries."
19624 (interactive "P")
19625 (when (display-graphic-p)
19626 (unless refresh
19627 (org-remove-inline-images)
19628 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19629 (org-with-wide-buffer
19630 (goto-char (or beg (point-min)))
19631 (let ((case-fold-search t)
19632 (file-extension-re (org-image-file-name-regexp)))
19633 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19634 (let ((link (save-match-data (org-element-context))))
19635 ;; Check if we're at an inline image.
19636 (when (and (equal (org-element-property :type link) "file")
19637 (or include-linked
19638 (not (org-element-property :contents-begin link)))
19639 (let ((parent (org-element-property :parent link)))
19640 (or (not (eq (org-element-type parent) 'link))
19641 (not (cdr (org-element-contents parent)))))
19642 (org-string-match-p file-extension-re
19643 (org-element-property :path link)))
19644 (let ((file (expand-file-name
19645 (org-link-unescape
19646 (org-element-property :path link)))))
19647 (when (file-exists-p file)
19648 (let ((width
19649 ;; Apply `org-image-actual-width' specifications.
19650 (cond
19651 ((not (image-type-available-p 'imagemagick)) nil)
19652 ((eq org-image-actual-width t) nil)
19653 ((listp org-image-actual-width)
19655 ;; First try to find a width among
19656 ;; attributes associated to the paragraph
19657 ;; containing link.
19658 (let ((paragraph
19659 (let ((e link))
19660 (while (and (setq e (org-element-property
19661 :parent e))
19662 (not (eq (org-element-type e)
19663 'paragraph))))
19664 e)))
19665 (when paragraph
19666 (save-excursion
19667 (goto-char (org-element-property :begin paragraph))
19668 (when
19669 (re-search-forward
19670 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19671 (org-element-property
19672 :post-affiliated paragraph)
19674 (string-to-number (match-string 1))))))
19675 ;; Otherwise, fall-back to provided number.
19676 (car org-image-actual-width)))
19677 ((numberp org-image-actual-width)
19678 org-image-actual-width)))
19679 (old (get-char-property-and-overlay
19680 (org-element-property :begin link)
19681 'org-image-overlay)))
19682 (if (and (car-safe old) refresh)
19683 (image-refresh (overlay-get (cdr old) 'display))
19684 (let ((image (create-image file
19685 (and width 'imagemagick)
19687 :width width)))
19688 (when image
19689 (let* ((link
19690 ;; If inline image is the description
19691 ;; of another link, be sure to
19692 ;; consider the latter as the one to
19693 ;; apply the overlay on.
19694 (let ((parent
19695 (org-element-property :parent link)))
19696 (if (eq (org-element-type parent) 'link)
19697 parent
19698 link)))
19699 (ov (make-overlay
19700 (org-element-property :begin link)
19701 (progn
19702 (goto-char
19703 (org-element-property :end link))
19704 (skip-chars-backward " \t")
19705 (point)))))
19706 (overlay-put ov 'display image)
19707 (overlay-put ov 'face 'default)
19708 (overlay-put ov 'org-image-overlay t)
19709 (overlay-put
19710 ov 'modification-hooks
19711 (list 'org-display-inline-remove-overlay))
19712 (push ov org-inline-image-overlays)))))))))))))))
19714 (define-obsolete-function-alias
19715 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19717 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19718 "Remove inline-display overlay if a corresponding region is modified."
19719 (let ((inhibit-modification-hooks t))
19720 (when (and ov after)
19721 (delete ov org-inline-image-overlays)
19722 (delete-overlay ov))))
19724 (defun org-remove-inline-images ()
19725 "Remove inline display of images."
19726 (interactive)
19727 (mapc 'delete-overlay org-inline-image-overlays)
19728 (setq org-inline-image-overlays nil))
19730 ;;;; Key bindings
19732 ;; Outline functions from `outline-mode-prefix-map'
19733 ;; that can be remapped in Org:
19734 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19735 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19736 (define-key org-mode-map [remap outline-forward-same-level]
19737 'org-forward-heading-same-level)
19738 (define-key org-mode-map [remap outline-backward-same-level]
19739 'org-backward-heading-same-level)
19740 (define-key org-mode-map [remap outline-show-branches]
19741 'org-kill-note-or-show-branches)
19742 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19743 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19744 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19745 (define-key org-mode-map [remap outline-next-visible-heading]
19746 'org-next-visible-heading)
19747 (define-key org-mode-map [remap outline-previous-visible-heading]
19748 'org-previous-visible-heading)
19749 (define-key org-mode-map [remap show-children] 'org-show-children)
19751 ;; Outline functions from `outline-mode-prefix-map' that can not
19752 ;; be remapped in Org:
19754 ;; - the column "key binding" shows whether the Outline function is still
19755 ;; available in Org mode on the same key that it has been bound to in
19756 ;; Outline mode:
19757 ;; - "overridden": key used for a different functionality in Org mode
19758 ;; - else: key still bound to the same Outline function in Org mode
19760 ;; | Outline function | key binding | Org replacement |
19761 ;; |------------------------------------+-------------+--------------------------|
19762 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19763 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19764 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19765 ;; | `show-entry' | overridden | no replacement |
19766 ;; | `show-branches' | `C-c C-k' | still same function |
19767 ;; | `show-subtree' | overridden | visibility cycling |
19768 ;; | `show-all' | overridden | no replacement |
19769 ;; | `hide-subtree' | overridden | visibility cycling |
19770 ;; | `hide-body' | overridden | no replacement |
19771 ;; | `hide-entry' | overridden | visibility cycling |
19772 ;; | `hide-leaves' | overridden | no replacement |
19773 ;; | `hide-sublevels' | overridden | no replacement |
19774 ;; | `hide-other' | overridden | no replacement |
19776 ;; Make `C-c C-x' a prefix key
19777 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19779 ;; TAB key with modifiers
19780 (org-defkey org-mode-map "\C-i" 'org-cycle)
19781 (org-defkey org-mode-map [(tab)] 'org-cycle)
19782 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19783 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19784 ;; The following line is necessary under Suse GNU/Linux
19785 (unless (featurep 'xemacs)
19786 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19787 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19788 (define-key org-mode-map [backtab] 'org-shifttab)
19790 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19791 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19792 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19794 ;; Cursor keys with modifiers
19795 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19796 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19797 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19798 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19800 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19801 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19802 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19803 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19804 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19805 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19807 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19808 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19809 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19810 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19812 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19813 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19814 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19815 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19817 ;; Babel keys
19818 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19819 (mapc (lambda (pair)
19820 (define-key org-babel-map (car pair) (cdr pair)))
19821 org-babel-key-bindings)
19823 ;;; Extra keys for tty access.
19824 ;; We only set them when really needed because otherwise the
19825 ;; menus don't show the simple keys
19827 (when (or org-use-extra-keys
19828 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19829 (not window-system))
19830 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19831 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19832 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19833 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19834 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19835 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19836 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19837 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19838 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19839 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19840 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19841 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19842 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19843 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19844 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19845 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19846 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19847 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19848 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19849 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19850 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19851 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19852 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19853 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19854 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19855 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19856 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19857 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19859 ;; All the other keys
19861 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19862 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19863 (if (boundp 'narrow-map)
19864 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19865 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19866 (if (boundp 'narrow-map)
19867 (org-defkey narrow-map "b" 'org-narrow-to-block)
19868 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19869 (if (boundp 'narrow-map)
19870 (org-defkey narrow-map "e" 'org-narrow-to-element)
19871 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19872 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19873 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19874 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19875 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19876 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19877 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19878 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19879 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19880 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19881 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19882 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19883 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19884 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19885 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19886 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19887 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19888 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19889 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19890 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19891 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19892 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19893 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19894 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19895 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19896 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19897 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19898 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19899 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19900 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19901 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19902 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19903 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19904 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19905 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19906 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19907 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19908 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19909 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19910 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19911 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19912 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19913 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19914 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19915 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19916 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19917 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19918 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19919 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19920 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19921 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19922 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19923 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19924 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19925 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19926 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19927 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19928 (org-defkey org-mode-map "\C-c^" 'org-sort)
19929 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19930 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19931 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19932 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19933 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19934 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19935 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19936 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19937 (org-defkey org-mode-map "\C-m" 'org-return)
19938 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19939 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19940 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19941 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19942 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19943 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19944 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19945 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19946 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19947 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19948 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19949 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19950 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19951 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19952 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19953 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19954 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19955 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19956 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19957 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19958 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19959 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19960 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19961 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19962 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19964 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19965 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19966 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19968 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19969 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19970 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19971 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19972 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19973 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19974 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19975 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19976 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19977 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19978 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19979 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19980 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19981 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19982 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19983 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19984 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19985 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19986 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19987 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19988 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19989 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19991 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19992 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19993 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19994 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19995 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19997 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19999 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
20001 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
20002 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
20004 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20007 (when (featurep 'xemacs)
20008 (org-defkey org-mode-map 'button3 'popup-mode-menu))
20011 (defconst org-speed-commands-default
20013 ("Outline Navigation")
20014 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20015 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20016 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20017 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20018 ("F" . org-next-block)
20019 ("B" . org-previous-block)
20020 ("u" . (org-speed-move-safe 'outline-up-heading))
20021 ("j" . org-goto)
20022 ("g" . (org-refile t))
20023 ("Outline Visibility")
20024 ("c" . org-cycle)
20025 ("C" . org-shifttab)
20026 (" " . org-display-outline-path)
20027 ("s" . org-narrow-to-subtree)
20028 ("=" . org-columns)
20029 ("Outline Structure Editing")
20030 ("U" . org-metaup)
20031 ("D" . org-metadown)
20032 ("r" . org-metaright)
20033 ("l" . org-metaleft)
20034 ("R" . org-shiftmetaright)
20035 ("L" . org-shiftmetaleft)
20036 ("i" . (progn (forward-char 1) (call-interactively
20037 'org-insert-heading-respect-content)))
20038 ("^" . org-sort)
20039 ("w" . org-refile)
20040 ("a" . org-archive-subtree-default-with-confirmation)
20041 ("@" . org-mark-subtree)
20042 ("#" . org-toggle-comment)
20043 ("Clock Commands")
20044 ("I" . org-clock-in)
20045 ("O" . org-clock-out)
20046 ("Meta Data Editing")
20047 ("t" . org-todo)
20048 ("," . (org-priority))
20049 ("0" . (org-priority ?\ ))
20050 ("1" . (org-priority ?A))
20051 ("2" . (org-priority ?B))
20052 ("3" . (org-priority ?C))
20053 (":" . org-set-tags-command)
20054 ("e" . org-set-effort)
20055 ("E" . org-inc-effort)
20056 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20057 (org-entry-put (point) "APPT_WARNTIME" m)))
20058 ("Agenda Views etc")
20059 ("v" . org-agenda)
20060 ("/" . org-sparse-tree)
20061 ("Misc")
20062 ("o" . org-open-at-point)
20063 ("?" . org-speed-command-help)
20064 ("<" . (org-agenda-set-restriction-lock 'subtree))
20065 (">" . (org-agenda-remove-restriction-lock))
20067 "The default speed commands.")
20069 (defun org-print-speed-command (e)
20070 (if (> (length (car e)) 1)
20071 (progn
20072 (princ "\n")
20073 (princ (car e))
20074 (princ "\n")
20075 (princ (make-string (length (car e)) ?-))
20076 (princ "\n"))
20077 (princ (car e))
20078 (princ " ")
20079 (if (symbolp (cdr e))
20080 (princ (symbol-name (cdr e)))
20081 (prin1 (cdr e)))
20082 (princ "\n")))
20084 (defun org-speed-command-help ()
20085 "Show the available speed commands."
20086 (interactive)
20087 (if (not org-use-speed-commands)
20088 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20089 (with-output-to-temp-buffer "*Help*"
20090 (princ "User-defined Speed commands\n===========================\n")
20091 (mapc 'org-print-speed-command org-speed-commands-user)
20092 (princ "\n")
20093 (princ "Built-in Speed commands\n=======================\n")
20094 (mapc 'org-print-speed-command org-speed-commands-default))
20095 (with-current-buffer "*Help*"
20096 (setq truncate-lines t))))
20098 (defun org-speed-move-safe (cmd)
20099 "Execute CMD, but make sure that the cursor always ends up in a headline.
20100 If not, return to the original position and throw an error."
20101 (interactive)
20102 (let ((pos (point)))
20103 (call-interactively cmd)
20104 (unless (and (bolp) (org-at-heading-p))
20105 (goto-char pos)
20106 (error "Boundary reached while executing %s" cmd))))
20108 (defvar org-self-insert-command-undo-counter 0)
20110 (defvar org-table-auto-blank-field) ; defined in org-table.el
20111 (defvar org-speed-command nil)
20113 (define-obsolete-function-alias
20114 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
20116 (defun org-speed-command-activate (keys)
20117 "Hook for activating single-letter speed commands.
20118 `org-speed-commands-default' specifies a minimal command set.
20119 Use `org-speed-commands-user' for further customization."
20120 (when (or (and (bolp) (looking-at org-outline-regexp))
20121 (and (functionp org-use-speed-commands)
20122 (funcall org-use-speed-commands)))
20123 (cdr (assoc keys (append org-speed-commands-user
20124 org-speed-commands-default)))))
20126 (define-obsolete-function-alias
20127 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
20129 (defun org-babel-speed-command-activate (keys)
20130 "Hook for activating single-letter code block commands."
20131 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20132 (cdr (assoc keys org-babel-key-bindings))))
20134 (defcustom org-speed-command-hook
20135 '(org-speed-command-default-hook org-babel-speed-command-hook)
20136 "Hook for activating speed commands at strategic locations.
20137 Hook functions are called in sequence until a valid handler is
20138 found.
20140 Each hook takes a single argument, a user-pressed command key
20141 which is also a `self-insert-command' from the global map.
20143 Within the hook, examine the cursor position and the command key
20144 and return nil or a valid handler as appropriate. Handler could
20145 be one of an interactive command, a function, or a form.
20147 Set `org-use-speed-commands' to non-nil value to enable this
20148 hook. The default setting is `org-speed-command-activate'."
20149 :group 'org-structure
20150 :version "24.1"
20151 :type 'hook)
20153 (defun org-self-insert-command (N)
20154 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20155 If the cursor is in a table looking at whitespace, the whitespace is
20156 overwritten, and the table is not marked as requiring realignment."
20157 (interactive "p")
20158 (org-check-before-invisible-edit 'insert)
20159 (cond
20160 ((and org-use-speed-commands
20161 (let ((kv (this-command-keys-vector)))
20162 (setq org-speed-command
20163 (run-hook-with-args-until-success
20164 'org-speed-command-hook
20165 (make-string 1 (aref kv (1- (length kv))))))))
20166 (cond
20167 ((commandp org-speed-command)
20168 (setq this-command org-speed-command)
20169 (call-interactively org-speed-command))
20170 ((functionp org-speed-command)
20171 (funcall org-speed-command))
20172 ((and org-speed-command (listp org-speed-command))
20173 (eval org-speed-command))
20174 (t (let (org-use-speed-commands)
20175 (call-interactively 'org-self-insert-command)))))
20176 ((and
20177 (org-table-p)
20178 (progn
20179 ;; check if we blank the field, and if that triggers align
20180 (and (featurep 'org-table) org-table-auto-blank-field
20181 (memq last-command
20182 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20183 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
20184 ;; got extra space, this field does not determine column width
20185 (let (org-table-may-need-update) (org-table-blank-field))
20186 ;; no extra space, this field may determine column width
20187 (org-table-blank-field)))
20189 (eq N 1)
20190 (looking-at "[^|\n]* |"))
20191 (let (org-table-may-need-update)
20192 (goto-char (1- (match-end 0)))
20193 (backward-delete-char 1)
20194 (goto-char (match-beginning 0))
20195 (self-insert-command N)))
20197 (setq org-table-may-need-update t)
20198 (self-insert-command N)
20199 (org-fix-tags-on-the-fly)
20200 (if org-self-insert-cluster-for-undo
20201 (if (not (eq last-command 'org-self-insert-command))
20202 (setq org-self-insert-command-undo-counter 1)
20203 (if (>= org-self-insert-command-undo-counter 20)
20204 (setq org-self-insert-command-undo-counter 1)
20205 (and (> org-self-insert-command-undo-counter 0)
20206 buffer-undo-list (listp buffer-undo-list)
20207 (not (cadr buffer-undo-list)) ; remove nil entry
20208 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20209 (setq org-self-insert-command-undo-counter
20210 (1+ org-self-insert-command-undo-counter))))))))
20212 (defun org-check-before-invisible-edit (kind)
20213 "Check is editing if kind KIND would be dangerous with invisible text around.
20214 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20215 ;; First, try to get out of here as quickly as possible, to reduce overhead
20216 (if (and org-catch-invisible-edits
20217 (or (not (boundp 'visible-mode)) (not visible-mode))
20218 (or (get-char-property (point) 'invisible)
20219 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20220 ;; OK, we need to take a closer look
20221 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20222 (invisible-before-point (if (bobp) nil (get-char-property
20223 (1- (point)) 'invisible)))
20224 (border-and-ok-direction
20226 ;; Check if we are acting predictably before invisible text
20227 (and invisible-at-point (not invisible-before-point)
20228 (memq kind '(insert delete-backward)))
20229 ;; Check if we are acting predictably after invisible text
20230 ;; This works not well, and I have turned it off. It seems
20231 ;; better to always show and stop after invisible text.
20232 ;; (and (not invisible-at-point) invisible-before-point
20233 ;; (memq kind '(insert delete)))
20235 (when (or (memq invisible-at-point '(outline org-hide-block t))
20236 (memq invisible-before-point '(outline org-hide-block t)))
20237 (if (eq org-catch-invisible-edits 'error)
20238 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20239 (if (and org-custom-properties-overlays
20240 (y-or-n-p "Display invisible properties in this buffer? "))
20241 (org-toggle-custom-properties-visibility)
20242 ;; Make the area visible
20243 (save-excursion
20244 (if invisible-before-point
20245 (goto-char (previous-single-char-property-change
20246 (point) 'invisible)))
20247 (outline-show-subtree))
20248 (cond
20249 ((eq org-catch-invisible-edits 'show)
20250 ;; That's it, we do the edit after showing
20251 (message
20252 "Unfolding invisible region around point before editing")
20253 (sit-for 1))
20254 ((and (eq org-catch-invisible-edits 'smart)
20255 border-and-ok-direction)
20256 (message "Unfolding invisible region around point before editing"))
20258 ;; Don't do the edit, make the user repeat it in full visibility
20259 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20261 (defun org-fix-tags-on-the-fly ()
20262 (when (and (equal (char-after (point-at-bol)) ?*)
20263 (org-at-heading-p))
20264 (org-align-tags-here org-tags-column)))
20266 (defun org-delete-backward-char (N)
20267 "Like `delete-backward-char', insert whitespace at field end in tables.
20268 When deleting backwards, in tables this function will insert whitespace in
20269 front of the next \"|\" separator, to keep the table aligned. The table will
20270 still be marked for re-alignment if the field did fill the entire column,
20271 because, in this case the deletion might narrow the column."
20272 (interactive "p")
20273 (save-match-data
20274 (org-check-before-invisible-edit 'delete-backward)
20275 (if (and (org-table-p)
20276 (eq N 1)
20277 (string-match "|" (buffer-substring (point-at-bol) (point)))
20278 (looking-at ".*?|"))
20279 (let ((pos (point))
20280 (noalign (looking-at "[^|\n\r]* |"))
20281 (c org-table-may-need-update))
20282 (backward-delete-char N)
20283 (if (not overwrite-mode)
20284 (progn
20285 (skip-chars-forward "^|")
20286 (insert " ")
20287 (goto-char (1- pos))))
20288 ;; noalign: if there were two spaces at the end, this field
20289 ;; does not determine the width of the column.
20290 (if noalign (setq org-table-may-need-update c)))
20291 (backward-delete-char N)
20292 (org-fix-tags-on-the-fly))))
20294 (defun org-delete-char (N)
20295 "Like `delete-char', but insert whitespace at field end in tables.
20296 When deleting characters, in tables this function will insert whitespace in
20297 front of the next \"|\" separator, to keep the table aligned. The table will
20298 still be marked for re-alignment if the field did fill the entire column,
20299 because, in this case the deletion might narrow the column."
20300 (interactive "p")
20301 (save-match-data
20302 (org-check-before-invisible-edit 'delete)
20303 (if (and (org-table-p)
20304 (not (bolp))
20305 (not (= (char-after) ?|))
20306 (eq N 1))
20307 (if (looking-at ".*?|")
20308 (let ((pos (point))
20309 (noalign (looking-at "[^|\n\r]* |"))
20310 (c org-table-may-need-update))
20311 (replace-match
20312 (concat (substring (match-string 0) 1 -1) " |") nil t)
20313 (goto-char pos)
20314 ;; noalign: if there were two spaces at the end, this field
20315 ;; does not determine the width of the column.
20316 (if noalign (setq org-table-may-need-update c)))
20317 (delete-char N))
20318 (delete-char N)
20319 (org-fix-tags-on-the-fly))))
20321 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20322 (put 'org-self-insert-command 'delete-selection
20323 (lambda ()
20324 (not (run-hook-with-args-until-success
20325 'self-insert-uses-region-functions))))
20326 (put 'orgtbl-self-insert-command 'delete-selection
20327 (lambda ()
20328 (not (run-hook-with-args-until-success
20329 'self-insert-uses-region-functions))))
20330 (put 'org-delete-char 'delete-selection 'supersede)
20331 (put 'org-delete-backward-char 'delete-selection 'supersede)
20332 (put 'org-yank 'delete-selection 'yank)
20334 ;; Make `flyspell-mode' delay after some commands
20335 (put 'org-self-insert-command 'flyspell-delayed t)
20336 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20337 (put 'org-delete-char 'flyspell-delayed t)
20338 (put 'org-delete-backward-char 'flyspell-delayed t)
20340 ;; Make pabbrev-mode expand after org-mode commands
20341 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20342 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20344 (defun org-remap (map &rest commands)
20345 "In MAP, remap the functions given in COMMANDS.
20346 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20347 (let (new old)
20348 (while commands
20349 (setq old (pop commands) new (pop commands))
20350 (if (fboundp 'command-remapping)
20351 (org-defkey map (vector 'remap old) new)
20352 (substitute-key-definition old new map global-map)))))
20354 (defun org-transpose-words ()
20355 "Transpose words for Org.
20356 This uses the `org-mode-transpose-word-syntax-table' syntax
20357 table, which interprets characters in `org-emphasis-alist' as
20358 word constituents."
20359 (interactive)
20360 (with-syntax-table org-mode-transpose-word-syntax-table
20361 (call-interactively 'transpose-words)))
20362 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20364 (when (eq org-enable-table-editor 'optimized)
20365 ;; If the user wants maximum table support, we need to hijack
20366 ;; some standard editing functions
20367 (org-remap org-mode-map
20368 'self-insert-command 'org-self-insert-command
20369 'delete-char 'org-delete-char
20370 'delete-backward-char 'org-delete-backward-char)
20371 (org-defkey org-mode-map "|" 'org-force-self-insert))
20373 (defvar org-ctrl-c-ctrl-c-hook nil
20374 "Hook for functions attaching themselves to `C-c C-c'.
20376 This can be used to add additional functionality to the C-c C-c
20377 key which executes context-dependent commands. This hook is run
20378 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20379 run after the last test.
20381 Each function will be called with no arguments. The function
20382 must check if the context is appropriate for it to act. If yes,
20383 it should do its thing and then return a non-nil value. If the
20384 context is wrong, just do nothing and return nil.")
20386 (defvar org-ctrl-c-ctrl-c-final-hook nil
20387 "Hook for functions attaching themselves to `C-c C-c'.
20389 This can be used to add additional functionality to the C-c C-c
20390 key which executes context-dependent commands. This hook is run
20391 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20392 before the first test.
20394 Each function will be called with no arguments. The function
20395 must check if the context is appropriate for it to act. If yes,
20396 it should do its thing and then return a non-nil value. If the
20397 context is wrong, just do nothing and return nil.")
20399 (defvar org-tab-first-hook nil
20400 "Hook for functions to attach themselves to TAB.
20401 See `org-ctrl-c-ctrl-c-hook' for more information.
20402 This hook runs as the first action when TAB is pressed, even before
20403 `org-cycle' messes around with the `outline-regexp' to cater for
20404 inline tasks and plain list item folding.
20405 If any function in this hook returns t, any other actions that
20406 would have been caused by TAB (such as table field motion or visibility
20407 cycling) will not occur.")
20409 (defvar org-tab-after-check-for-table-hook nil
20410 "Hook for functions to attach themselves to TAB.
20411 See `org-ctrl-c-ctrl-c-hook' for more information.
20412 This hook runs after it has been established that the cursor is not in a
20413 table, but before checking if the cursor is in a headline or if global cycling
20414 should be done.
20415 If any function in this hook returns t, not other actions like visibility
20416 cycling will be done.")
20418 (defvar org-tab-after-check-for-cycling-hook nil
20419 "Hook for functions to attach themselves to TAB.
20420 See `org-ctrl-c-ctrl-c-hook' for more information.
20421 This hook runs after it has been established that not table field motion and
20422 not visibility should be done because of current context. This is probably
20423 the place where a package like yasnippets can hook in.")
20425 (defvar org-tab-before-tab-emulation-hook nil
20426 "Hook for functions to attach themselves to TAB.
20427 See `org-ctrl-c-ctrl-c-hook' for more information.
20428 This hook runs after every other options for TAB have been exhausted, but
20429 before indentation and \t insertion takes place.")
20431 (defvar org-metaleft-hook nil
20432 "Hook for functions attaching themselves to `M-left'.
20433 See `org-ctrl-c-ctrl-c-hook' for more information.")
20434 (defvar org-metaright-hook nil
20435 "Hook for functions attaching themselves to `M-right'.
20436 See `org-ctrl-c-ctrl-c-hook' for more information.")
20437 (defvar org-metaup-hook nil
20438 "Hook for functions attaching themselves to `M-up'.
20439 See `org-ctrl-c-ctrl-c-hook' for more information.")
20440 (defvar org-metadown-hook nil
20441 "Hook for functions attaching themselves to `M-down'.
20442 See `org-ctrl-c-ctrl-c-hook' for more information.")
20443 (defvar org-shiftmetaleft-hook nil
20444 "Hook for functions attaching themselves to `M-S-left'.
20445 See `org-ctrl-c-ctrl-c-hook' for more information.")
20446 (defvar org-shiftmetaright-hook nil
20447 "Hook for functions attaching themselves to `M-S-right'.
20448 See `org-ctrl-c-ctrl-c-hook' for more information.")
20449 (defvar org-shiftmetaup-hook nil
20450 "Hook for functions attaching themselves to `M-S-up'.
20451 See `org-ctrl-c-ctrl-c-hook' for more information.")
20452 (defvar org-shiftmetadown-hook nil
20453 "Hook for functions attaching themselves to `M-S-down'.
20454 See `org-ctrl-c-ctrl-c-hook' for more information.")
20455 (defvar org-metareturn-hook nil
20456 "Hook for functions attaching themselves to `M-RET'.
20457 See `org-ctrl-c-ctrl-c-hook' for more information.")
20458 (defvar org-shiftup-hook nil
20459 "Hook for functions attaching themselves to `S-up'.
20460 See `org-ctrl-c-ctrl-c-hook' for more information.")
20461 (defvar org-shiftup-final-hook nil
20462 "Hook for functions attaching themselves to `S-up'.
20463 This one runs after all other options except shift-select have been excluded.
20464 See `org-ctrl-c-ctrl-c-hook' for more information.")
20465 (defvar org-shiftdown-hook nil
20466 "Hook for functions attaching themselves to `S-down'.
20467 See `org-ctrl-c-ctrl-c-hook' for more information.")
20468 (defvar org-shiftdown-final-hook nil
20469 "Hook for functions attaching themselves to `S-down'.
20470 This one runs after all other options except shift-select have been excluded.
20471 See `org-ctrl-c-ctrl-c-hook' for more information.")
20472 (defvar org-shiftleft-hook nil
20473 "Hook for functions attaching themselves to `S-left'.
20474 See `org-ctrl-c-ctrl-c-hook' for more information.")
20475 (defvar org-shiftleft-final-hook nil
20476 "Hook for functions attaching themselves to `S-left'.
20477 This one runs after all other options except shift-select have been excluded.
20478 See `org-ctrl-c-ctrl-c-hook' for more information.")
20479 (defvar org-shiftright-hook nil
20480 "Hook for functions attaching themselves to `S-right'.
20481 See `org-ctrl-c-ctrl-c-hook' for more information.")
20482 (defvar org-shiftright-final-hook nil
20483 "Hook for functions attaching themselves to `S-right'.
20484 This one runs after all other options except shift-select have been excluded.
20485 See `org-ctrl-c-ctrl-c-hook' for more information.")
20487 (defun org-modifier-cursor-error ()
20488 "Throw an error, a modified cursor command was applied in wrong context."
20489 (user-error "This command is active in special context like tables, headlines or items"))
20491 (defun org-shiftselect-error ()
20492 "Throw an error because Shift-Cursor command was applied in wrong context."
20493 (if (and (boundp 'shift-select-mode) shift-select-mode)
20494 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20495 (user-error "This command works only in special context like headlines or timestamps")))
20497 (defun org-call-for-shift-select (cmd)
20498 (let ((this-command-keys-shift-translated t))
20499 (call-interactively cmd)))
20501 (defun org-shifttab (&optional arg)
20502 "Global visibility cycling or move to previous table field.
20503 Call `org-table-previous-field' within a table.
20504 When ARG is nil, cycle globally through visibility states.
20505 When ARG is a numeric prefix, show contents of this level."
20506 (interactive "P")
20507 (cond
20508 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20509 ((integerp arg)
20510 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20511 (message "Content view to level: %d" arg)
20512 (org-content (prefix-numeric-value arg2))
20513 (org-cycle-show-empty-lines t)
20514 (setq org-cycle-global-status 'overview)))
20515 (t (call-interactively 'org-global-cycle))))
20517 (defun org-shiftmetaleft ()
20518 "Promote subtree or delete table column.
20519 Calls `org-promote-subtree', `org-outdent-item-tree', or
20520 `org-table-delete-column', depending on context. See the
20521 individual commands for more information."
20522 (interactive)
20523 (cond
20524 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20525 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20526 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20527 ((if (not (org-region-active-p)) (org-at-item-p)
20528 (save-excursion (goto-char (region-beginning))
20529 (org-at-item-p)))
20530 (call-interactively 'org-outdent-item-tree))
20531 (t (org-modifier-cursor-error))))
20533 (defun org-shiftmetaright ()
20534 "Demote subtree or insert table column.
20535 Calls `org-demote-subtree', `org-indent-item-tree', or
20536 `org-table-insert-column', depending on context. See the
20537 individual commands for more information."
20538 (interactive)
20539 (cond
20540 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20541 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20542 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20543 ((if (not (org-region-active-p)) (org-at-item-p)
20544 (save-excursion (goto-char (region-beginning))
20545 (org-at-item-p)))
20546 (call-interactively 'org-indent-item-tree))
20547 (t (org-modifier-cursor-error))))
20549 (defun org-shiftmetaup (&optional arg)
20550 "Drag the line at point up.
20551 In a table, kill the current row.
20552 On a clock timestamp, update the value of the timestamp like `S-<up>'
20553 but also adjust the previous clocked item in the clock history.
20554 Everywhere else, drag the line at point up."
20555 (interactive "P")
20556 (cond
20557 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20558 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20559 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20560 (call-interactively 'org-timestamp-up)))
20561 (t (call-interactively 'org-drag-line-backward))))
20563 (defun org-shiftmetadown (&optional arg)
20564 "Drag the line at point down.
20565 In a table, insert an empty row at the current line.
20566 On a clock timestamp, update the value of the timestamp like `S-<down>'
20567 but also adjust the previous clocked item in the clock history.
20568 Everywhere else, drag the line at point down."
20569 (interactive "P")
20570 (cond
20571 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20572 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20573 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20574 (call-interactively 'org-timestamp-down)))
20575 (t (call-interactively 'org-drag-line-forward))))
20577 (defsubst org-hidden-tree-error ()
20578 (user-error
20579 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20581 (defun org-metaleft (&optional arg)
20582 "Promote heading, list item at point or move table column left.
20584 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20585 depending on context. With no specific context, calls the Emacs
20586 default `backward-word'. See the individual commands for more
20587 information.
20589 This function runs the hook `org-metaleft-hook' as a first step,
20590 and returns at first non-nil value."
20591 (interactive "P")
20592 (cond
20593 ((run-hook-with-args-until-success 'org-metaleft-hook))
20594 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20595 ((org-with-limited-levels
20596 (or (org-at-heading-p)
20597 (and (org-region-active-p)
20598 (save-excursion
20599 (goto-char (region-beginning))
20600 (org-at-heading-p)))))
20601 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20602 (call-interactively 'org-do-promote))
20603 ;; At an inline task.
20604 ((org-at-heading-p)
20605 (call-interactively 'org-inlinetask-promote))
20606 ((or (org-at-item-p)
20607 (and (org-region-active-p)
20608 (save-excursion
20609 (goto-char (region-beginning))
20610 (org-at-item-p))))
20611 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20612 (call-interactively 'org-outdent-item))
20613 (t (call-interactively 'backward-word))))
20615 (defun org-metaright (&optional arg)
20616 "Demote heading, list item at point or move table column right.
20618 In front of a drawer or a block keyword, indent it correctly.
20620 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20621 `org-indnet-drawer' or `org-indent-block' depending on context.
20622 With no specific context, calls the Emacs default `forward-word'.
20623 See the individual commands for more information.
20625 This function runs the hook `org-metaright-hook' as a first step,
20626 and returns at first non-nil value."
20627 (interactive "P")
20628 (cond
20629 ((run-hook-with-args-until-success 'org-metaright-hook))
20630 ((org-at-table-p) (call-interactively 'org-table-move-column))
20631 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20632 ((org-at-block-p) (call-interactively 'org-indent-block))
20633 ((org-with-limited-levels
20634 (or (org-at-heading-p)
20635 (and (org-region-active-p)
20636 (save-excursion
20637 (goto-char (region-beginning))
20638 (org-at-heading-p)))))
20639 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20640 (call-interactively 'org-do-demote))
20641 ;; At an inline task.
20642 ((org-at-heading-p)
20643 (call-interactively 'org-inlinetask-demote))
20644 ((or (org-at-item-p)
20645 (and (org-region-active-p)
20646 (save-excursion
20647 (goto-char (region-beginning))
20648 (org-at-item-p))))
20649 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20650 (call-interactively 'org-indent-item))
20651 (t (call-interactively 'forward-word))))
20653 (defun org-check-for-hidden (what)
20654 "Check if there are hidden headlines/items in the current visual line.
20655 WHAT can be either `headlines' or `items'. If the current line is
20656 an outline or item heading and it has a folded subtree below it,
20657 this function returns t, nil otherwise."
20658 (let ((re (cond
20659 ((eq what 'headlines) org-outline-regexp-bol)
20660 ((eq what 'items) (org-item-beginning-re))
20661 (t (error "This should not happen"))))
20662 beg end)
20663 (save-excursion
20664 (catch 'exit
20665 (unless (org-region-active-p)
20666 (setq beg (point-at-bol))
20667 (beginning-of-line 2)
20668 (while (and (not (eobp)) ;; this is like `next-line'
20669 (get-char-property (1- (point)) 'invisible))
20670 (beginning-of-line 2))
20671 (setq end (point))
20672 (goto-char beg)
20673 (goto-char (point-at-eol))
20674 (setq end (max end (point)))
20675 (while (re-search-forward re end t)
20676 (if (get-char-property (match-beginning 0) 'invisible)
20677 (throw 'exit t))))
20678 nil))))
20680 (defun org-metaup (&optional arg)
20681 "Move subtree up or move table row up.
20682 Calls `org-move-subtree-up' or `org-table-move-row' or
20683 `org-move-item-up', depending on context. See the individual commands
20684 for more information."
20685 (interactive "P")
20686 (cond
20687 ((run-hook-with-args-until-success 'org-metaup-hook))
20688 ((org-region-active-p)
20689 (let* ((a (min (region-beginning) (region-end)))
20690 (b (1- (max (region-beginning) (region-end))))
20691 (c (save-excursion (goto-char a)
20692 (move-beginning-of-line 0)))
20693 (d (save-excursion (goto-char a)
20694 (move-end-of-line 0) (point))))
20695 (transpose-regions a b c d)
20696 (goto-char c)))
20697 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20698 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20699 ((org-at-item-p) (call-interactively 'org-move-item-up))
20700 (t (org-drag-element-backward))))
20702 (defun org-metadown (&optional arg)
20703 "Move subtree down or move table row down.
20704 Calls `org-move-subtree-down' or `org-table-move-row' or
20705 `org-move-item-down', depending on context. See the individual
20706 commands for more information."
20707 (interactive "P")
20708 (cond
20709 ((run-hook-with-args-until-success 'org-metadown-hook))
20710 ((org-region-active-p)
20711 (let* ((a (min (region-beginning) (region-end)))
20712 (b (max (region-beginning) (region-end)))
20713 (c (save-excursion (goto-char b)
20714 (move-beginning-of-line 1)))
20715 (d (save-excursion (goto-char b)
20716 (move-end-of-line 1) (1+ (point)))))
20717 (transpose-regions a b c d)
20718 (goto-char d)))
20719 ((org-at-table-p) (call-interactively 'org-table-move-row))
20720 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20721 ((org-at-item-p) (call-interactively 'org-move-item-down))
20722 (t (org-drag-element-forward))))
20724 (defun org-shiftup (&optional arg)
20725 "Increase item in timestamp or increase priority of current headline.
20726 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20727 depending on context. See the individual commands for more information."
20728 (interactive "P")
20729 (cond
20730 ((run-hook-with-args-until-success 'org-shiftup-hook))
20731 ((and org-support-shift-select (org-region-active-p))
20732 (org-call-for-shift-select 'previous-line))
20733 ((org-at-timestamp-p t)
20734 (call-interactively (if org-edit-timestamp-down-means-later
20735 'org-timestamp-down 'org-timestamp-up)))
20736 ((and (not (eq org-support-shift-select 'always))
20737 org-enable-priority-commands
20738 (org-at-heading-p))
20739 (call-interactively 'org-priority-up))
20740 ((and (not org-support-shift-select) (org-at-item-p))
20741 (call-interactively 'org-previous-item))
20742 ((org-clocktable-try-shift 'up arg))
20743 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20744 (org-support-shift-select
20745 (org-call-for-shift-select 'previous-line))
20746 (t (org-shiftselect-error))))
20748 (defun org-shiftdown (&optional arg)
20749 "Decrease item in timestamp or decrease priority of current headline.
20750 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20751 depending on context. See the individual commands for more information."
20752 (interactive "P")
20753 (cond
20754 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20755 ((and org-support-shift-select (org-region-active-p))
20756 (org-call-for-shift-select 'next-line))
20757 ((org-at-timestamp-p t)
20758 (call-interactively (if org-edit-timestamp-down-means-later
20759 'org-timestamp-up 'org-timestamp-down)))
20760 ((and (not (eq org-support-shift-select 'always))
20761 org-enable-priority-commands
20762 (org-at-heading-p))
20763 (call-interactively 'org-priority-down))
20764 ((and (not org-support-shift-select) (org-at-item-p))
20765 (call-interactively 'org-next-item))
20766 ((org-clocktable-try-shift 'down arg))
20767 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20768 (org-support-shift-select
20769 (org-call-for-shift-select 'next-line))
20770 (t (org-shiftselect-error))))
20772 (defun org-shiftright (&optional arg)
20773 "Cycle the thing at point or in the current line, depending on context.
20774 Depending on context, this does one of the following:
20776 - switch a timestamp at point one day into the future
20777 - on a headline, switch to the next TODO keyword.
20778 - on an item, switch entire list to the next bullet type
20779 - on a property line, switch to the next allowed value
20780 - on a clocktable definition line, move time block into the future"
20781 (interactive "P")
20782 (cond
20783 ((run-hook-with-args-until-success 'org-shiftright-hook))
20784 ((and org-support-shift-select (org-region-active-p))
20785 (org-call-for-shift-select 'forward-char))
20786 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20787 ((and (not (eq org-support-shift-select 'always))
20788 (org-at-heading-p))
20789 (let ((org-inhibit-logging
20790 (not org-treat-S-cursor-todo-selection-as-state-change))
20791 (org-inhibit-blocking
20792 (not org-treat-S-cursor-todo-selection-as-state-change)))
20793 (org-call-with-arg 'org-todo 'right)))
20794 ((or (and org-support-shift-select
20795 (not (eq org-support-shift-select 'always))
20796 (org-at-item-bullet-p))
20797 (and (not org-support-shift-select) (org-at-item-p)))
20798 (org-call-with-arg 'org-cycle-list-bullet nil))
20799 ((and (not (eq org-support-shift-select 'always))
20800 (org-at-property-p))
20801 (call-interactively 'org-property-next-allowed-value))
20802 ((org-clocktable-try-shift 'right arg))
20803 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20804 (org-support-shift-select
20805 (org-call-for-shift-select 'forward-char))
20806 (t (org-shiftselect-error))))
20808 (defun org-shiftleft (&optional arg)
20809 "Cycle the thing at point or in the current line, depending on context.
20810 Depending on context, this does one of the following:
20812 - switch a timestamp at point one day into the past
20813 - on a headline, switch to the previous TODO keyword.
20814 - on an item, switch entire list to the previous bullet type
20815 - on a property line, switch to the previous allowed value
20816 - on a clocktable definition line, move time block into the past"
20817 (interactive "P")
20818 (cond
20819 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20820 ((and org-support-shift-select (org-region-active-p))
20821 (org-call-for-shift-select 'backward-char))
20822 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20823 ((and (not (eq org-support-shift-select 'always))
20824 (org-at-heading-p))
20825 (let ((org-inhibit-logging
20826 (not org-treat-S-cursor-todo-selection-as-state-change))
20827 (org-inhibit-blocking
20828 (not org-treat-S-cursor-todo-selection-as-state-change)))
20829 (org-call-with-arg 'org-todo 'left)))
20830 ((or (and org-support-shift-select
20831 (not (eq org-support-shift-select 'always))
20832 (org-at-item-bullet-p))
20833 (and (not org-support-shift-select) (org-at-item-p)))
20834 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20835 ((and (not (eq org-support-shift-select 'always))
20836 (org-at-property-p))
20837 (call-interactively 'org-property-previous-allowed-value))
20838 ((org-clocktable-try-shift 'left arg))
20839 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20840 (org-support-shift-select
20841 (org-call-for-shift-select 'backward-char))
20842 (t (org-shiftselect-error))))
20844 (defun org-shiftcontrolright ()
20845 "Switch to next TODO set."
20846 (interactive)
20847 (cond
20848 ((and org-support-shift-select (org-region-active-p))
20849 (org-call-for-shift-select 'forward-word))
20850 ((and (not (eq org-support-shift-select 'always))
20851 (org-at-heading-p))
20852 (org-call-with-arg 'org-todo 'nextset))
20853 (org-support-shift-select
20854 (org-call-for-shift-select 'forward-word))
20855 (t (org-shiftselect-error))))
20857 (defun org-shiftcontrolleft ()
20858 "Switch to previous TODO set."
20859 (interactive)
20860 (cond
20861 ((and org-support-shift-select (org-region-active-p))
20862 (org-call-for-shift-select 'backward-word))
20863 ((and (not (eq org-support-shift-select 'always))
20864 (org-at-heading-p))
20865 (org-call-with-arg 'org-todo 'previousset))
20866 (org-support-shift-select
20867 (org-call-for-shift-select 'backward-word))
20868 (t (org-shiftselect-error))))
20870 (defun org-shiftcontrolup (&optional n)
20871 "Change timestamps synchronously up in CLOCK log lines.
20872 Optional argument N tells to change by that many units."
20873 (interactive "P")
20874 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20875 (let (org-support-shift-select)
20876 (org-clock-timestamps-up n))
20877 (user-error "Not at a clock log")))
20879 (defun org-shiftcontroldown (&optional n)
20880 "Change timestamps synchronously down in CLOCK log lines.
20881 Optional argument N tells to change by that many units."
20882 (interactive "P")
20883 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20884 (let (org-support-shift-select)
20885 (org-clock-timestamps-down n))
20886 (user-error "Not at a clock log")))
20888 (defun org-increase-number-at-point (&optional inc)
20889 "Increment the number at point.
20890 With an optional prefix numeric argument INC, increment using
20891 this numeric value."
20892 (interactive "p")
20893 (if (not (number-at-point))
20894 (user-error "Not on a number")
20895 (unless inc (setq inc 1))
20896 (let ((pos (point))
20897 (beg (skip-chars-backward "-+^/*0-9eE."))
20898 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20899 (setq nap (buffer-substring-no-properties
20900 (+ pos beg) (+ pos beg end)))
20901 (delete-region (+ pos beg) (+ pos beg end))
20902 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20903 (when (org-at-table-p)
20904 (org-table-align)
20905 (org-table-end-of-field 1))))
20907 (defun org-decrease-number-at-point (&optional inc)
20908 "Decrement the number at point.
20909 With an optional prefix numeric argument INC, decrement using
20910 this numeric value."
20911 (interactive "p")
20912 (org-increase-number-at-point (- (or inc 1))))
20914 (defun org-ctrl-c-ret ()
20915 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20916 (interactive)
20917 (cond
20918 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20919 (t (call-interactively 'org-insert-heading))))
20921 (defun org-find-visible ()
20922 (let ((s (point)))
20923 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20924 (get-char-property s 'invisible)))
20926 (defun org-find-invisible ()
20927 (let ((s (point)))
20928 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20929 (not (get-char-property s 'invisible))))
20932 (defun org-copy-visible (beg end)
20933 "Copy the visible parts of the region."
20934 (interactive "r")
20935 (let (snippets s)
20936 (save-excursion
20937 (save-restriction
20938 (narrow-to-region beg end)
20939 (setq s (goto-char (point-min)))
20940 (while (not (= (point) (point-max)))
20941 (goto-char (org-find-invisible))
20942 (push (buffer-substring s (point)) snippets)
20943 (setq s (goto-char (org-find-visible))))))
20944 (kill-new (apply 'concat (nreverse snippets)))))
20946 (defun org-copy-special ()
20947 "Copy region in table or copy current subtree.
20948 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20949 See the individual commands for more information."
20950 (interactive)
20951 (call-interactively
20952 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20954 (defun org-cut-special ()
20955 "Cut region in table or cut current subtree.
20956 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20957 See the individual commands for more information."
20958 (interactive)
20959 (call-interactively
20960 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20962 (defun org-paste-special (arg)
20963 "Paste rectangular region into table, or past subtree relative to level.
20964 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20965 See the individual commands for more information."
20966 (interactive "P")
20967 (if (org-at-table-p)
20968 (org-table-paste-rectangle)
20969 (org-paste-subtree arg)))
20971 (defsubst org-in-fixed-width-region-p ()
20972 "Is point in a fixed-width region?"
20973 (save-match-data
20974 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20976 (defun org-edit-special (&optional arg)
20977 "Call a special editor for the element at point.
20978 When at a table, call the formula editor with `org-table-edit-formulas'.
20979 When in a source code block, call `org-edit-src-code'.
20980 When in a fixed-width region, call `org-edit-fixed-width-region'.
20981 When in an export block, call `org-edit-export-block'.
20982 When at an #+INCLUDE keyword, visit the included file.
20983 When at a footnote reference, call `org-edit-footnote-reference'
20984 On a link, call `ffap' to visit the link at point.
20985 Otherwise, return a user error."
20986 (interactive "P")
20987 (let ((element (org-element-at-point)))
20988 (assert (not buffer-read-only) nil
20989 "Buffer is read-only: %s" (buffer-name))
20990 (case (org-element-type element)
20991 (src-block
20992 (if (not arg) (org-edit-src-code)
20993 (let* ((info (org-babel-get-src-block-info))
20994 (lang (nth 0 info))
20995 (params (nth 2 info))
20996 (session (cdr (assq :session params))))
20997 (if (not session) (org-edit-src-code)
20998 ;; At a src-block with a session and function called with
20999 ;; an ARG: switch to the buffer related to the inferior
21000 ;; process.
21001 (switch-to-buffer
21002 (funcall (intern (concat "org-babel-prep-session:" lang))
21003 session params))))))
21004 (keyword
21005 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
21006 (org-open-link-from-string
21007 (format "[[%s]]"
21008 (expand-file-name
21009 (let ((value (org-element-property :value element)))
21010 (cond ((not (org-string-nw-p value))
21011 (user-error "No file to edit"))
21012 ((string-match "\\`\"\\(.*?\\)\"" value)
21013 (match-string 1 value))
21014 ((string-match "\\`[^ \t\"]\\S-*" value)
21015 (match-string 0 value))
21016 (t (user-error "No valid file specified")))))))
21017 (user-error "No special environment to edit here")))
21018 (table
21019 (if (eq (org-element-property :type element) 'table.el)
21020 (org-edit-table.el)
21021 (call-interactively 'org-table-edit-formulas)))
21022 ;; Only Org tables contain `table-row' type elements.
21023 (table-row (call-interactively 'org-table-edit-formulas))
21024 (example-block (org-edit-src-code))
21025 (export-block (org-edit-export-block))
21026 (fixed-width (org-edit-fixed-width-region))
21027 (otherwise
21028 ;; No notable element at point. Though, we may be at a link or
21029 ;; a footnote reference, which are objects. Thus, scan deeper.
21030 (let ((context (org-element-context element)))
21031 (case (org-element-type context)
21032 (link (call-interactively #'ffap))
21033 (footnote-reference (org-edit-footnote-reference))
21034 (t (user-error "No special environment to edit here"))))))))
21036 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21037 (defun org-ctrl-c-ctrl-c (&optional arg)
21038 "Set tags in headline, or update according to changed information at point.
21040 This command does many different things, depending on context:
21042 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21043 this is what we do.
21045 - If the cursor is on a statistics cookie, update it.
21047 - If the cursor is in a headline, prompt for tags and insert them
21048 into the current line, aligned to `org-tags-column'. When called
21049 with prefix arg, realign all tags in the current buffer.
21051 - If the cursor is in one of the special #+KEYWORD lines, this
21052 triggers scanning the buffer for these lines and updating the
21053 information.
21055 - If the cursor is inside a table, realign the table. This command
21056 works even if the automatic table editor has been turned off.
21058 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21059 the entire table.
21061 - If the cursor is at a footnote reference or definition, jump to
21062 the corresponding definition or references, respectively.
21064 - If the cursor is a the beginning of a dynamic block, update it.
21066 - If the current buffer is a capture buffer, close note and file it.
21068 - If the cursor is on a <<<target>>>, update radio targets and
21069 corresponding links in this buffer.
21071 - If the cursor is on a numbered item in a plain list, renumber the
21072 ordered list.
21074 - If the cursor is on a checkbox, toggle it.
21076 - If the cursor is on a code block, evaluate it. The variable
21077 `org-confirm-babel-evaluate' can be used to control prompting
21078 before code block evaluation, by default every code block
21079 evaluation requires confirmation. Code block evaluation can be
21080 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21081 (interactive "P")
21082 (cond
21083 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21084 org-occur-highlights)
21085 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21086 (org-remove-occur-highlights)
21087 (message "Temporary highlights/overlays removed from current buffer"))
21088 ((and (local-variable-p 'org-finish-function (current-buffer))
21089 (fboundp org-finish-function))
21090 (funcall org-finish-function))
21091 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21093 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21094 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21095 (user-error "C-c C-c can do nothing useful at this location"))
21096 (let* ((context (org-element-context))
21097 (type (org-element-type context)))
21098 (case type
21099 ;; When at a link, act according to the parent instead.
21100 (link (setq context (org-element-property :parent context))
21101 (setq type (org-element-type context)))
21102 ;; Unsupported object types: refer to the first supported
21103 ;; element or object containing it.
21104 ((bold code entity export-snippet inline-babel-call inline-src-block
21105 italic latex-fragment line-break macro strike-through subscript
21106 superscript underline verbatim)
21107 (setq context
21108 (org-element-lineage
21109 context '(radio-target paragraph verse-block table-cell)))))
21110 ;; For convenience: at the first line of a paragraph on the
21111 ;; same line as an item, apply function on that item instead.
21112 (when (eq type 'paragraph)
21113 (let ((parent (org-element-property :parent context)))
21114 (when (and (eq (org-element-type parent) 'item)
21115 (= (line-beginning-position)
21116 (org-element-property :begin parent)))
21117 (setq context parent type 'item))))
21118 ;; Act according to type of element or object at point.
21119 (case type
21120 (clock (org-clock-update-time-maybe))
21121 (dynamic-block
21122 (save-excursion
21123 (goto-char (org-element-property :post-affiliated context))
21124 (org-update-dblock)))
21125 (footnote-definition
21126 (goto-char (org-element-property :post-affiliated context))
21127 (call-interactively 'org-footnote-action))
21128 (footnote-reference (call-interactively 'org-footnote-action))
21129 ((headline inlinetask)
21130 (save-excursion (goto-char (org-element-property :begin context))
21131 (call-interactively 'org-set-tags)))
21132 (item
21133 ;; At an item: a double C-u set checkbox to "[-]"
21134 ;; unconditionally, whereas a single one will toggle its
21135 ;; presence. Without a universal argument, if the item
21136 ;; has a checkbox, toggle it. Otherwise repair the list.
21137 (let* ((box (org-element-property :checkbox context))
21138 (struct (org-element-property :structure context))
21139 (old-struct (copy-tree struct))
21140 (parents (org-list-parents-alist struct))
21141 (prevs (org-list-prevs-alist struct))
21142 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21143 (org-list-set-checkbox
21144 (org-element-property :begin context) struct
21145 (cond ((equal arg '(16)) "[-]")
21146 ((and (not box) (equal arg '(4))) "[ ]")
21147 ((or (not box) (equal arg '(4))) nil)
21148 ((eq box 'on) "[ ]")
21149 (t "[X]")))
21150 ;; Mimic `org-list-write-struct' but with grabbing
21151 ;; a return value from `org-list-struct-fix-box'.
21152 (org-list-struct-fix-ind struct parents 2)
21153 (org-list-struct-fix-item-end struct)
21154 (org-list-struct-fix-bul struct prevs)
21155 (org-list-struct-fix-ind struct parents)
21156 (let ((block-item
21157 (org-list-struct-fix-box struct parents prevs orderedp)))
21158 (if (and box (equal struct old-struct))
21159 (if (equal arg '(16))
21160 (message "Checkboxes already reset")
21161 (user-error "Cannot toggle this checkbox: %s"
21162 (if (eq box 'on)
21163 "all subitems checked"
21164 "unchecked subitems")))
21165 (org-list-struct-apply-struct struct old-struct)
21166 (org-update-checkbox-count-maybe))
21167 (when block-item
21168 (message "Checkboxes were removed due to empty box at line %d"
21169 (org-current-line block-item))))))
21170 (keyword
21171 (let ((org-inhibit-startup-visibility-stuff t)
21172 (org-startup-align-all-tables nil))
21173 (when (boundp 'org-table-coordinate-overlays)
21174 (mapc 'delete-overlay org-table-coordinate-overlays)
21175 (setq org-table-coordinate-overlays nil))
21176 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21177 (message "Local setup has been refreshed"))
21178 (plain-list
21179 ;; At a plain list, with a double C-u argument, set
21180 ;; checkboxes of each item to "[-]", whereas a single one
21181 ;; will toggle their presence according to the state of the
21182 ;; first item in the list. Without an argument, repair the
21183 ;; list.
21184 (let* ((begin (org-element-property :contents-begin context))
21185 (beginm (move-marker (make-marker) begin))
21186 (struct (org-element-property :structure context))
21187 (old-struct (copy-tree struct))
21188 (first-box (save-excursion
21189 (goto-char begin)
21190 (looking-at org-list-full-item-re)
21191 (match-string-no-properties 3)))
21192 (new-box (cond ((equal arg '(16)) "[-]")
21193 ((equal arg '(4)) (unless first-box "[ ]"))
21194 ((equal first-box "[X]") "[ ]")
21195 (t "[X]"))))
21196 (cond
21197 (arg
21198 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
21199 (org-list-get-all-items
21200 begin struct (org-list-prevs-alist struct))))
21201 ((and first-box (eq (point) begin))
21202 ;; For convenience, when point is at bol on the first
21203 ;; item of the list and no argument is provided, simply
21204 ;; toggle checkbox of that item, if any.
21205 (org-list-set-checkbox begin struct new-box)))
21206 (org-list-write-struct
21207 struct (org-list-parents-alist struct) old-struct)
21208 (org-update-checkbox-count-maybe)
21209 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21210 ((property-drawer node-property)
21211 (call-interactively 'org-property-action))
21212 ((radio-target target)
21213 (call-interactively 'org-update-radio-target-regexp))
21214 (statistics-cookie
21215 (call-interactively 'org-update-statistics-cookies))
21216 ((table table-cell table-row)
21217 ;; At a table, recalculate every field and align it. Also
21218 ;; send the table if necessary. If the table has
21219 ;; a `table.el' type, just give up. At a table row or
21220 ;; cell, maybe recalculate line but always align table.
21221 (if (eq (org-element-property :type context) 'table.el)
21222 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21223 Use \\[org-edit-special] to edit table.el tables"))
21224 (let ((org-enable-table-editor t))
21225 (if (or (eq type 'table)
21226 ;; Check if point is at a TBLFM line.
21227 (and (eq type 'table-row)
21228 (= (point) (org-element-property :end context))))
21229 (save-excursion
21230 (if (org-at-TBLFM-p)
21231 (progn (require 'org-table)
21232 (org-table-calc-current-TBLFM))
21233 (goto-char (org-element-property :contents-begin context))
21234 (org-call-with-arg 'org-table-recalculate (or arg t))
21235 (orgtbl-send-table 'maybe)))
21236 (org-table-maybe-eval-formula)
21237 (cond (arg (call-interactively 'org-table-recalculate))
21238 ((org-table-maybe-recalculate-line))
21239 (t (org-table-align)))))))
21240 (timestamp (org-timestamp-change 0 'day))
21241 (otherwise
21242 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21243 (user-error
21244 "C-c C-c can do nothing useful at this location")))))))))
21246 (defun org-mode-restart ()
21247 (interactive)
21248 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
21249 (funcall major-mode)
21250 (hack-local-variables)
21251 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
21252 (org-indent-mode -1)))
21253 (message "%s restarted" major-mode))
21255 (defun org-kill-note-or-show-branches ()
21256 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21257 (interactive)
21258 (if (not org-finish-function)
21259 (progn
21260 (outline-hide-subtree)
21261 (call-interactively 'outline-show-branches))
21262 (let ((org-note-abort t))
21263 (funcall org-finish-function))))
21265 (defun org-delete-indentation (&optional ARG)
21266 "Join current line to previous and fix whitespace at join.
21268 If previous line is a headline add to headline title. Otherwise
21269 the function calls `delete-indentation'.
21271 With argument, join this line to following line."
21272 (interactive "*P")
21273 (if (save-excursion
21274 (if ARG (beginning-of-line)
21275 (forward-line -1))
21276 (looking-at org-complex-heading-regexp))
21277 ;; At headline.
21278 (let ((tags-column (when (match-beginning 5)
21279 (save-excursion (goto-char (match-beginning 5))
21280 (current-column))))
21281 (string (concat " " (progn (when ARG (forward-line 1))
21282 (org-trim (delete-and-extract-region
21283 (line-beginning-position)
21284 (line-end-position)))))))
21285 (unless (bobp) (delete-region (point) (1- (point))))
21286 (goto-char (or (match-end 4)
21287 (match-beginning 5)
21288 (match-end 0)))
21289 (skip-chars-backward " \t")
21290 (save-excursion (insert string))
21291 ;; Adjust alignment of tags.
21292 (when tags-column
21293 (org-align-tags-here (if org-auto-align-tags
21294 org-tags-column
21295 tags-column))))
21296 (delete-indentation ARG)))
21298 (defun org-open-line (n)
21299 "Insert a new row in tables, call `open-line' elsewhere.
21300 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21301 (interactive "*p")
21302 (cond
21303 ((not org-special-ctrl-o)
21304 (open-line n))
21305 ((org-at-table-p)
21306 (org-table-insert-row))
21308 (open-line n))))
21310 (defun org-return (&optional indent)
21311 "Goto next table row or insert a newline.
21313 Calls `org-table-next-row' or `newline', depending on context.
21315 When optional INDENT argument is non-nil, call
21316 `newline-and-indent' instead of `newline'.
21318 When `org-return-follows-link' is non-nil and point is on
21319 a timestamp or a link, call `org-open-at-point'. However, it
21320 will not happen if point is in a table or on a \"dead\"
21321 object (e.g., within a comment). In these case, you need to use
21322 `org-open-at-point' directly."
21323 (interactive)
21324 (let* ((context (if org-return-follows-link (org-element-context)
21325 (org-element-at-point)))
21326 (type (org-element-type context)))
21327 (cond
21328 ;; In a table, call `org-table-next-row'.
21329 ((or (and (eq type 'table)
21330 (>= (point) (org-element-property :contents-begin context))
21331 (< (point) (org-element-property :contents-end context)))
21332 (org-element-lineage context '(table-row table-cell) t))
21333 (org-table-justify-field-maybe)
21334 (call-interactively #'org-table-next-row))
21335 ;; On a link or a timestamp but not on white spaces after it,
21336 ;; call `org-open-line' if `org-return-follows-link' allows it.
21337 ((and org-return-follows-link
21338 (memq type '(link timestamp))
21339 (< (point)
21340 (save-excursion (goto-char (org-element-property :end context))
21341 (skip-chars-backward " \t")
21342 (point))))
21343 (call-interactively #'org-open-at-point))
21344 ;; Insert newline in heading, but preserve tags.
21345 ((and (not (bolp))
21346 (save-excursion (beginning-of-line)
21347 (looking-at org-complex-heading-regexp)))
21348 ;; At headline. Split line. However, if point is on keyword,
21349 ;; priority cookie or tags, do not break any of them: add
21350 ;; a newline after the headline instead.
21351 (let ((tags-column (and (match-beginning 5)
21352 (save-excursion (goto-char (match-beginning 5))
21353 (current-column))))
21354 (string
21355 (when (and (match-end 4)
21356 (>= (point)
21357 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21358 (<= (point) (match-end 4)))
21359 (delete-and-extract-region (point) (match-end 4)))))
21360 (when (and tags-column string) ; Adjust tag alignment.
21361 (org-align-tags-here
21362 (if org-auto-align-tags org-tags-column tags-column)))
21363 (end-of-line)
21364 (org-show-entry)
21365 (if indent (newline-and-indent) (newline))
21366 (when string (save-excursion (insert (org-trim string))))))
21367 ;; In a list, make sure indenting keeps trailing text within.
21368 ((and indent
21369 (not (eolp))
21370 (org-element-lineage context '(item)))
21371 (let ((trailing-data
21372 (delete-and-extract-region (point) (line-end-position))))
21373 (newline-and-indent)
21374 (save-excursion (insert trailing-data))))
21375 (t (if indent (newline-and-indent) (newline))))))
21377 (defun org-return-indent ()
21378 "Goto next table row or insert a newline and indent.
21379 Calls `org-table-next-row' or `newline-and-indent', depending on
21380 context. See the individual commands for more information."
21381 (interactive)
21382 (org-return t))
21384 (defun org-ctrl-c-star ()
21385 "Compute table, or change heading status of lines.
21386 Calls `org-table-recalculate' or `org-toggle-heading',
21387 depending on context."
21388 (interactive)
21389 (cond
21390 ((org-at-table-p)
21391 (call-interactively 'org-table-recalculate))
21393 ;; Convert all lines in region to list items
21394 (call-interactively 'org-toggle-heading))))
21396 (defun org-ctrl-c-minus ()
21397 "Insert separator line in table or modify bullet status of line.
21398 Also turns a plain line or a region of lines into list items.
21399 Calls `org-table-insert-hline', `org-toggle-item', or
21400 `org-cycle-list-bullet', depending on context."
21401 (interactive)
21402 (cond
21403 ((org-at-table-p)
21404 (call-interactively 'org-table-insert-hline))
21405 ((org-region-active-p)
21406 (call-interactively 'org-toggle-item))
21407 ((org-in-item-p)
21408 (call-interactively 'org-cycle-list-bullet))
21410 (call-interactively 'org-toggle-item))))
21412 (defun org-toggle-item (arg)
21413 "Convert headings or normal lines to items, items to normal lines.
21414 If there is no active region, only the current line is considered.
21416 If the first non blank line in the region is a headline, convert
21417 all headlines to items, shifting text accordingly.
21419 If it is an item, convert all items to normal lines.
21421 If it is normal text, change region into a list of items.
21422 With a prefix argument ARG, change the region in a single item."
21423 (interactive "P")
21424 (let ((shift-text
21425 (function
21426 ;; Shift text in current section to IND, from point to END.
21427 ;; The function leaves point to END line.
21428 (lambda (ind end)
21429 (let ((min-i 1000) (end (copy-marker end)))
21430 ;; First determine the minimum indentation (MIN-I) of
21431 ;; the text.
21432 (save-excursion
21433 (catch 'exit
21434 (while (< (point) end)
21435 (let ((i (org-get-indentation)))
21436 (cond
21437 ;; Skip blank lines and inline tasks.
21438 ((looking-at "^[ \t]*$"))
21439 ((looking-at org-outline-regexp-bol))
21440 ;; We can't find less than 0 indentation.
21441 ((zerop i) (throw 'exit (setq min-i 0)))
21442 ((< i min-i) (setq min-i i))))
21443 (forward-line))))
21444 ;; Then indent each line so that a line indented to
21445 ;; MIN-I becomes indented to IND. Ignore blank lines
21446 ;; and inline tasks in the process.
21447 (let ((delta (- ind min-i)))
21448 (while (< (point) end)
21449 (unless (or (looking-at "^[ \t]*$")
21450 (looking-at org-outline-regexp-bol))
21451 (org-indent-line-to (+ (org-get-indentation) delta)))
21452 (forward-line)))))))
21453 (skip-blanks
21454 (function
21455 ;; Return beginning of first non-blank line, starting from
21456 ;; line at POS.
21457 (lambda (pos)
21458 (save-excursion
21459 (goto-char pos)
21460 (skip-chars-forward " \r\t\n")
21461 (point-at-bol)))))
21462 beg end)
21463 ;; Determine boundaries of changes.
21464 (if (org-region-active-p)
21465 (setq beg (funcall skip-blanks (region-beginning))
21466 end (copy-marker (region-end)))
21467 (setq beg (funcall skip-blanks (point-at-bol))
21468 end (copy-marker (point-at-eol))))
21469 ;; Depending on the starting line, choose an action on the text
21470 ;; between BEG and END.
21471 (org-with-limited-levels
21472 (save-excursion
21473 (goto-char beg)
21474 (cond
21475 ;; Case 1. Start at an item: de-itemize. Note that it only
21476 ;; happens when a region is active: `org-ctrl-c-minus'
21477 ;; would call `org-cycle-list-bullet' otherwise.
21478 ((org-at-item-p)
21479 (while (< (point) end)
21480 (when (org-at-item-p)
21481 (skip-chars-forward " \t")
21482 (delete-region (point) (match-end 0)))
21483 (forward-line)))
21484 ;; Case 2. Start at an heading: convert to items.
21485 ((org-at-heading-p)
21486 (let* ((bul (org-list-bullet-string "-"))
21487 (bul-len (length bul))
21488 (done (org-entry-is-done-p))
21489 (todo (org-entry-is-todo-p))
21490 ;; Indentation of the first heading. It should be
21491 ;; relative to the indentation of its parent, if any.
21492 (start-ind (save-excursion
21493 (cond
21494 ((not org-adapt-indentation) 0)
21495 ((not (outline-previous-heading)) 0)
21496 (t (length (match-string 0))))))
21497 ;; Level of first heading. Further headings will be
21498 ;; compared to it to determine hierarchy in the list.
21499 (ref-level (org-reduced-level (org-outline-level))))
21500 (when (or done todo) (org-todo ""))
21501 (while (< (point) end)
21502 (let* ((level (org-reduced-level (org-outline-level)))
21503 (delta (max 0 (- level ref-level))))
21504 ;; If current headline is less indented than the first
21505 ;; one, set it as reference, in order to preserve
21506 ;; subtrees.
21507 (when (< level ref-level) (setq ref-level level))
21508 (replace-match bul t t)
21509 (org-indent-line-to (+ start-ind (* delta bul-len)))
21510 (when (or done todo)
21511 (let* ((struct (org-list-struct))
21512 (old (copy-tree struct)))
21513 (org-list-set-checkbox (line-beginning-position)
21514 struct
21515 (if done "[X]" "[ ]"))
21516 (org-list-write-struct struct
21517 (org-list-parents-alist struct)
21518 old)))
21519 ;; Ensure all text down to END (or SECTION-END) belongs
21520 ;; to the newly created item.
21521 (let ((section-end (save-excursion
21522 (or (outline-next-heading) (point)))))
21523 (forward-line)
21524 (funcall shift-text
21525 (+ start-ind (* (1+ delta) bul-len))
21526 (min end section-end)))))))
21527 ;; Case 3. Normal line with ARG: make the first line of region
21528 ;; an item, and shift indentation of others lines to
21529 ;; set them as item's body.
21530 (arg (let* ((bul (org-list-bullet-string "-"))
21531 (bul-len (length bul))
21532 (ref-ind (org-get-indentation)))
21533 (skip-chars-forward " \t")
21534 (insert bul)
21535 (forward-line)
21536 (while (< (point) end)
21537 ;; Ensure that lines less indented than first one
21538 ;; still get included in item body.
21539 (funcall shift-text
21540 (+ ref-ind bul-len)
21541 (min end (save-excursion (or (outline-next-heading)
21542 (point)))))
21543 (forward-line))))
21544 ;; Case 4. Normal line without ARG: turn each non-item line
21545 ;; into an item.
21547 (while (< (point) end)
21548 (unless (or (org-at-heading-p) (org-at-item-p))
21549 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21550 (replace-match
21551 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21552 (forward-line))))))))
21554 (defun org-toggle-heading (&optional nstars)
21555 "Convert headings to normal text, or items or text to headings.
21556 If there is no active region, only convert the current line.
21558 With a \\[universal-argument] prefix, convert the whole list at
21559 point into heading.
21561 In a region:
21563 - If the first non blank line is a headline, remove the stars
21564 from all headlines in the region.
21566 - If it is a normal line, turn each and every normal line (i.e.,
21567 not an heading or an item) in the region into headings. If you
21568 want to convert only the first line of this region, use one
21569 universal prefix argument.
21571 - If it is a plain list item, turn all plain list items into headings.
21573 When converting a line into a heading, the number of stars is chosen
21574 such that the lines become children of the current entry. However,
21575 when a numeric prefix argument is given, its value determines the
21576 number of stars to add."
21577 (interactive "P")
21578 (let ((skip-blanks
21579 (function
21580 ;; Return beginning of first non-blank line, starting from
21581 ;; line at POS.
21582 (lambda (pos)
21583 (save-excursion
21584 (goto-char pos)
21585 (while (org-at-comment-p) (forward-line))
21586 (skip-chars-forward " \r\t\n")
21587 (point-at-bol)))))
21588 beg end toggled)
21589 ;; Determine boundaries of changes. If a universal prefix has
21590 ;; been given, put the list in a region. If region ends at a bol,
21591 ;; do not consider the last line to be in the region.
21593 (when (and current-prefix-arg (org-at-item-p))
21594 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
21595 (org-mark-element))
21597 (if (org-region-active-p)
21598 (setq beg (funcall skip-blanks (region-beginning))
21599 end (copy-marker (save-excursion
21600 (goto-char (region-end))
21601 (if (bolp) (point) (point-at-eol)))))
21602 (setq beg (funcall skip-blanks (point-at-bol))
21603 end (copy-marker (point-at-eol))))
21604 ;; Ensure inline tasks don't count as headings.
21605 (org-with-limited-levels
21606 (save-excursion
21607 (goto-char beg)
21608 (cond
21609 ;; Case 1. Started at an heading: de-star headings.
21610 ((org-at-heading-p)
21611 (while (< (point) end)
21612 (when (org-at-heading-p t)
21613 (looking-at org-outline-regexp) (replace-match "")
21614 (setq toggled t))
21615 (forward-line)))
21616 ;; Case 2. Started at an item: change items into headlines.
21617 ;; One star will be added by `org-list-to-subtree'.
21618 ((org-at-item-p)
21619 (while (< (point) end)
21620 (when (org-at-item-p)
21621 ;; Pay attention to cases when region ends before list.
21622 (let* ((struct (org-list-struct))
21623 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
21624 (save-restriction
21625 (narrow-to-region (point) list-end)
21626 (insert (org-list-to-subtree (org-list-parse-list t)))))
21627 (setq toggled t))
21628 (forward-line)))
21629 ;; Case 3. Started at normal text: make every line an heading,
21630 ;; skipping headlines and items.
21631 (t (let* ((stars
21632 (make-string
21633 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21634 (add-stars
21635 (cond (nstars "") ; stars from prefix only
21636 ((equal stars "") "*") ; before first heading
21637 (org-odd-levels-only "**") ; inside heading, odd
21638 (t "*"))) ; inside heading, oddeven
21639 (rpl (concat stars add-stars " "))
21640 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
21641 (while (< (point) (if (equal nstars '(4)) lend end))
21642 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21643 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21644 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21645 (forward-line)))))))
21646 (unless toggled (message "Cannot toggle heading from here"))))
21648 (defun org-meta-return (&optional _arg)
21649 "Insert a new heading or wrap a region in a table.
21650 Calls `org-insert-heading' or `org-table-wrap-region', depending
21651 on context. See the individual commands for more information."
21652 (interactive)
21653 (org-check-before-invisible-edit 'insert)
21654 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21655 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21656 #'org-insert-heading))))
21658 ;;; Menu entries
21660 (defsubst org-in-subtree-not-table-p ()
21661 "Are we in a subtree and not in a table?"
21662 (and (not (org-before-first-heading-p))
21663 (not (org-at-table-p))))
21665 ;; Define the Org-mode menus
21666 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21667 '("Tbl"
21668 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21669 ["Next Field" org-cycle (org-at-table-p)]
21670 ["Previous Field" org-shifttab (org-at-table-p)]
21671 ["Next Row" org-return (org-at-table-p)]
21672 "--"
21673 ["Blank Field" org-table-blank-field (org-at-table-p)]
21674 ["Edit Field" org-table-edit-field (org-at-table-p)]
21675 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21676 "--"
21677 ("Column"
21678 ["Move Column Left" org-metaleft (org-at-table-p)]
21679 ["Move Column Right" org-metaright (org-at-table-p)]
21680 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21681 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21682 ("Row"
21683 ["Move Row Up" org-metaup (org-at-table-p)]
21684 ["Move Row Down" org-metadown (org-at-table-p)]
21685 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21686 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21687 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21688 "--"
21689 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21690 ("Rectangle"
21691 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21692 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21693 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21694 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21695 "--"
21696 ("Calculate"
21697 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21698 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21699 ["Edit Formulas" org-edit-special (org-at-table-p)]
21700 "--"
21701 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21702 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21703 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21704 "--"
21705 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21706 "--"
21707 ["Sum Column/Rectangle" org-table-sum
21708 (or (org-at-table-p) (org-region-active-p))]
21709 ["Which Column?" org-table-current-column (org-at-table-p)])
21710 ["Debug Formulas"
21711 org-table-toggle-formula-debugger
21712 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21713 ["Show Col/Row Numbers"
21714 org-table-toggle-coordinate-overlays
21715 :style toggle
21716 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21717 "--"
21718 ["Create" org-table-create (and (not (org-at-table-p))
21719 org-enable-table-editor)]
21720 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21721 ["Import from File" org-table-import (not (org-at-table-p))]
21722 ["Export to File" org-table-export (org-at-table-p)]
21723 "--"
21724 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21725 "--"
21726 ("Plot"
21727 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21728 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21730 (easy-menu-define org-org-menu org-mode-map "Org menu"
21731 '("Org"
21732 ("Show/Hide"
21733 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21734 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21735 ["Sparse Tree..." org-sparse-tree t]
21736 ["Reveal Context" org-reveal t]
21737 ["Show All" outline-show-all t]
21738 "--"
21739 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21740 "--"
21741 ["New Heading" org-insert-heading t]
21742 ("Navigate Headings"
21743 ["Up" outline-up-heading t]
21744 ["Next" outline-next-visible-heading t]
21745 ["Previous" outline-previous-visible-heading t]
21746 ["Next Same Level" outline-forward-same-level t]
21747 ["Previous Same Level" outline-backward-same-level t]
21748 "--"
21749 ["Jump" org-goto t])
21750 ("Edit Structure"
21751 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21752 "--"
21753 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21754 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21755 "--"
21756 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21757 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21758 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21759 "--"
21760 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21761 "--"
21762 ["Copy visible text" org-copy-visible t]
21763 "--"
21764 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21765 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21766 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21767 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21768 "--"
21769 ["Sort Region/Children" org-sort t]
21770 "--"
21771 ["Convert to odd levels" org-convert-to-odd-levels t]
21772 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21773 ("Editing"
21774 ["Emphasis..." org-emphasize t]
21775 ["Edit Source Example" org-edit-special t]
21776 "--"
21777 ["Footnote new/jump" org-footnote-action t]
21778 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21779 ("Archive"
21780 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21781 "--"
21782 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21783 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21784 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21786 "--"
21787 ("Hyperlinks"
21788 ["Store Link (Global)" org-store-link t]
21789 ["Find existing link to here" org-occur-link-in-agenda-files t]
21790 ["Insert Link" org-insert-link t]
21791 ["Follow Link" org-open-at-point t]
21792 "--"
21793 ["Next link" org-next-link t]
21794 ["Previous link" org-previous-link t]
21795 "--"
21796 ["Descriptive Links"
21797 org-toggle-link-display
21798 :style radio
21799 :selected org-descriptive-links
21801 ["Literal Links"
21802 org-toggle-link-display
21803 :style radio
21804 :selected (not org-descriptive-links)])
21805 "--"
21806 ("TODO Lists"
21807 ["TODO/DONE/-" org-todo t]
21808 ("Select keyword"
21809 ["Next keyword" org-shiftright (org-at-heading-p)]
21810 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21811 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21812 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21813 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21814 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21815 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21816 "--"
21817 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21818 :selected org-enforce-todo-dependencies :style toggle :active t]
21819 "Settings for tree at point"
21820 ["Do Children sequentially" org-toggle-ordered-property :style radio
21821 :selected (org-entry-get nil "ORDERED")
21822 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21823 ["Do Children parallel" org-toggle-ordered-property :style radio
21824 :selected (not (org-entry-get nil "ORDERED"))
21825 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21826 "--"
21827 ["Set Priority" org-priority t]
21828 ["Priority Up" org-shiftup t]
21829 ["Priority Down" org-shiftdown t]
21830 "--"
21831 ["Get news from all feeds" org-feed-update-all t]
21832 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21833 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21834 ("TAGS and Properties"
21835 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21836 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21837 "--"
21838 ["Set property" org-set-property (not (org-before-first-heading-p))]
21839 ["Column view of properties" org-columns t]
21840 ["Insert Column View DBlock" org-insert-columns-dblock t])
21841 ("Dates and Scheduling"
21842 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21843 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21844 ("Change Date"
21845 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21846 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21847 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21848 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21849 ["Compute Time Range" org-evaluate-time-range t]
21850 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21851 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21852 "--"
21853 ["Custom time format" org-toggle-time-stamp-overlays
21854 :style radio :selected org-display-custom-times]
21855 "--"
21856 ["Goto Calendar" org-goto-calendar t]
21857 ["Date from Calendar" org-date-from-calendar t]
21858 "--"
21859 ["Start/Restart Timer" org-timer-start t]
21860 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21861 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21862 ["Insert Timer String" org-timer t]
21863 ["Insert Timer Item" org-timer-item t])
21864 ("Logging work"
21865 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21866 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21867 ["Clock out" org-clock-out t]
21868 ["Clock cancel" org-clock-cancel t]
21869 "--"
21870 ["Mark as default task" org-clock-mark-default-task t]
21871 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21872 ["Goto running clock" org-clock-goto t]
21873 "--"
21874 ["Display times" org-clock-display t]
21875 ["Create clock table" org-clock-report t]
21876 "--"
21877 ["Record DONE time"
21878 (progn (setq org-log-done (not org-log-done))
21879 (message "Switching to %s will %s record a timestamp"
21880 (car org-done-keywords)
21881 (if org-log-done "automatically" "not")))
21882 :style toggle :selected org-log-done])
21883 "--"
21884 ["Agenda Command..." org-agenda t]
21885 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21886 ("File List for Agenda")
21887 ("Special views current file"
21888 ["TODO Tree" org-show-todo-tree t]
21889 ["Check Deadlines" org-check-deadlines t]
21890 ["Timeline" org-timeline t]
21891 ["Tags/Property tree" org-match-sparse-tree t])
21892 "--"
21893 ["Export/Publish..." org-export-dispatch t]
21894 ("LaTeX"
21895 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21896 :selected org-cdlatex-mode]
21897 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21898 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21899 ["Modify math symbol" org-cdlatex-math-modify
21900 (org-inside-LaTeX-fragment-p)]
21901 ["Insert citation" org-reftex-citation t]
21902 "--"
21903 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21904 "--"
21905 ("MobileOrg"
21906 ["Push Files and Views" org-mobile-push t]
21907 ["Get Captured and Flagged" org-mobile-pull t]
21908 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21909 "--"
21910 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21911 "--"
21912 ("Documentation"
21913 ["Show Version" org-version t]
21914 ["Info Documentation" org-info t])
21915 ("Customize"
21916 ["Browse Org Group" org-customize t]
21917 "--"
21918 ["Expand This Menu" org-create-customize-menu
21919 (fboundp 'customize-menu-create)])
21920 ["Send bug report" org-submit-bug-report t]
21921 "--"
21922 ("Refresh/Reload"
21923 ["Refresh setup current buffer" org-mode-restart t]
21924 ["Reload Org (after update)" org-reload t]
21925 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21928 (defun org-info (&optional node)
21929 "Read documentation for Org-mode in the info system.
21930 With optional NODE, go directly to that node."
21931 (interactive)
21932 (info (format "(org)%s" (or node ""))))
21934 ;;;###autoload
21935 (defun org-submit-bug-report ()
21936 "Submit a bug report on Org-mode via mail.
21938 Don't hesitate to report any problems or inaccurate documentation.
21940 If you don't have setup sending mail from (X)Emacs, please copy the
21941 output buffer into your mail program, as it gives us important
21942 information about your Org-mode version and configuration."
21943 (interactive)
21944 (require 'reporter)
21945 (defvar reporter-prompt-for-summary-p)
21946 (org-load-modules-maybe)
21947 (org-require-autoloaded-modules)
21948 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21949 (reporter-submit-bug-report
21950 "emacs-orgmode@gnu.org"
21951 (org-version nil 'full)
21952 (let (list)
21953 (save-window-excursion
21954 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21955 (delete-other-windows)
21956 (erase-buffer)
21957 (insert "You are about to submit a bug report to the Org-mode mailing list.
21959 We would like to add your full Org-mode and Outline configuration to the
21960 bug report. This greatly simplifies the work of the maintainer and
21961 other experts on the mailing list.
21963 HOWEVER, some variables you have customized may contain private
21964 information. The names of customers, colleagues, or friends, might
21965 appear in the form of file names, tags, todo states, or search strings.
21966 If you answer yes to the prompt, you might want to check and remove
21967 such private information before sending the email.")
21968 (add-text-properties (point-min) (point-max) '(face org-warning))
21969 (when (yes-or-no-p "Include your Org-mode configuration ")
21970 (mapatoms
21971 (lambda (v)
21972 (and (boundp v)
21973 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21974 (or (and (symbol-value v)
21975 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21976 (and
21977 (get v 'custom-type) (get v 'standard-value)
21978 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21979 (push v list)))))
21980 (kill-buffer (get-buffer "*Warn about privacy*"))
21981 list))
21982 nil nil
21983 "Remember to cover the basics, that is, what you expected to happen and
21984 what in fact did happen. You don't know how to make a good report? See
21986 http://orgmode.org/manual/Feedback.html#Feedback
21988 Your bug report will be posted to the Org-mode mailing list.
21989 ------------------------------------------------------------------------")
21990 (save-excursion
21991 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21992 (replace-match "\\1Bug: \\3 [\\2]")))))
21995 (defun org-install-agenda-files-menu ()
21996 (let ((bl (buffer-list)))
21997 (save-excursion
21998 (while bl
21999 (set-buffer (pop bl))
22000 (if (derived-mode-p 'org-mode) (setq bl nil)))
22001 (when (derived-mode-p 'org-mode)
22002 (easy-menu-change
22003 '("Org") "File List for Agenda"
22004 (append
22005 (list
22006 ["Edit File List" (org-edit-agenda-file-list) t]
22007 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
22008 ["Remove Current File from List" org-remove-file t]
22009 ["Cycle through agenda files" org-cycle-agenda-files t]
22010 ["Occur in all agenda files" org-occur-in-agenda-files t]
22011 "--")
22012 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
22014 ;;;; Documentation
22016 (defun org-require-autoloaded-modules ()
22017 (interactive)
22018 (mapc 'require
22019 '(org-agenda org-archive org-attach org-clock org-colview org-id
22020 org-table org-timer)))
22022 ;;;###autoload
22023 (defun org-reload (&optional uncompiled)
22024 "Reload all org lisp files.
22025 With prefix arg UNCOMPILED, load the uncompiled versions."
22026 (interactive "P")
22027 (require 'loadhist)
22028 (let* ((org-dir (org-find-library-dir "org"))
22029 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
22030 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
22031 (remove-re (mapconcat 'identity
22032 (mapcar (lambda (f) (concat "^" f "$"))
22033 (list (if (featurep 'xemacs)
22034 "org-colview"
22035 "org-colview-xemacs")
22036 "org" "org-loaddefs" "org-version"))
22037 "\\|"))
22038 (feats (delete-dups
22039 (mapcar 'file-name-sans-extension
22040 (mapcar 'file-name-nondirectory
22041 (delq nil
22042 (mapcar 'feature-file
22043 features))))))
22044 (lfeat (append
22045 (sort
22046 (setq feats
22047 (delq nil (mapcar
22048 (lambda (f)
22049 (if (and (string-match feature-re f)
22050 (not (string-match remove-re f)))
22051 f nil))
22052 feats)))
22053 'string-lessp)
22054 (list "org-version" "org")))
22055 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
22056 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
22057 load-uncore load-misses)
22058 (setq load-misses
22059 (delq 't
22060 (mapcar (lambda (f)
22061 (or (org-load-noerror-mustsuffix (concat org-dir f))
22062 (and (string= org-dir contrib-dir)
22063 (org-load-noerror-mustsuffix (concat contrib-dir f)))
22064 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
22065 (add-to-list 'load-uncore f 'append)
22068 lfeat)))
22069 (if load-uncore
22070 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
22071 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
22072 (if load-misses
22073 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
22074 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
22075 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
22077 ;;;###autoload
22078 (defun org-customize ()
22079 "Call the customize function with org as argument."
22080 (interactive)
22081 (org-load-modules-maybe)
22082 (org-require-autoloaded-modules)
22083 (customize-browse 'org))
22085 (defun org-create-customize-menu ()
22086 "Create a full customization menu for Org-mode, insert it into the menu."
22087 (interactive)
22088 (org-load-modules-maybe)
22089 (org-require-autoloaded-modules)
22090 (if (fboundp 'customize-menu-create)
22091 (progn
22092 (easy-menu-change
22093 '("Org") "Customize"
22094 `(["Browse Org group" org-customize t]
22095 "--"
22096 ,(customize-menu-create 'org)
22097 ["Set" Custom-set t]
22098 ["Save" Custom-save t]
22099 ["Reset to Current" Custom-reset-current t]
22100 ["Reset to Saved" Custom-reset-saved t]
22101 ["Reset to Standard Settings" Custom-reset-standard t]))
22102 (message "\"Org\"-menu now contains full customization menu"))
22103 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22105 ;;;; Miscellaneous stuff
22107 ;;; Generally useful functions
22109 (defsubst org-get-at-eol (property n)
22110 "Get text property PROPERTY at the end of line less N characters."
22111 (get-text-property (- (point-at-eol) n) property))
22113 (defun org-find-text-property-in-string (prop s)
22114 "Return the first non-nil value of property PROP in string S."
22115 (or (get-text-property 0 prop s)
22116 (get-text-property (or (next-single-property-change 0 prop s) 0)
22117 prop s)))
22119 (defun org-display-warning (message) ;; Copied from Emacs-Muse
22120 "Display the given MESSAGE as a warning."
22121 (if (fboundp 'display-warning)
22122 (display-warning 'org message
22123 (if (featurep 'xemacs) 'warning :warning))
22124 (let ((buf (get-buffer-create "*Org warnings*")))
22125 (with-current-buffer buf
22126 (goto-char (point-max))
22127 (insert "Warning (Org): " message)
22128 (unless (bolp)
22129 (newline)))
22130 (display-buffer buf)
22131 (sit-for 0))))
22133 (defun org-eval (form)
22134 "Eval FORM and return result."
22135 (condition-case error
22136 (eval form)
22137 (error (format "%%![Error: %s]" error))))
22139 (defun org-in-clocktable-p ()
22140 "Check if the cursor is in a clocktable."
22141 (let ((pos (point)) start)
22142 (save-excursion
22143 (end-of-line 1)
22144 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22145 (setq start (match-beginning 0))
22146 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22147 (>= (match-end 0) pos)
22148 start))))
22150 (defun org-in-verbatim-emphasis ()
22151 (save-match-data
22152 (and (org-in-regexp org-emph-re 2)
22153 (>= (point) (match-beginning 3))
22154 (<= (point) (match-end 4))
22155 (member (match-string 3) '("=" "~")))))
22157 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22158 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22159 (if (and marker (marker-buffer marker)
22160 (buffer-live-p (marker-buffer marker)))
22161 (progn
22162 (org-pop-to-buffer-same-window (marker-buffer marker))
22163 (if (or (> marker (point-max)) (< marker (point-min)))
22164 (widen))
22165 (goto-char marker)
22166 (org-show-context 'org-goto))
22167 (if bookmark
22168 (bookmark-jump bookmark)
22169 (error "Cannot find location"))))
22171 (defun org-quote-csv-field (s)
22172 "Quote field for inclusion in CSV material."
22173 (if (string-match "[\",]" s)
22174 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22177 (defun org-force-self-insert (N)
22178 "Needed to enforce self-insert under remapping."
22179 (interactive "p")
22180 (self-insert-command N))
22182 (defun org-string-width (s)
22183 "Compute width of string, ignoring invisible characters.
22184 This ignores character with invisibility property `org-link', and also
22185 characters with property `org-cwidth', because these will become invisible
22186 upon the next fontification round."
22187 (let (b l)
22188 (when (or (eq t buffer-invisibility-spec)
22189 (assq 'org-link buffer-invisibility-spec))
22190 (while (setq b (text-property-any 0 (length s)
22191 'invisible 'org-link s))
22192 (setq s (concat (substring s 0 b)
22193 (substring s (or (next-single-property-change
22194 b 'invisible s)
22195 (length s)))))))
22196 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22197 (setq s (concat (substring s 0 b)
22198 (substring s (or (next-single-property-change
22199 b 'org-cwidth s)
22200 (length s))))))
22201 (setq l (string-width s) b -1)
22202 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22203 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22206 (defun org-shorten-string (s maxlength)
22207 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22208 If the string is shorter or has length MAXLENGTH, just return the
22209 original string. If it is longer, the functions finds a space in the
22210 string, breaks this string off at that locations and adds three dots
22211 as ellipsis. Including the ellipsis, the string will not be longer
22212 than MAXLENGTH. If finding a good breaking point in the string does
22213 not work, the string is just chopped off in the middle of a word
22214 if necessary."
22215 (if (<= (length s) maxlength)
22217 (let* ((n (max (- maxlength 4) 1))
22218 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22219 (if (string-match re s)
22220 (concat (match-string 1 s) "...")
22221 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22223 (defun org-get-indentation (&optional line)
22224 "Get the indentation of the current line, interpreting tabs.
22225 When LINE is given, assume it represents a line and compute its indentation."
22226 (if line
22227 (if (string-match "^ *" (org-remove-tabs line))
22228 (match-end 0))
22229 (save-excursion
22230 (beginning-of-line 1)
22231 (skip-chars-forward " \t")
22232 (current-column))))
22234 (defun org-get-string-indentation (s)
22235 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22236 (let ((n -1) (i 0) (w tab-width) c)
22237 (catch 'exit
22238 (while (< (setq n (1+ n)) (length s))
22239 (setq c (aref s n))
22240 (cond ((= c ?\ ) (setq i (1+ i)))
22241 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22242 (t (throw 'exit t)))))
22245 (defun org-remove-tabs (s &optional width)
22246 "Replace tabulators in S with spaces.
22247 Assumes that s is a single line, starting in column 0."
22248 (setq width (or width tab-width))
22249 (while (string-match "\t" s)
22250 (setq s (replace-match
22251 (make-string
22252 (- (* width (/ (+ (match-beginning 0) width) width))
22253 (match-beginning 0)) ?\ )
22254 t t s)))
22257 (defun org-fix-indentation (line ind)
22258 "Fix indentation in LINE.
22259 IND is a cons cell with target and minimum indentation.
22260 If the current indentation in LINE is smaller than the minimum,
22261 leave it alone. If it is larger than ind, set it to the target."
22262 (let* ((l (org-remove-tabs line))
22263 (i (org-get-indentation l))
22264 (i1 (car ind)) (i2 (cdr ind)))
22265 (if (>= i i2) (setq l (substring line i2)))
22266 (if (> i1 0)
22267 (concat (make-string i1 ?\ ) l)
22268 l)))
22270 (defun org-remove-indentation (code &optional n)
22271 "Remove the maximum common indentation from the lines in CODE.
22272 N may optionally be the number of spaces to remove."
22273 (with-temp-buffer
22274 (insert code)
22275 (org-do-remove-indentation n)
22276 (buffer-string)))
22278 (defun org-do-remove-indentation (&optional n)
22279 "Remove the maximum common indentation from the buffer."
22280 (untabify (point-min) (point-max))
22281 (let ((min 10000) re)
22282 (if n
22283 (setq min n)
22284 (goto-char (point-min))
22285 (while (re-search-forward "^ *[^ \n]" nil t)
22286 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
22287 (unless (or (= min 0) (= min 10000))
22288 (setq re (format "^ \\{%d\\}" min))
22289 (goto-char (point-min))
22290 (while (re-search-forward re nil t)
22291 (replace-match "")
22292 (end-of-line 1))
22293 min)))
22295 (defun org-fill-template (template alist)
22296 "Find each %key of ALIST in TEMPLATE and replace it."
22297 (let ((case-fold-search nil))
22298 (dolist (entry (sort (copy-sequence alist)
22299 (lambda (a b) (< (length (car a)) (length (car b))))))
22300 (setq template
22301 (replace-regexp-in-string
22302 (concat "%" (regexp-quote (car entry)))
22303 (or (cdr entry) "") template t t)))
22304 template))
22306 (defun org-base-buffer (buffer)
22307 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22308 (if (not buffer)
22309 buffer
22310 (or (buffer-base-buffer buffer)
22311 buffer)))
22313 (defun org-wrap (string &optional width lines)
22314 "Wrap string to either a number of lines, or a width in characters.
22315 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22316 that costs. If there is a word longer than WIDTH, the text is actually
22317 wrapped to the length of that word.
22318 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22319 many lines, whatever width that takes.
22320 The return value is a list of lines, without newlines at the end."
22321 (let* ((words (org-split-string string "[ \t\n]+"))
22322 (maxword (apply 'max (mapcar 'org-string-width words)))
22323 w ll)
22324 (cond (width
22325 (org-do-wrap words (max maxword width)))
22326 (lines
22327 (setq w maxword)
22328 (setq ll (org-do-wrap words maxword))
22329 (if (<= (length ll) lines)
22331 (setq ll words)
22332 (while (> (length ll) lines)
22333 (setq w (1+ w))
22334 (setq ll (org-do-wrap words w)))
22335 ll))
22336 (t (error "Cannot wrap this")))))
22338 (defun org-do-wrap (words width)
22339 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22340 (let (lines line)
22341 (while words
22342 (setq line (pop words))
22343 (while (and words (< (+ (length line) (length (car words))) width))
22344 (setq line (concat line " " (pop words))))
22345 (setq lines (push line lines)))
22346 (nreverse lines)))
22348 (defun org-split-string (string &optional separators)
22349 "Splits STRING into substrings at SEPARATORS.
22350 SEPARATORS is a regular expression.
22351 No empty strings are returned if there are matches at the beginning
22352 and end of string."
22353 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22354 (let ((start 0) notfirst list)
22355 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22356 (if (and notfirst
22357 (= start (match-beginning 0))
22358 (< start (length string)))
22359 (1+ start) start))
22360 (< (match-beginning 0) (length string)))
22361 (setq notfirst t)
22362 (or (eq (match-beginning 0) 0)
22363 (and (eq (match-beginning 0) (match-end 0))
22364 (eq (match-beginning 0) start))
22365 (push (substring string start (match-beginning 0)) list))
22366 (setq start (match-end 0)))
22367 (or (eq start (length string))
22368 (push (substring string start) list))
22369 (nreverse list)))
22371 (defun org-quote-vert (s)
22372 "Replace \"|\" with \"\\vert\"."
22373 (while (string-match "|" s)
22374 (setq s (replace-match "\\vert" t t s)))
22377 (defun org-uuidgen-p (s)
22378 "Is S an ID created by UUIDGEN?"
22379 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22381 (defun org-in-src-block-p (&optional inside)
22382 "Whether point is in a code source block.
22383 When INSIDE is non-nil, don't consider we are within a src block
22384 when point is at #+BEGIN_SRC or #+END_SRC."
22385 (let ((case-fold-search t) ov)
22386 (or (and (eq (get-char-property (point) 'src-block) t))
22387 (and (not inside)
22388 (save-match-data
22389 (save-excursion
22390 (beginning-of-line)
22391 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22393 (defun org-context ()
22394 "Return a list of contexts of the current cursor position.
22395 If several contexts apply, all are returned.
22396 Each context entry is a list with a symbol naming the context, and
22397 two positions indicating start and end of the context. Possible
22398 contexts are:
22400 :headline anywhere in a headline
22401 :headline-stars on the leading stars in a headline
22402 :todo-keyword on a TODO keyword (including DONE) in a headline
22403 :tags on the TAGS in a headline
22404 :priority on the priority cookie in a headline
22405 :item on the first line of a plain list item
22406 :item-bullet on the bullet/number of a plain list item
22407 :checkbox on the checkbox in a plain list item
22408 :table in an org-mode table
22409 :table-special on a special filed in a table
22410 :table-table in a table.el table
22411 :clocktable in a clocktable
22412 :src-block in a source block
22413 :link on a hyperlink
22414 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22415 :target on a <<target>>
22416 :radio-target on a <<<radio-target>>>
22417 :latex-fragment on a LaTeX fragment
22418 :latex-preview on a LaTeX fragment with overlaid preview image
22420 This function expects the position to be visible because it uses font-lock
22421 faces as a help to recognize the following contexts: :table-special, :link,
22422 and :keyword."
22423 (let* ((f (get-text-property (point) 'face))
22424 (faces (if (listp f) f (list f)))
22425 (case-fold-search t)
22426 (p (point)) clist o)
22427 ;; First the large context
22428 (cond
22429 ((org-at-heading-p t)
22430 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22431 (when (progn
22432 (beginning-of-line 1)
22433 (looking-at org-todo-line-tags-regexp))
22434 (push (org-point-in-group p 1 :headline-stars) clist)
22435 (push (org-point-in-group p 2 :todo-keyword) clist)
22436 (push (org-point-in-group p 4 :tags) clist))
22437 (goto-char p)
22438 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22439 (if (looking-at "\\[#[A-Z0-9]\\]")
22440 (push (org-point-in-group p 0 :priority) clist)))
22442 ((org-at-item-p)
22443 (push (org-point-in-group p 2 :item-bullet) clist)
22444 (push (list :item (point-at-bol)
22445 (save-excursion (org-end-of-item) (point)))
22446 clist)
22447 (and (org-at-item-checkbox-p)
22448 (push (org-point-in-group p 0 :checkbox) clist)))
22450 ((org-at-table-p)
22451 (push (list :table (org-table-begin) (org-table-end)) clist)
22452 (if (memq 'org-formula faces)
22453 (push (list :table-special
22454 (previous-single-property-change p 'face)
22455 (next-single-property-change p 'face)) clist)))
22456 ((org-at-table-p 'any)
22457 (push (list :table-table) clist)))
22458 (goto-char p)
22460 (let ((case-fold-search t))
22461 ;; New the "medium" contexts: clocktables, source blocks
22462 (cond ((org-in-clocktable-p)
22463 (push (list :clocktable
22464 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22465 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22466 (match-beginning 1))
22467 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22468 (match-end 0))) clist))
22469 ((org-in-src-block-p)
22470 (push (list :src-block
22471 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22472 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22473 (match-beginning 1))
22474 (and (search-forward "#+END_SRC" nil t)
22475 (match-beginning 0))) clist))))
22476 (goto-char p)
22478 ;; Now the small context
22479 (cond
22480 ((org-at-timestamp-p)
22481 (push (org-point-in-group p 0 :timestamp) clist))
22482 ((memq 'org-link faces)
22483 (push (list :link
22484 (previous-single-property-change p 'face)
22485 (next-single-property-change p 'face)) clist))
22486 ((memq 'org-special-keyword faces)
22487 (push (list :keyword
22488 (previous-single-property-change p 'face)
22489 (next-single-property-change p 'face)) clist))
22490 ((org-at-target-p)
22491 (push (org-point-in-group p 0 :target) clist)
22492 (goto-char (1- (match-beginning 0)))
22493 (if (looking-at org-radio-target-regexp)
22494 (push (org-point-in-group p 0 :radio-target) clist))
22495 (goto-char p))
22496 ((setq o (car (delq nil
22497 (mapcar
22498 (lambda (x)
22499 (if (memq x org-latex-fragment-image-overlays) x))
22500 (overlays-at (point))))))
22501 (push (list :latex-fragment
22502 (overlay-start o) (overlay-end o)) clist)
22503 (push (list :latex-preview
22504 (overlay-start o) (overlay-end o)) clist))
22505 ((org-inside-LaTeX-fragment-p)
22506 ;; FIXME: positions wrong.
22507 (push (list :latex-fragment (point) (point)) clist)))
22509 (setq clist (nreverse (delq nil clist)))
22510 clist))
22512 (defun org-in-regexp (re &optional nlines visually)
22513 "Check if point is inside a match of RE.
22515 Normally only the current line is checked, but you can include
22516 NLINES extra lines after point into the search. If VISUALLY is
22517 set, require that the cursor is not after the match but really
22518 on, so that the block visually is on the match."
22519 (catch 'exit
22520 (let ((pos (point))
22521 (eol (point-at-eol (+ 1 (or nlines 0))))
22522 (inc (if visually 1 0)))
22523 (save-excursion
22524 (beginning-of-line (- 1 (or nlines 0)))
22525 (while (re-search-forward re eol t)
22526 (if (and (<= (match-beginning 0) pos)
22527 (>= (+ inc (match-end 0)) pos))
22528 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
22529 (define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp
22530 "Org mode 8.3")
22532 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22533 "Non-nil when point is between matches of START-RE and END-RE.
22535 Also return a non-nil value when point is on one of the matches.
22537 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22538 buffer positions. Default values are the positions of headlines
22539 surrounding the point.
22541 The functions returns a cons cell whose car (resp. cdr) is the
22542 position before START-RE (resp. after END-RE)."
22543 (save-match-data
22544 (let ((pos (point))
22545 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22546 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22547 beg end)
22548 (save-excursion
22549 ;; Point is on a block when on START-RE or if START-RE can be
22550 ;; found before it...
22551 (and (or (org-in-regexp start-re)
22552 (re-search-backward start-re limit-up t))
22553 (setq beg (match-beginning 0))
22554 ;; ... and END-RE after it...
22555 (goto-char (match-end 0))
22556 (re-search-forward end-re limit-down t)
22557 (> (setq end (match-end 0)) pos)
22558 ;; ... without another START-RE in-between.
22559 (goto-char (match-beginning 0))
22560 (not (re-search-backward start-re (1+ beg) t))
22561 ;; Return value.
22562 (cons beg end))))))
22564 (defun org-in-block-p (names)
22565 "Non-nil when point belongs to a block whose name belongs to NAMES.
22567 NAMES is a list of strings containing names of blocks.
22569 Return first block name matched, or nil. Beware that in case of
22570 nested blocks, the returned name may not belong to the closest
22571 block from point."
22572 (save-match-data
22573 (catch 'exit
22574 (let ((case-fold-search t)
22575 (lim-up (save-excursion (outline-previous-heading)))
22576 (lim-down (save-excursion (outline-next-heading))))
22577 (mapc (lambda (name)
22578 (let ((n (regexp-quote name)))
22579 (when (org-between-regexps-p
22580 (concat "^[ \t]*#\\+begin_" n)
22581 (concat "^[ \t]*#\\+end_" n)
22582 lim-up lim-down)
22583 (throw 'exit n))))
22584 names))
22585 nil)))
22587 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22588 "Call `multi-occur' with buffers for all agenda files."
22589 (interactive "sOrg-files matching: ")
22590 (let* ((files (org-agenda-files))
22591 (tnames (mapcar #'file-truename files))
22592 (extra org-agenda-text-search-extra-files))
22593 (when (eq (car extra) 'agenda-archives)
22594 (setq extra (cdr extra))
22595 (setq files (org-add-archive-files files)))
22596 (dolist (f extra)
22597 (unless (member (file-truename f) tnames)
22598 (unless (member f files) (setq files (append files (list f))))
22599 (setq tnames (append tnames (list (file-truename f))))))
22600 (multi-occur
22601 (mapcar (lambda (x)
22602 (with-current-buffer
22603 ;; FIXME: Why not just (find-file-noselect x)?
22604 ;; Is it to avoid the "revert buffer" prompt?
22605 (or (get-file-buffer x) (find-file-noselect x))
22606 (widen)
22607 (current-buffer)))
22608 files)
22609 regexp)))
22611 (if (boundp 'occur-mode-find-occurrence-hook)
22612 ;; Emacs 23
22613 (add-hook 'occur-mode-find-occurrence-hook
22614 (lambda ()
22615 (when (derived-mode-p 'org-mode)
22616 (org-reveal))))
22617 ;; Emacs 22
22618 (defadvice occur-mode-goto-occurrence
22619 (after org-occur-reveal activate)
22620 (and (derived-mode-p 'org-mode) (org-reveal)))
22621 (defadvice occur-mode-goto-occurrence-other-window
22622 (after org-occur-reveal activate)
22623 (and (derived-mode-p 'org-mode) (org-reveal)))
22624 (defadvice occur-mode-display-occurrence
22625 (after org-occur-reveal activate)
22626 (when (derived-mode-p 'org-mode)
22627 (let ((pos (occur-mode-find-occurrence)))
22628 (with-current-buffer (marker-buffer pos)
22629 (save-excursion
22630 (goto-char pos)
22631 (org-reveal)))))))
22633 (defun org-occur-link-in-agenda-files ()
22634 "Create a link and search for it in the agendas.
22635 The link is not stored in `org-stored-links', it is just created
22636 for the search purpose."
22637 (interactive)
22638 (let ((link (condition-case nil
22639 (org-store-link nil)
22640 (error "Unable to create a link to here"))))
22641 (org-occur-in-agenda-files (regexp-quote link))))
22643 (defun org-reverse-string (string)
22644 "Return the reverse of STRING."
22645 (apply 'string (reverse (string-to-list string))))
22647 ;; defsubst org-uniquify must be defined before first use
22649 (defun org-uniquify-alist (alist)
22650 "Merge elements of ALIST with the same key.
22652 For example, in this alist:
22654 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22655 => \\='((a 1 3) (b 2))
22657 merge (a 1) and (a 3) into (a 1 3).
22659 The function returns the new ALIST."
22660 (let (rtn)
22661 (mapc
22662 (lambda (e)
22663 (let (n)
22664 (if (not (assoc (car e) rtn))
22665 (push e rtn)
22666 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22667 (setq rtn (assq-delete-all (car e) rtn))
22668 (push n rtn))))
22669 alist)
22670 rtn))
22672 (defun org-delete-all (elts list)
22673 "Remove all elements in ELTS from LIST."
22674 (while elts
22675 (setq list (delete (pop elts) list)))
22676 list)
22678 (defun org-count (cl-item cl-seq)
22679 "Count the number of occurrences of ITEM in SEQ.
22680 Taken from `count' in cl-seq.el with all keyword arguments removed."
22681 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
22682 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
22683 (while (< cl-start cl-end)
22684 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
22685 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
22686 (setq cl-start (1+ cl-start)))
22687 cl-count))
22689 (defun org-remove-if (predicate seq)
22690 "Remove everything from SEQ that fulfills PREDICATE."
22691 (let (res e)
22692 (while seq
22693 (setq e (pop seq))
22694 (if (not (funcall predicate e)) (push e res)))
22695 (nreverse res)))
22697 (defun org-remove-if-not (predicate seq)
22698 "Remove everything from SEQ that does not fulfill PREDICATE."
22699 (let (res e)
22700 (while seq
22701 (setq e (pop seq))
22702 (if (funcall predicate e) (push e res)))
22703 (nreverse res)))
22705 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22706 "Reduce two-argument FUNCTION across SEQ.
22707 Taken from `reduce' in cl-seq.el with all keyword arguments but
22708 \":initial-value\" removed."
22709 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22710 (cadr (memq :initial-value cl-keys)))
22711 (cl-seq (pop cl-seq))
22712 (t (funcall cl-func)))))
22713 (while cl-seq
22714 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22715 cl-accum))
22717 (defun org-every (pred seq)
22718 "Return true if PREDICATE is true of every element of SEQ.
22719 Adapted from `every' in cl.el."
22720 (catch 'org-every
22721 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22724 (defun org-some (pred seq)
22725 "Return true if PREDICATE is true of any element of SEQ.
22726 Adapted from `some' in cl.el."
22727 (catch 'org-some
22728 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22729 nil))
22731 (defun org-back-over-empty-lines ()
22732 "Move backwards over whitespace, to the beginning of the first empty line.
22733 Returns the number of empty lines passed."
22734 (let ((pos (point)))
22735 (if (cdr (assoc 'heading org-blank-before-new-entry))
22736 (skip-chars-backward " \t\n\r")
22737 (unless (eobp)
22738 (forward-line -1)))
22739 (beginning-of-line 2)
22740 (goto-char (min (point) pos))
22741 (count-lines (point) pos)))
22743 (defun org-skip-whitespace ()
22744 (skip-chars-forward " \t\n\r"))
22746 (defun org-point-in-group (point group &optional context)
22747 "Check if POINT is in match-group GROUP.
22748 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22749 match. If the match group does not exist or point is not inside it,
22750 return nil."
22751 (and (match-beginning group)
22752 (>= point (match-beginning group))
22753 (<= point (match-end group))
22754 (if context
22755 (list context (match-beginning group) (match-end group))
22756 t)))
22758 (defun org-switch-to-buffer-other-window (&rest args)
22759 "Switch to buffer in a second window on the current frame.
22760 In particular, do not allow pop-up frames.
22761 Returns the newly created buffer."
22762 (org-no-popups
22763 (apply 'switch-to-buffer-other-window args)))
22765 (defun org-combine-plists (&rest plists)
22766 "Create a single property list from all plists in PLISTS.
22767 The process starts by copying the first list, and then setting properties
22768 from the other lists. Settings in the last list are the most significant
22769 ones and overrule settings in the other lists."
22770 (let ((rtn (copy-sequence (pop plists)))
22771 p v ls)
22772 (while plists
22773 (setq ls (pop plists))
22774 (while ls
22775 (setq p (pop ls) v (pop ls))
22776 (setq rtn (plist-put rtn p v))))
22777 rtn))
22779 (defun org-replace-escapes (string table)
22780 "Replace %-escapes in STRING with values in TABLE.
22781 TABLE is an association list with keys like \"%a\" and string values.
22782 The sequences in STRING may contain normal field width and padding information,
22783 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22784 so values can contain further %-escapes if they are define later in TABLE."
22785 (let ((tbl (copy-alist table))
22786 (case-fold-search nil)
22787 (pchg 0)
22788 e re rpl)
22789 (dolist (e tbl)
22790 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22791 (when (and (cdr e) (string-match re (cdr e)))
22792 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22793 (safe "SREF"))
22794 (add-text-properties 0 3 (list 'sref sref) safe)
22795 (setcdr e (replace-match safe t t (cdr e)))))
22796 (while (string-match re string)
22797 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22798 (cdr e)))
22799 (setq string (replace-match rpl t t string))))
22800 (while (setq pchg (next-property-change pchg string))
22801 (let ((sref (get-text-property pchg 'sref string)))
22802 (when (and sref (string-match "SREF" string pchg))
22803 (setq string (replace-match sref t t string)))))
22804 string))
22806 (defun org-sublist (list start end)
22807 "Return a section of LIST, from START to END.
22808 Counting starts at 1."
22809 (let (rtn (c start))
22810 (setq list (nthcdr (1- start) list))
22811 (while (and list (<= c end))
22812 (push (pop list) rtn)
22813 (setq c (1+ c)))
22814 (nreverse rtn)))
22816 (defun org-find-base-buffer-visiting (file)
22817 "Like `find-buffer-visiting' but always return the base buffer and
22818 not an indirect buffer."
22819 (let ((buf (or (get-file-buffer file)
22820 (find-buffer-visiting file))))
22821 (if buf
22822 (or (buffer-base-buffer buf) buf)
22823 nil)))
22825 (defun org-image-file-name-regexp (&optional extensions)
22826 "Return regexp matching the file names of images.
22827 If EXTENSIONS is given, only match these."
22828 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22829 (image-file-name-regexp)
22830 (let ((image-file-name-extensions
22831 (or extensions
22832 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22833 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22834 (concat "\\."
22835 (regexp-opt (nconc (mapcar 'upcase
22836 image-file-name-extensions)
22837 image-file-name-extensions)
22839 "\\'"))))
22841 (defun org-file-image-p (file &optional extensions)
22842 "Return non-nil if FILE is an image."
22843 (save-match-data
22844 (string-match (org-image-file-name-regexp extensions) file)))
22846 (defun org-get-cursor-date (&optional with-time)
22847 "Return the date at cursor in as a time.
22848 This works in the calendar and in the agenda, anywhere else it just
22849 returns the current time.
22850 If WITH-TIME is non-nil, returns the time of the event at point (in
22851 the agenda) or the current time of the day."
22852 (let (date day defd tp hod mod)
22853 (when with-time
22854 (setq tp (get-text-property (point) 'time))
22855 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22856 (setq hod (string-to-number (match-string 1 tp))
22857 mod (string-to-number (match-string 2 tp))))
22858 (or tp (let ((now (decode-time)))
22859 (setq hod (nth 2 now)
22860 mod (nth 1 now)))))
22861 (cond
22862 ((eq major-mode 'calendar-mode)
22863 (setq date (calendar-cursor-to-date)
22864 defd (encode-time 0 (or mod 0) (or hod 0)
22865 (nth 1 date) (nth 0 date) (nth 2 date))))
22866 ((eq major-mode 'org-agenda-mode)
22867 (setq day (get-text-property (point) 'day))
22868 (if day
22869 (setq date (calendar-gregorian-from-absolute day)
22870 defd (encode-time 0 (or mod 0) (or hod 0)
22871 (nth 1 date) (nth 0 date) (nth 2 date))))))
22872 (or defd (current-time))))
22874 (defun org-mark-subtree (&optional up)
22875 "Mark the current subtree.
22876 This puts point at the start of the current subtree, and mark at
22877 the end. If a numeric prefix UP is given, move up into the
22878 hierarchy of headlines by UP levels before marking the subtree."
22879 (interactive "P")
22880 (org-with-limited-levels
22881 (cond ((org-at-heading-p) (beginning-of-line))
22882 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22883 (t (outline-previous-visible-heading 1))))
22884 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22885 (if (org-called-interactively-p 'any)
22886 (call-interactively 'org-mark-element)
22887 (org-mark-element)))
22890 ;;; Indentation
22892 (defun org--get-expected-indentation (element contentsp)
22893 "Expected indentation column for current line, according to ELEMENT.
22894 ELEMENT is an element containing point. CONTENTSP is non-nil
22895 when indentation is to be computed according to contents of
22896 ELEMENT."
22897 (let ((type (org-element-type element))
22898 (start (org-element-property :begin element))
22899 (post-affiliated (org-element-property :post-affiliated element)))
22900 (org-with-wide-buffer
22901 (cond
22902 (contentsp
22903 (case type
22904 ((diary-sexp footnote-definition) 0)
22905 ((headline inlinetask nil)
22906 (if (not org-adapt-indentation) 0
22907 (let ((level (org-current-level)))
22908 (if level (1+ level) 0))))
22909 ((item plain-list) (org-list-item-body-column post-affiliated))
22911 (goto-char start)
22912 (org-get-indentation))))
22913 ((memq type '(headline inlinetask nil))
22914 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22915 (org--get-expected-indentation element t)
22917 ((memq type '(diary-sexp footnote-definition)) 0)
22918 ;; First paragraph of a footnote definition or an item.
22919 ;; Indent like parent.
22920 ((< (line-beginning-position) start)
22921 (org--get-expected-indentation
22922 (org-element-property :parent element) t))
22923 ;; At first line: indent according to previous sibling, if any,
22924 ;; ignoring footnote definitions and inline tasks, or parent's
22925 ;; contents.
22926 ((= (line-beginning-position) start)
22927 (catch 'exit
22928 (while t
22929 (if (= (point-min) start) (throw 'exit 0)
22930 (goto-char (1- start))
22931 (let* ((previous (org-element-at-point))
22932 (parent previous))
22933 (while (and parent (<= (org-element-property :end parent) start))
22934 (setq previous parent
22935 parent (org-element-property :parent parent)))
22936 (cond
22937 ((not previous) (throw 'exit 0))
22938 ((> (org-element-property :end previous) start)
22939 (throw 'exit (org--get-expected-indentation previous t)))
22940 ((memq (org-element-type previous)
22941 '(footnote-definition inlinetask))
22942 (setq start (org-element-property :begin previous)))
22943 (t (goto-char (org-element-property :begin previous))
22944 (throw 'exit
22945 (if (bolp) (org-get-indentation)
22946 ;; At first paragraph in an item or
22947 ;; a footnote definition.
22948 (org--get-expected-indentation
22949 (org-element-property :parent previous) t))))))))))
22950 ;; Otherwise, move to the first non-blank line above.
22952 (beginning-of-line)
22953 (let ((pos (point)))
22954 (skip-chars-backward " \r\t\n")
22955 (cond
22956 ;; Two blank lines end a footnote definition or a plain
22957 ;; list. When we indent an empty line after them, the
22958 ;; containing list or footnote definition is over, so it
22959 ;; qualifies as a previous sibling. Therefore, we indent
22960 ;; like its first line.
22961 ((and (memq type '(footnote-definition plain-list))
22962 (> (count-lines (point) pos) 2))
22963 (goto-char start)
22964 (org-get-indentation))
22965 ;; Line above is the first one of a paragraph at the
22966 ;; beginning of an item or a footnote definition. Indent
22967 ;; like parent.
22968 ((< (line-beginning-position) start)
22969 (org--get-expected-indentation
22970 (org-element-property :parent element) t))
22971 ;; Line above is the beginning of an element, i.e., point
22972 ;; was originally on the blank lines between element's start
22973 ;; and contents.
22974 ((= (line-beginning-position) post-affiliated)
22975 (org--get-expected-indentation element t))
22976 ;; POS is after contents in a greater element. Indent like
22977 ;; the beginning of the element.
22979 ;; As a special case, if point is at the end of a footnote
22980 ;; definition or an item, indent like the very last element
22981 ;; within.
22982 ((and (not (eq type 'paragraph))
22983 (let ((cend (org-element-property :contents-end element)))
22984 (and cend (<= cend pos))))
22985 (if (memq type '(footnote-definition item plain-list))
22986 (let ((last (org-element-at-point)))
22987 (org--get-expected-indentation
22988 last
22989 (memq (org-element-type last)
22990 '(footnote-definition item plain-list))))
22991 (goto-char start)
22992 (org-get-indentation)))
22993 ;; In any other case, indent like the current line.
22994 (t (org-get-indentation)))))))))
22996 (defun org--align-node-property ()
22997 "Align node property at point.
22998 Alignment is done according to `org-property-format', which see."
22999 (when (save-excursion
23000 (beginning-of-line)
23001 (looking-at org-property-re))
23002 (replace-match
23003 (concat (match-string 4)
23004 (org-trim
23005 (format org-property-format (match-string 1) (match-string 3))))
23006 t t)))
23008 (defun org-indent-line ()
23009 "Indent line depending on context.
23011 Indentation is done according to the following rules:
23013 - Footnote definitions, diary sexps, headlines and inline tasks
23014 have to start at column 0.
23016 - On the very first line of an element, consider, in order, the
23017 next rules until one matches:
23019 1. If there's a sibling element before, ignoring footnote
23020 definitions and inline tasks, indent like its first line.
23022 2. If element has a parent, indent like its contents. More
23023 precisely, if parent is an item, indent after the
23024 description part, if any, or the bullet (see
23025 `org-list-description-max-indent'). Else, indent like
23026 parent's first line.
23028 3. Otherwise, indent relatively to current level, if
23029 `org-adapt-indentation' is non-nil, or to left margin.
23031 - On a blank line at the end of an element, indent according to
23032 the type of the element. More precisely
23034 1. If element is a plain list, an item, or a footnote
23035 definition, indent like the very last element within.
23037 2. If element is a paragraph, indent like its last non blank
23038 line.
23040 3. Otherwise, indent like its very first line.
23042 - In the code part of a source block, use language major mode
23043 to indent current line if `org-src-tab-acts-natively' is
23044 non-nil. If it is nil, do nothing.
23046 - Otherwise, indent like the first non-blank line above.
23048 The function doesn't indent an item as it could break the whole
23049 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
23050 \\[org-shiftmetaright].
23052 Also align node properties according to `org-property-format'."
23053 (interactive)
23054 (cond
23055 (orgstruct-is-++
23056 (let ((indent-line-function
23057 (cadadr (assq 'indent-line-function org-fb-vars))))
23058 (indent-according-to-mode)))
23059 ((org-at-heading-p) 'noindent)
23061 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
23062 (type (org-element-type element)))
23063 (cond ((and (memq type '(plain-list item))
23064 (= (line-beginning-position)
23065 (org-element-property :post-affiliated element)))
23066 'noindent)
23067 ((and (eq type 'src-block)
23068 org-src-tab-acts-natively
23069 (> (line-beginning-position)
23070 (org-element-property :post-affiliated element))
23071 (< (line-beginning-position)
23072 (org-with-wide-buffer
23073 (goto-char (org-element-property :end element))
23074 (skip-chars-backward " \r\t\n")
23075 (line-beginning-position))))
23076 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
23078 (let ((column (org--get-expected-indentation element nil)))
23079 ;; Preserve current column.
23080 (if (<= (current-column) (current-indentation))
23081 (org-indent-line-to column)
23082 (save-excursion (org-indent-line-to column))))
23083 ;; Align node property. Also preserve current column.
23084 (when (eq type 'node-property)
23085 (let ((column (current-column)))
23086 (org--align-node-property)
23087 (org-move-to-column column)))))))))
23089 (defun org-indent-region (start end)
23090 "Indent each non-blank line in the region.
23091 Called from a program, START and END specify the region to
23092 indent. The function will not indent contents of example blocks,
23093 verse blocks and export blocks as leading white spaces are
23094 assumed to be significant there."
23095 (interactive "r")
23096 (save-excursion
23097 (goto-char start)
23098 (skip-chars-forward " \r\t\n")
23099 (unless (eobp) (beginning-of-line))
23100 (let ((indent-to
23101 (lambda (ind pos)
23102 ;; Set IND as indentation for all lines between point and
23103 ;; POS or END, whichever comes first. Blank lines are
23104 ;; ignored. Leave point after POS once done.
23105 (let ((limit (copy-marker (min end pos))))
23106 (while (< (point) limit)
23107 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
23108 (forward-line))
23109 (set-marker limit nil))))
23110 (end (copy-marker end)))
23111 (while (< (point) end)
23112 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23113 (let* ((element (org-element-at-point))
23114 (type (org-element-type element))
23115 (element-end (copy-marker (org-element-property :end element)))
23116 (ind (org--get-expected-indentation element nil)))
23117 (cond
23118 ((or (memq type '(paragraph table table-row))
23119 (not (or (org-element-property :contents-begin element)
23120 (memq type
23121 '(example-block export-block src-block)))))
23122 ;; Elements here are indented as a single block. Also
23123 ;; align node properties.
23124 (when (eq type 'node-property)
23125 (org--align-node-property)
23126 (beginning-of-line))
23127 (funcall indent-to ind element-end))
23129 ;; Elements in this category consist of three parts:
23130 ;; before the contents, the contents, and after the
23131 ;; contents. The contents are treated specially,
23132 ;; according to the element type, or not indented at
23133 ;; all. Other parts are indented as a single block.
23134 (let* ((post (copy-marker
23135 (org-element-property :post-affiliated element)))
23136 (cbeg
23137 (copy-marker
23138 (cond
23139 ((not (org-element-property :contents-begin element))
23140 ;; Fake contents for source blocks.
23141 (org-with-wide-buffer
23142 (goto-char post)
23143 (forward-line)
23144 (point)))
23145 ((memq type '(footnote-definition item plain-list))
23146 ;; Contents in these elements could start on
23147 ;; the same line as the beginning of the
23148 ;; element. Make sure we start indenting
23149 ;; from the second line.
23150 (org-with-wide-buffer
23151 (goto-char post)
23152 (end-of-line)
23153 (skip-chars-forward " \r\t\n")
23154 (if (eobp) (point) (line-beginning-position))))
23155 (t (org-element-property :contents-begin element)))))
23156 (cend (copy-marker
23157 (or (org-element-property :contents-end element)
23158 ;; Fake contents for source blocks.
23159 (org-with-wide-buffer
23160 (goto-char element-end)
23161 (skip-chars-backward " \r\t\n")
23162 (line-beginning-position)))
23163 t)))
23164 ;; Do not change items indentation individually as it
23165 ;; might break the list as a whole. On the other
23166 ;; hand, when at a plain list, indent it as a whole.
23167 (cond ((eq type 'plain-list)
23168 (let ((offset (- ind (org-get-indentation))))
23169 (unless (zerop offset)
23170 (indent-rigidly (org-element-property :begin element)
23171 (org-element-property :end element)
23172 offset))
23173 (goto-char cbeg)))
23174 ((eq type 'item) (goto-char cbeg))
23175 (t (funcall indent-to ind cbeg)))
23176 (when (< (point) end)
23177 (case type
23178 ((example-block export-block verse-block))
23179 (src-block
23180 ;; In a source block, indent source code
23181 ;; according to language major mode, but only if
23182 ;; `org-src-tab-acts-natively' is non-nil.
23183 (when (and (< (point) end) org-src-tab-acts-natively)
23184 (ignore-errors
23185 (org-babel-do-in-edit-buffer
23186 (indent-region (point-min) (point-max))))))
23187 (t (org-indent-region (point) (min cend end))))
23188 (goto-char (min cend end))
23189 (when (< (point) end) (funcall indent-to ind element-end)))
23190 (set-marker post nil)
23191 (set-marker cbeg nil)
23192 (set-marker cend nil))))
23193 (set-marker element-end nil))))
23194 (set-marker end nil))))
23196 (defun org-indent-drawer ()
23197 "Indent the drawer at point."
23198 (interactive)
23199 (unless (save-excursion
23200 (beginning-of-line)
23201 (org-looking-at-p org-drawer-regexp))
23202 (user-error "Not at a drawer"))
23203 (let ((element (org-element-at-point)))
23204 (unless (memq (org-element-type element) '(drawer property-drawer))
23205 (user-error "Not at a drawer"))
23206 (org-with-wide-buffer
23207 (org-indent-region (org-element-property :begin element)
23208 (org-element-property :end element))))
23209 (message "Drawer at point indented"))
23211 (defun org-indent-block ()
23212 "Indent the block at point."
23213 (interactive)
23214 (unless (save-excursion
23215 (beginning-of-line)
23216 (let ((case-fold-search t))
23217 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23218 (user-error "Not at a block"))
23219 (let ((element (org-element-at-point)))
23220 (unless (memq (org-element-type element)
23221 '(comment-block center-block dynamic-block example-block
23222 export-block quote-block special-block
23223 src-block verse-block))
23224 (user-error "Not at a block"))
23225 (org-with-wide-buffer
23226 (org-indent-region (org-element-property :begin element)
23227 (org-element-property :end element))))
23228 (message "Block at point indented"))
23231 ;;; Filling
23233 ;; We use our own fill-paragraph and auto-fill functions.
23235 ;; `org-fill-paragraph' relies on adaptive filling and context
23236 ;; checking. Appropriate `fill-prefix' is computed with
23237 ;; `org-adaptive-fill-function'.
23239 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23240 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23241 ;; `org-adaptive-fill-function' value. Internally,
23242 ;; `org-comment-line-break-function' breaks the line.
23244 ;; `org-setup-filling' installs filling and auto-filling related
23245 ;; variables during `org-mode' initialization.
23247 (defvar org-element-paragraph-separate) ; org-element.el
23248 (defun org-setup-filling ()
23249 (require 'org-element)
23250 ;; Prevent auto-fill from inserting unwanted new items.
23251 (when (boundp 'fill-nobreak-predicate)
23252 (org-set-local
23253 'fill-nobreak-predicate
23254 (org-uniquify
23255 (append fill-nobreak-predicate
23256 '(org-fill-line-break-nobreak-p
23257 org-fill-paragraph-with-timestamp-nobreak-p)))))
23258 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23259 (org-set-local 'paragraph-start paragraph-ending)
23260 (org-set-local 'paragraph-separate paragraph-ending))
23261 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
23262 (org-set-local 'auto-fill-inhibit-regexp nil)
23263 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
23264 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
23265 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
23267 (defun org-fill-line-break-nobreak-p ()
23268 "Non-nil when a new line at point would create an Org line break."
23269 (save-excursion
23270 (skip-chars-backward "[ \t]")
23271 (skip-chars-backward "\\\\")
23272 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23274 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23275 "Non-nil when a new line at point would split a timestamp."
23276 (and (org-at-timestamp-p t)
23277 (not (looking-at org-ts-regexp-both))))
23279 (declare-function message-in-body-p "message" ())
23280 (defvar orgtbl-line-start-regexp) ; From org-table.el
23281 (defun org-adaptive-fill-function ()
23282 "Compute a fill prefix for the current line.
23283 Return fill prefix, as a string, or nil if current line isn't
23284 meant to be filled. For convenience, if `adaptive-fill-regexp'
23285 matches in paragraphs or comments, use it."
23286 (catch 'exit
23287 (when (derived-mode-p 'message-mode)
23288 (save-excursion
23289 (beginning-of-line)
23290 (cond ((not (message-in-body-p)) (throw 'exit nil))
23291 ((org-looking-at-p org-table-line-regexp) (throw 'exit nil))
23292 ((looking-at message-cite-prefix-regexp)
23293 (throw 'exit (match-string-no-properties 0)))
23294 ((looking-at org-outline-regexp)
23295 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23296 (org-with-wide-buffer
23297 (unless (org-at-heading-p)
23298 (let* ((p (line-beginning-position))
23299 (element (save-excursion
23300 (beginning-of-line)
23301 (org-element-at-point)))
23302 (type (org-element-type element))
23303 (post-affiliated (org-element-property :post-affiliated element)))
23304 (unless (< p post-affiliated)
23305 (case type
23306 (comment
23307 (save-excursion
23308 (beginning-of-line)
23309 (looking-at "[ \t]*")
23310 (concat (match-string 0) "# ")))
23311 (footnote-definition "")
23312 ((item plain-list)
23313 (make-string (org-list-item-body-column post-affiliated) ?\s))
23314 (paragraph
23315 ;; Fill prefix is usually the same as the current line,
23316 ;; unless the paragraph is at the beginning of an item.
23317 (let ((parent (org-element-property :parent element)))
23318 (save-excursion
23319 (beginning-of-line)
23320 (cond ((eq (org-element-type parent) 'item)
23321 (make-string (org-list-item-body-column
23322 (org-element-property :begin parent))
23323 ?\s))
23324 ((and adaptive-fill-regexp
23325 ;; Locally disable
23326 ;; `adaptive-fill-function' to let
23327 ;; `fill-context-prefix' handle
23328 ;; `adaptive-fill-regexp' variable.
23329 (let (adaptive-fill-function)
23330 (fill-context-prefix
23331 post-affiliated
23332 (org-element-property :end element)))))
23333 ((looking-at "[ \t]+") (match-string 0))
23334 (t "")))))
23335 (comment-block
23336 ;; Only fill contents if P is within block boundaries.
23337 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23338 (forward-line)
23339 (point)))
23340 (cend (save-excursion
23341 (goto-char (org-element-property :end element))
23342 (skip-chars-backward " \r\t\n")
23343 (line-beginning-position))))
23344 (when (and (>= p cbeg) (< p cend))
23345 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23346 (match-string 0)
23347 "")))))))))))
23349 (declare-function message-goto-body "message" ())
23350 (defvar message-cite-prefix-regexp) ; From message.el
23351 (defun org-fill-paragraph (&optional justify)
23352 "Fill element at point, when applicable.
23354 This function only applies to comment blocks, comments, example
23355 blocks and paragraphs. Also, as a special case, re-align table
23356 when point is at one.
23358 If JUSTIFY is non-nil (interactively, with prefix argument),
23359 justify as well. If `sentence-end-double-space' is non-nil, then
23360 period followed by one space does not end a sentence, so don't
23361 break a line there. The variable `fill-column' controls the
23362 width for filling.
23364 For convenience, when point is at a plain list, an item or
23365 a footnote definition, try to fill the first paragraph within."
23366 (interactive)
23367 (if (and (derived-mode-p 'message-mode)
23368 (or (not (message-in-body-p))
23369 (save-excursion (move-beginning-of-line 1)
23370 (looking-at message-cite-prefix-regexp))))
23371 ;; First ensure filling is correct in message-mode.
23372 (let ((fill-paragraph-function
23373 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
23374 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
23375 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
23376 (paragraph-separate
23377 (cadadr (assoc 'paragraph-separate org-fb-vars))))
23378 (fill-paragraph nil))
23379 (with-syntax-table org-mode-transpose-word-syntax-table
23380 ;; Move to end of line in order to get the first paragraph
23381 ;; within a plain list or a footnote definition.
23382 (let ((element (save-excursion
23383 (end-of-line)
23384 (or (ignore-errors (org-element-at-point))
23385 (user-error "An element cannot be parsed line %d"
23386 (line-number-at-pos (point)))))))
23387 ;; First check if point is in a blank line at the beginning of
23388 ;; the buffer. In that case, ignore filling.
23389 (case (org-element-type element)
23390 ;; Use major mode filling function is src blocks.
23391 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23392 ;; Align Org tables, leave table.el tables as-is.
23393 (table-row (org-table-align) t)
23394 (table
23395 (when (eq (org-element-property :type element) 'org)
23396 (save-excursion
23397 (goto-char (org-element-property :post-affiliated element))
23398 (org-table-align)))
23400 (paragraph
23401 ;; Paragraphs may contain `line-break' type objects.
23402 (let ((beg (max (point-min)
23403 (org-element-property :contents-begin element)))
23404 (end (min (point-max)
23405 (org-element-property :contents-end element))))
23406 ;; Do nothing if point is at an affiliated keyword.
23407 (if (< (line-end-position) beg) t
23408 (when (derived-mode-p 'message-mode)
23409 ;; In `message-mode', do not fill following citation
23410 ;; in current paragraph nor text before message body.
23411 (let ((body-start (save-excursion (message-goto-body))))
23412 (when body-start (setq beg (max body-start beg))))
23413 (when (save-excursion
23414 (re-search-forward
23415 (concat "^" message-cite-prefix-regexp) end t))
23416 (setq end (match-beginning 0))))
23417 ;; Fill paragraph, taking line breaks into account.
23418 (save-excursion
23419 (goto-char beg)
23420 (let ((cuts (list beg)))
23421 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23422 (when (eq 'line-break
23423 (org-element-type
23424 (save-excursion (backward-char)
23425 (org-element-context))))
23426 (push (point) cuts)))
23427 (dolist (c (delq end cuts))
23428 (fill-region-as-paragraph c end justify)
23429 (setq end c))))
23430 t)))
23431 ;; Contents of `comment-block' type elements should be
23432 ;; filled as plain text, but only if point is within block
23433 ;; markers.
23434 (comment-block
23435 (let* ((case-fold-search t)
23436 (beg (save-excursion
23437 (goto-char (org-element-property :begin element))
23438 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23439 (forward-line)
23440 (point)))
23441 (end (save-excursion
23442 (goto-char (org-element-property :end element))
23443 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23444 (line-beginning-position))))
23445 (if (or (< (point) beg) (> (point) end)) t
23446 (fill-region-as-paragraph
23447 (save-excursion (end-of-line)
23448 (re-search-backward "^[ \t]*$" beg 'move)
23449 (line-beginning-position))
23450 (save-excursion (beginning-of-line)
23451 (re-search-forward "^[ \t]*$" end 'move)
23452 (line-beginning-position))
23453 justify))))
23454 ;; Fill comments.
23455 (comment
23456 (let ((begin (org-element-property :post-affiliated element))
23457 (end (org-element-property :end element)))
23458 (when (and (>= (point) begin) (<= (point) end))
23459 (let ((begin (save-excursion
23460 (end-of-line)
23461 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23462 (progn (forward-line) (point))
23463 begin)))
23464 (end (save-excursion
23465 (end-of-line)
23466 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23467 (1- (line-beginning-position))
23468 (skip-chars-backward " \r\t\n")
23469 (line-end-position)))))
23470 ;; Do not fill comments when at a blank line.
23471 (when (> end begin)
23472 (let ((fill-prefix
23473 (save-excursion
23474 (beginning-of-line)
23475 (looking-at "[ \t]*#")
23476 (let ((comment-prefix (match-string 0)))
23477 (goto-char (match-end 0))
23478 (if (looking-at adaptive-fill-regexp)
23479 (concat comment-prefix (match-string 0))
23480 (concat comment-prefix " "))))))
23481 (save-excursion
23482 (fill-region-as-paragraph begin end justify))))))
23484 ;; Ignore every other element.
23485 (otherwise t))))))
23487 (defun org-auto-fill-function ()
23488 "Auto-fill function."
23489 ;; Check if auto-filling is meaningful.
23490 (let ((fc (current-fill-column)))
23491 (when (and fc (> (current-column) fc))
23492 (let* ((fill-prefix (org-adaptive-fill-function))
23493 ;; Enforce empty fill prefix, if required. Otherwise, it
23494 ;; will be computed again.
23495 (adaptive-fill-mode (not (equal fill-prefix ""))))
23496 (when fill-prefix (do-auto-fill))))))
23498 (defun org-comment-line-break-function (&optional soft)
23499 "Break line at point and indent, continuing comment if within one.
23500 The inserted newline is marked hard if variable
23501 `use-hard-newlines' is true, unless optional argument SOFT is
23502 non-nil."
23503 (if soft (insert-and-inherit ?\n) (newline 1))
23504 (save-excursion (forward-char -1) (delete-horizontal-space))
23505 (delete-horizontal-space)
23506 (indent-to-left-margin)
23507 (insert-before-markers-and-inherit fill-prefix))
23510 ;;; Fixed Width Areas
23512 (defun org-toggle-fixed-width ()
23513 "Toggle fixed-width markup.
23515 Add or remove fixed-width markup on current line, whenever it
23516 makes sense. Return an error otherwise.
23518 If a region is active and if it contains only fixed-width areas
23519 or blank lines, remove all fixed-width markup in it. If the
23520 region contains anything else, convert all non-fixed-width lines
23521 to fixed-width ones.
23523 Blank lines at the end of the region are ignored unless the
23524 region only contains such lines."
23525 (interactive)
23526 (if (not (org-region-active-p))
23527 ;; No region:
23529 ;; Remove fixed width marker only in a fixed-with element.
23531 ;; Add fixed width maker in paragraphs, in blank lines after
23532 ;; elements or at the beginning of a headline or an inlinetask,
23533 ;; and before any one-line elements (e.g., a clock).
23534 (progn
23535 (beginning-of-line)
23536 (let* ((element (org-element-at-point))
23537 (type (org-element-type element)))
23538 (cond
23539 ((and (eq type 'fixed-width)
23540 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23541 (replace-match
23542 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23543 ((and (memq type '(babel-call clock comment diary-sexp headline
23544 horizontal-rule keyword paragraph
23545 planning))
23546 (<= (org-element-property :post-affiliated element) (point)))
23547 (skip-chars-forward " \t")
23548 (insert ": "))
23549 ((and (org-looking-at-p "[ \t]*$")
23550 (or (eq type 'inlinetask)
23551 (save-excursion
23552 (skip-chars-forward " \r\t\n")
23553 (<= (org-element-property :end element) (point)))))
23554 (delete-region (point) (line-end-position))
23555 (org-indent-line)
23556 (insert ": "))
23557 (t (user-error "Cannot insert a fixed-width line here")))))
23558 ;; Region active.
23559 (let* ((begin (save-excursion
23560 (goto-char (region-beginning))
23561 (line-beginning-position)))
23562 (end (copy-marker
23563 (save-excursion
23564 (goto-char (region-end))
23565 (unless (eolp) (beginning-of-line))
23566 (if (save-excursion (re-search-backward "\\S-" begin t))
23567 (progn (skip-chars-backward " \r\t\n") (point))
23568 (point)))))
23569 (all-fixed-width-p
23570 (catch 'not-all-p
23571 (save-excursion
23572 (goto-char begin)
23573 (skip-chars-forward " \r\t\n")
23574 (when (eobp) (throw 'not-all-p nil))
23575 (while (< (point) end)
23576 (let ((element (org-element-at-point)))
23577 (if (eq (org-element-type element) 'fixed-width)
23578 (goto-char (org-element-property :end element))
23579 (throw 'not-all-p nil))))
23580 t))))
23581 (if all-fixed-width-p
23582 (save-excursion
23583 (goto-char begin)
23584 (while (< (point) end)
23585 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23586 (replace-match
23587 "" nil nil nil
23588 (if (= (line-end-position) (match-end 0)) 0 1)))
23589 (forward-line)))
23590 (let ((min-ind (point-max)))
23591 ;; Find minimum indentation across all lines.
23592 (save-excursion
23593 (goto-char begin)
23594 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23595 (setq min-ind 0)
23596 (catch 'zerop
23597 (while (< (point) end)
23598 (unless (org-looking-at-p "[ \t]*$")
23599 (let ((ind (org-get-indentation)))
23600 (setq min-ind (min min-ind ind))
23601 (when (zerop ind) (throw 'zerop t))))
23602 (forward-line)))))
23603 ;; Loop over all lines and add fixed-width markup everywhere
23604 ;; but in fixed-width lines.
23605 (save-excursion
23606 (goto-char begin)
23607 (while (< (point) end)
23608 (cond
23609 ((org-at-heading-p)
23610 (insert ": ")
23611 (forward-line)
23612 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23613 (insert ":")
23614 (forward-line)))
23615 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23616 (let* ((element (org-element-at-point))
23617 (element-end (org-element-property :end element)))
23618 (if (eq (org-element-type element) 'fixed-width)
23619 (progn (goto-char element-end)
23620 (skip-chars-backward " \r\t\n")
23621 (forward-line))
23622 (let ((limit (min end element-end)))
23623 (while (< (point) limit)
23624 (org-move-to-column min-ind t)
23625 (insert ": ")
23626 (forward-line))))))
23628 (org-move-to-column min-ind t)
23629 (insert ": ")
23630 (forward-line)))))))
23631 (set-marker end nil))))
23634 ;;; Comments
23636 ;; Org comments syntax is quite complex. It requires the entire line
23637 ;; to be just a comment. Also, even with the right syntax at the
23638 ;; beginning of line, some some elements (i.e. verse-block or
23639 ;; example-block) don't accept comments. Usual Emacs comment commands
23640 ;; cannot cope with those requirements. Therefore, Org replaces them.
23642 ;; Org still relies on `comment-dwim', but cannot trust
23643 ;; `comment-only-p'. So, `comment-region-function' and
23644 ;; `uncomment-region-function' both point
23645 ;; to`org-comment-or-uncomment-region'. Eventually,
23646 ;; `org-insert-comment' takes care of insertion of comments at the
23647 ;; beginning of line.
23649 ;; `org-setup-comments-handling' install comments related variables
23650 ;; during `org-mode' initialization.
23652 (defun org-setup-comments-handling ()
23653 (interactive)
23654 (org-set-local 'comment-use-syntax nil)
23655 (org-set-local 'comment-start "# ")
23656 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23657 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
23658 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
23659 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
23661 (defun org-insert-comment ()
23662 "Insert an empty comment above current line.
23663 If the line is empty, insert comment at its beginning. When
23664 point is within a source block, comment according to the related
23665 major mode."
23666 (if (let ((element (org-element-at-point)))
23667 (and (eq (org-element-type element) 'src-block)
23668 (< (save-excursion
23669 (goto-char (org-element-property :post-affiliated element))
23670 (line-end-position))
23671 (point))
23672 (> (save-excursion
23673 (goto-char (org-element-property :end element))
23674 (skip-chars-backward " \r\t\n")
23675 (line-beginning-position))
23676 (point))))
23677 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23678 (beginning-of-line)
23679 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23680 (open-line 1))
23681 (org-indent-line)
23682 (insert "# ")))
23684 (defvar comment-empty-lines) ; From newcomment.el.
23685 (defun org-comment-or-uncomment-region (beg end &rest _)
23686 "Comment or uncomment each non-blank line in the region.
23687 Uncomment each non-blank line between BEG and END if it only
23688 contains commented lines. Otherwise, comment them. If region is
23689 strictly within a source block, use appropriate comment syntax."
23690 (if (let ((element (org-element-at-point)))
23691 (and (eq (org-element-type element) 'src-block)
23692 (< (save-excursion
23693 (goto-char (org-element-property :post-affiliated element))
23694 (line-end-position))
23695 beg)
23696 (>= (save-excursion
23697 (goto-char (org-element-property :end element))
23698 (skip-chars-backward " \r\t\n")
23699 (line-beginning-position))
23700 end)))
23701 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23702 (save-restriction
23703 ;; Restrict region
23704 (narrow-to-region (save-excursion (goto-char beg)
23705 (skip-chars-forward " \r\t\n" end)
23706 (line-beginning-position))
23707 (save-excursion (goto-char end)
23708 (skip-chars-backward " \r\t\n" beg)
23709 (line-end-position)))
23710 (let ((uncommentp
23711 ;; UNCOMMENTP is non-nil when every non blank line between
23712 ;; BEG and END is a comment.
23713 (save-excursion
23714 (goto-char (point-min))
23715 (while (and (not (eobp))
23716 (let ((element (org-element-at-point)))
23717 (and (eq (org-element-type element) 'comment)
23718 (goto-char (min (point-max)
23719 (org-element-property
23720 :end element)))))))
23721 (eobp))))
23722 (if uncommentp
23723 ;; Only blank lines and comments in region: uncomment it.
23724 (save-excursion
23725 (goto-char (point-min))
23726 (while (not (eobp))
23727 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23728 (replace-match "" nil nil nil 1))
23729 (forward-line)))
23730 ;; Comment each line in region.
23731 (let ((min-indent (point-max)))
23732 ;; First find the minimum indentation across all lines.
23733 (save-excursion
23734 (goto-char (point-min))
23735 (while (and (not (eobp)) (not (zerop min-indent)))
23736 (unless (looking-at "[ \t]*$")
23737 (setq min-indent (min min-indent (current-indentation))))
23738 (forward-line)))
23739 ;; Then loop over all lines.
23740 (save-excursion
23741 (goto-char (point-min))
23742 (while (not (eobp))
23743 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23744 ;; Don't get fooled by invisible text (e.g. link path)
23745 ;; when moving to column MIN-INDENT.
23746 (let ((buffer-invisibility-spec nil))
23747 (org-move-to-column min-indent t))
23748 (insert comment-start))
23749 (forward-line)))))))))
23751 (defun org-comment-dwim (arg)
23752 "Call `comment-dwim' within a source edit buffer if needed."
23753 (interactive "*P")
23754 (if (org-in-src-block-p)
23755 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23756 (call-interactively 'comment-dwim)))
23759 ;;; Timestamps API
23761 ;; This section contains tools to operate on timestamp objects, as
23762 ;; returned by, e.g. `org-element-context'.
23764 (defun org-timestamp--to-internal-time (timestamp &optional end)
23765 "Encode TIMESTAMP object into Emacs internal time.
23766 Use end of date range or time range when END is non-nil."
23767 (apply #'encode-time
23768 (cons 0
23769 (mapcar
23770 (lambda (prop) (or (org-element-property prop timestamp) 0))
23771 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23772 '(:minute-start :hour-start :day-start :month-start
23773 :year-start))))))
23775 (defun org-timestamp-has-time-p (timestamp)
23776 "Non-nil when TIMESTAMP has a time specified."
23777 (org-element-property :hour-start timestamp))
23779 (defun org-timestamp-format (timestamp format &optional end utc)
23780 "Format a TIMESTAMP object into a string.
23782 FORMAT is a format specifier to be passed to
23783 `format-time-string'.
23785 When optional argument END is non-nil, use end of date-range or
23786 time-range, if possible.
23788 When optional argument UTC is non-nil, time will be expressed as
23789 Universal Time."
23790 (format-time-string
23791 format (org-timestamp--to-internal-time timestamp end) utc))
23793 (defun org-timestamp-split-range (timestamp &optional end)
23794 "Extract a TIMESTAMP object from a date or time range.
23796 END, when non-nil, means extract the end of the range.
23797 Otherwise, extract its start.
23799 Return a new timestamp object."
23800 (let ((type (org-element-property :type timestamp)))
23801 (if (memq type '(active inactive diary)) timestamp
23802 (let ((split-ts (org-element-copy timestamp)))
23803 ;; Set new type.
23804 (org-element-put-property
23805 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23806 ;; Copy start properties over end properties if END is
23807 ;; non-nil. Otherwise, copy end properties over `start' ones.
23808 (let ((p-alist '((:minute-start . :minute-end)
23809 (:hour-start . :hour-end)
23810 (:day-start . :day-end)
23811 (:month-start . :month-end)
23812 (:year-start . :year-end))))
23813 (dolist (p-cell p-alist)
23814 (org-element-put-property
23815 split-ts
23816 (funcall (if end #'car #'cdr) p-cell)
23817 (org-element-property
23818 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23819 ;; Eventually refresh `:raw-value'.
23820 (org-element-put-property split-ts :raw-value nil)
23821 (org-element-put-property
23822 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23824 (defun org-timestamp-translate (timestamp &optional boundary)
23825 "Translate TIMESTAMP object to custom format.
23827 Format string is defined in `org-time-stamp-custom-formats',
23828 which see.
23830 When optional argument BOUNDARY is non-nil, it is either the
23831 symbol `start' or `end'. In this case, only translate the
23832 starting or ending part of TIMESTAMP if it is a date or time
23833 range. Otherwise, translate both parts.
23835 Return timestamp as-is if `org-display-custom-times' is nil or if
23836 it has a `diary' type."
23837 (let ((type (org-element-property :type timestamp)))
23838 (if (or (not org-display-custom-times) (eq type 'diary))
23839 (org-element-interpret-data timestamp)
23840 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23841 org-time-stamp-custom-formats)))
23842 (if (and (not boundary) (memq type '(active-range inactive-range)))
23843 (concat (org-timestamp-format timestamp fmt)
23844 "--"
23845 (org-timestamp-format timestamp fmt t))
23846 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23850 ;;; Other stuff.
23852 (defvar reftex-docstruct-symbol)
23853 (defvar reftex-cite-format)
23854 (defvar org--rds)
23856 (defun org-reftex-citation ()
23857 "Use reftex-citation to insert a citation into the buffer.
23858 This looks for a line like
23860 #+BIBLIOGRAPHY: foo plain option:-d
23862 and derives from it that foo.bib is the bibliography file relevant
23863 for this document. It then installs the necessary environment for RefTeX
23864 to work in this buffer and calls `reftex-citation' to insert a citation
23865 into the buffer.
23867 Export of such citations to both LaTeX and HTML is handled by the contributed
23868 package ox-bibtex by Taru Karttunen."
23869 (interactive)
23870 (let ((reftex-docstruct-symbol 'org--rds)
23871 (reftex-cite-format "\\cite{%l}")
23872 org--rds bib)
23873 (save-excursion
23874 (save-restriction
23875 (widen)
23876 (let ((case-fold-search t)
23877 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23878 (if (not (save-excursion
23879 (or (re-search-forward re nil t)
23880 (re-search-backward re nil t))))
23881 (user-error "No bibliography defined in file")
23882 (setq bib (concat (match-string 1) ".bib")
23883 org--rds (list (list 'bib bib)))))))
23884 (call-interactively 'reftex-citation)))
23886 ;;;; Functions extending outline functionality
23888 (defun org-beginning-of-line (&optional arg)
23889 "Go to the beginning of the current line. If that is invisible, continue
23890 to a visible line beginning. This makes the function of C-a more intuitive.
23891 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23892 first attempt, and only move to after the tags when the cursor is already
23893 beyond the end of the headline."
23894 (interactive "P")
23895 (let ((pos (point))
23896 (special (if (consp org-special-ctrl-a/e)
23897 (car org-special-ctrl-a/e)
23898 org-special-ctrl-a/e))
23899 deactivate-mark refpos)
23900 (if (org-bound-and-true-p visual-line-mode)
23901 (beginning-of-visual-line 1)
23902 (beginning-of-line 1))
23903 (if (and arg (fboundp 'move-beginning-of-line))
23904 (call-interactively 'move-beginning-of-line)
23905 (if (bobp)
23907 (backward-char 1)
23908 (if (org-truely-invisible-p)
23909 (while (and (not (bobp)) (org-truely-invisible-p))
23910 (backward-char 1)
23911 (beginning-of-line 1))
23912 (forward-char 1))))
23913 (when special
23914 (cond
23915 ((and (looking-at org-complex-heading-regexp)
23916 (eq (char-after (match-end 1)) ?\s))
23917 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23918 (point-at-eol)))
23919 (goto-char
23920 (if (eq special t)
23921 (cond ((> pos refpos) refpos)
23922 ((= pos (point)) refpos)
23923 (t (point)))
23924 (cond ((> pos (point)) (point))
23925 ((not (eq last-command this-command)) (point))
23926 (t refpos)))))
23927 ((org-at-item-p)
23928 ;; Being at an item and not looking at an the item means point
23929 ;; was previously moved to beginning of a visual line, which
23930 ;; doesn't contain the item. Therefore, do nothing special,
23931 ;; just stay here.
23932 (when (looking-at org-list-full-item-re)
23933 ;; Set special position at first white space character after
23934 ;; bullet, and check-box, if any.
23935 (let ((after-bullet
23936 (let ((box (match-end 3)))
23937 (if (not box) (match-end 1)
23938 (let ((after (char-after box)))
23939 (if (and after (= after ? )) (1+ box) box))))))
23940 ;; Special case: Move point to special position when
23941 ;; currently after it or at beginning of line.
23942 (if (eq special t)
23943 (when (or (> pos after-bullet) (= (point) pos))
23944 (goto-char after-bullet))
23945 ;; Reversed case: Move point to special position when
23946 ;; point was already at beginning of line and command is
23947 ;; repeated.
23948 (when (and (= (point) pos) (eq last-command this-command))
23949 (goto-char after-bullet))))))))
23950 (org-no-warnings
23951 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23952 (setq disable-point-adjustment
23953 (or (not (invisible-p (point)))
23954 (not (invisible-p (max (point-min) (1- (point))))))))
23956 (defun org-end-of-line (&optional arg)
23957 "Go to the end of the line.
23958 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23959 tags on the first attempt, and only move to after the tags when
23960 the cursor is already beyond the end of the headline."
23961 (interactive "P")
23962 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23963 org-special-ctrl-a/e))
23964 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23965 'end-of-visual-line)
23966 ((fboundp 'move-end-of-line) 'move-end-of-line)
23967 (t 'end-of-line)))
23968 deactivate-mark)
23969 (if (or (not special) arg) (call-interactively move-fun)
23970 (let* ((element (save-excursion (beginning-of-line)
23971 (org-element-at-point)))
23972 (type (org-element-type element)))
23973 (cond
23974 ((memq type '(headline inlinetask))
23975 (let ((pos (point)))
23976 (beginning-of-line 1)
23977 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23978 (if (eq special t)
23979 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23980 (goto-char (match-beginning 1))
23981 (goto-char (match-end 0)))
23982 (if (or (< pos (match-end 0))
23983 (not (eq this-command last-command)))
23984 (goto-char (match-end 0))
23985 (goto-char (match-beginning 1))))
23986 (call-interactively move-fun))))
23987 ((outline-invisible-p (line-end-position))
23988 ;; If element is hidden, `move-end-of-line' would put point
23989 ;; after it. Use `end-of-line' to stay on current line.
23990 (call-interactively 'end-of-line))
23991 (t (call-interactively move-fun)))))
23992 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23993 (setq disable-point-adjustment
23994 (or (not (invisible-p (point)))
23995 (not (invisible-p (max (point-min) (1- (point))))))))
23997 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23998 (define-key org-mode-map "\C-e" 'org-end-of-line)
24000 (defun org-backward-sentence (&optional _arg)
24001 "Go to beginning of sentence, or beginning of table field.
24002 This will call `backward-sentence' or `org-table-beginning-of-field',
24003 depending on context."
24004 (interactive)
24005 (let* ((element (org-element-at-point))
24006 (contents-begin (org-element-property :contents-begin element))
24007 (table (org-element-lineage element '(table) t)))
24008 (if (and table
24009 (> (point) contents-begin)
24010 (<= (point) (org-element-property :contents-end table)))
24011 (call-interactively #'org-table-beginning-of-field)
24012 (save-restriction
24013 (when (and contents-begin
24014 (< (point-min) contents-begin)
24015 (> (point) contents-begin))
24016 (narrow-to-region contents-begin
24017 (org-element-property :contents-end element)))
24018 (call-interactively #'backward-sentence)))))
24020 (defun org-forward-sentence (&optional _arg)
24021 "Go to end of sentence, or end of table field.
24022 This will call `forward-sentence' or `org-table-end-of-field',
24023 depending on context."
24024 (interactive)
24025 (let* ((element (org-element-at-point))
24026 (contents-end (org-element-property :contents-end element))
24027 (table (org-element-lineage element '(table) t)))
24028 (if (and table
24029 (>= (point) (org-element-property :contents-begin table))
24030 (< (point) contents-end))
24031 (call-interactively #'org-table-end-of-field)
24032 (save-restriction
24033 (when (and contents-end
24034 (> (point-max) contents-end)
24035 ;; Skip blank lines between elements.
24036 (< (org-element-property :end element)
24037 (save-excursion (goto-char contents-end)
24038 (skip-chars-forward " \r\t\n"))))
24039 (narrow-to-region (org-element-property :contents-begin element)
24040 contents-end))
24041 (call-interactively #'forward-sentence)))))
24043 (define-key org-mode-map "\M-a" 'org-backward-sentence)
24044 (define-key org-mode-map "\M-e" 'org-forward-sentence)
24046 (defun org-kill-line (&optional _arg)
24047 "Kill line, to tags or end of line."
24048 (interactive)
24049 (cond
24050 ((or (not org-special-ctrl-k)
24051 (bolp)
24052 (not (org-at-heading-p)))
24053 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
24054 org-ctrl-k-protect-subtree)
24055 (if (or (eq org-ctrl-k-protect-subtree 'error)
24056 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
24057 (user-error "C-k aborted as it would kill a hidden subtree")))
24058 (call-interactively
24059 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
24060 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
24061 (kill-region (point) (match-beginning 1))
24062 (org-set-tags nil t))
24063 (t (kill-region (point) (point-at-eol)))))
24065 (define-key org-mode-map "\C-k" 'org-kill-line)
24067 (defun org-yank (&optional arg)
24068 "Yank. If the kill is a subtree, treat it specially.
24069 This command will look at the current kill and check if is a single
24070 subtree, or a series of subtrees[1]. If it passes the test, and if the
24071 cursor is at the beginning of a line or after the stars of a currently
24072 empty headline, then the yank is handled specially. How exactly depends
24073 on the value of the following variables, both set by default.
24075 `org-yank-folded-subtrees'
24076 When set, the subtree(s) will be folded after insertion, but only
24077 if doing so would now swallow text after the yanked text.
24079 `org-yank-adjusted-subtrees'
24080 When set, the subtree will be promoted or demoted in order to
24081 fit into the local outline tree structure, which means that the
24082 level will be adjusted so that it becomes the smaller one of the
24083 two *visible* surrounding headings.
24085 Any prefix to this command will cause `yank' to be called directly with
24086 no special treatment. In particular, a simple \\[universal-argument] prefix \
24087 will just
24088 plainly yank the text as it is.
24090 \[1] The test checks if the first non-white line is a heading
24091 and if there are no other headings with fewer stars."
24092 (interactive "P")
24093 (org-yank-generic 'yank arg))
24095 (defun org-yank-generic (command arg)
24096 "Perform some yank-like command.
24098 This function implements the behavior described in the `org-yank'
24099 documentation. However, it has been generalized to work for any
24100 interactive command with similar behavior."
24102 ;; pretend to be command COMMAND
24103 (setq this-command command)
24105 (if arg
24106 (call-interactively command)
24108 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24109 (and (org-kill-is-subtree-p)
24110 (or (bolp)
24111 (and (looking-at "[ \t]*$")
24112 (string-match
24113 "\\`\\*+\\'"
24114 (buffer-substring (point-at-bol) (point)))))))
24115 swallowp)
24116 (cond
24117 ((and subtreep org-yank-folded-subtrees)
24118 (let ((beg (point))
24119 end)
24120 (if (and subtreep org-yank-adjusted-subtrees)
24121 (org-paste-subtree nil nil 'for-yank)
24122 (call-interactively command))
24124 (setq end (point))
24125 (goto-char beg)
24126 (when (and (bolp) subtreep
24127 (not (setq swallowp
24128 (org-yank-folding-would-swallow-text beg end))))
24129 (org-with-limited-levels
24130 (or (looking-at org-outline-regexp)
24131 (re-search-forward org-outline-regexp-bol end t))
24132 (while (and (< (point) end) (looking-at org-outline-regexp))
24133 (outline-hide-subtree)
24134 (org-cycle-show-empty-lines 'folded)
24135 (condition-case nil
24136 (outline-forward-same-level 1)
24137 (error (goto-char end))))))
24138 (when swallowp
24139 (message
24140 "Inserted text not folded because that would swallow text"))
24142 (goto-char end)
24143 (skip-chars-forward " \t\n\r")
24144 (beginning-of-line 1)
24145 (push-mark beg 'nomsg)))
24146 ((and subtreep org-yank-adjusted-subtrees)
24147 (let ((beg (point-at-bol)))
24148 (org-paste-subtree nil nil 'for-yank)
24149 (push-mark beg 'nomsg)))
24151 (call-interactively command))))))
24153 (defun org-yank-folding-would-swallow-text (beg end)
24154 "Would hide-subtree at BEG swallow any text after END?"
24155 (let (level)
24156 (org-with-limited-levels
24157 (save-excursion
24158 (goto-char beg)
24159 (when (or (looking-at org-outline-regexp)
24160 (re-search-forward org-outline-regexp-bol end t))
24161 (setq level (org-outline-level)))
24162 (goto-char end)
24163 (skip-chars-forward " \t\r\n\v\f")
24164 (if (or (eobp)
24165 (and (bolp) (looking-at org-outline-regexp)
24166 (<= (org-outline-level) level)))
24167 nil ; Nothing would be swallowed
24168 t))))) ; something would swallow
24170 (define-key org-mode-map "\C-y" 'org-yank)
24172 (defun org-truely-invisible-p ()
24173 "Check if point is at a character currently not visible.
24174 This version does not only check the character property, but also
24175 `visible-mode'."
24176 ;; Early versions of noutline don't have `outline-invisible-p'.
24177 (if (org-bound-and-true-p visible-mode)
24179 (outline-invisible-p)))
24181 (defun org-invisible-p2 ()
24182 "Check if point is at a character currently not visible."
24183 (save-excursion
24184 (if (and (eolp) (not (bobp))) (backward-char 1))
24185 ;; Early versions of noutline don't have `outline-invisible-p'.
24186 (outline-invisible-p)))
24188 (defun org-back-to-heading (&optional invisible-ok)
24189 "Call `outline-back-to-heading', but provide a better error message."
24190 (condition-case nil
24191 (outline-back-to-heading invisible-ok)
24192 (error (error "Before first headline at position %d in buffer %s"
24193 (point) (current-buffer)))))
24195 (defun org-before-first-heading-p ()
24196 "Before first heading?"
24197 (save-excursion
24198 (end-of-line)
24199 (null (re-search-backward org-outline-regexp-bol nil t))))
24201 (defun org-at-heading-p (&optional ignored)
24202 (outline-on-heading-p t))
24203 ;; Compatibility alias with Org versions < 7.8.03
24204 (defalias 'org-on-heading-p 'org-at-heading-p)
24206 (defun org-in-commented-heading-p (&optional no-inheritance)
24207 "Non-nil if point is under a commented heading.
24208 This function also checks ancestors of the current headline,
24209 unless optional argument NO-INHERITANCE is non-nil."
24210 (cond
24211 ((org-before-first-heading-p) nil)
24212 ((let ((headline (nth 4 (org-heading-components))))
24213 (and headline
24214 (let ((case-fold-search nil))
24215 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24216 headline)))))
24217 (no-inheritance nil)
24219 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24221 (defun org-at-comment-p nil
24222 "Is cursor in a commented line?"
24223 (save-excursion
24224 (save-match-data
24225 (beginning-of-line)
24226 (looking-at "^[ \t]*# "))))
24228 (defun org-at-drawer-p nil
24229 "Is cursor at a drawer keyword?"
24230 (save-excursion
24231 (move-beginning-of-line 1)
24232 (looking-at org-drawer-regexp)))
24234 (defun org-at-block-p nil
24235 "Is cursor at a block keyword?"
24236 (save-excursion
24237 (move-beginning-of-line 1)
24238 (looking-at org-block-regexp)))
24240 (defun org-point-at-end-of-empty-headline ()
24241 "If point is at the end of an empty headline, return t, else nil.
24242 If the heading only contains a TODO keyword, it is still still considered
24243 empty."
24244 (and (looking-at "[ \t]*$")
24245 (when org-todo-line-regexp
24246 (save-excursion
24247 (beginning-of-line 1)
24248 (let ((case-fold-search nil))
24249 (looking-at org-todo-line-regexp)
24250 (string= (match-string 3) ""))))))
24252 (defun org-at-heading-or-item-p ()
24253 (or (org-at-heading-p) (org-at-item-p)))
24255 (defun org-at-target-p ()
24256 (or (org-in-regexp org-radio-target-regexp)
24257 (org-in-regexp org-target-regexp)))
24258 ;; Compatibility alias with Org versions < 7.8.03
24259 (defalias 'org-on-target-p 'org-at-target-p)
24261 (defun org-up-heading-all (arg)
24262 "Move to the heading line of which the present line is a subheading.
24263 This function considers both visible and invisible heading lines.
24264 With argument, move up ARG levels."
24265 (if (fboundp 'outline-up-heading-all)
24266 (outline-up-heading-all arg) ; emacs 21 version of outline.el
24267 (outline-up-heading arg t))) ; emacs 22 version of outline.el
24269 (defun org-up-heading-safe ()
24270 "Move to the heading line of which the present line is a subheading.
24271 This version will not throw an error. It will return the level of the
24272 headline found, or nil if no higher level is found.
24274 Also, this function will be a lot faster than `outline-up-heading',
24275 because it relies on stars being the outline starters. This can really
24276 make a significant difference in outlines with very many siblings."
24277 (when (ignore-errors (org-back-to-heading t))
24278 (let ((level-up (1- (funcall outline-level))))
24279 (and (> level-up 0)
24280 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24281 (funcall outline-level)))))
24283 (defun org-first-sibling-p ()
24284 "Is this heading the first child of its parents?"
24285 (interactive)
24286 (let ((re org-outline-regexp-bol)
24287 level l)
24288 (unless (org-at-heading-p t)
24289 (user-error "Not at a heading"))
24290 (setq level (funcall outline-level))
24291 (save-excursion
24292 (if (not (re-search-backward re nil t))
24294 (setq l (funcall outline-level))
24295 (< l level)))))
24297 (defun org-goto-sibling (&optional previous)
24298 "Goto the next sibling, even if it is invisible.
24299 When PREVIOUS is set, go to the previous sibling instead. Returns t
24300 when a sibling was found. When none is found, return nil and don't
24301 move point."
24302 (let ((fun (if previous 're-search-backward 're-search-forward))
24303 (pos (point))
24304 (re org-outline-regexp-bol)
24305 level l)
24306 (when (ignore-errors (org-back-to-heading t))
24307 (setq level (funcall outline-level))
24308 (catch 'exit
24309 (or previous (forward-char 1))
24310 (while (funcall fun re nil t)
24311 (setq l (funcall outline-level))
24312 (when (< l level) (goto-char pos) (throw 'exit nil))
24313 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24314 (goto-char pos)
24315 nil))))
24317 (defun org-show-siblings ()
24318 "Show all siblings of the current headline."
24319 (save-excursion
24320 (while (org-goto-sibling) (org-flag-heading nil)))
24321 (save-excursion
24322 (while (org-goto-sibling 'previous)
24323 (org-flag-heading nil))))
24325 (defun org-goto-first-child ()
24326 "Goto the first child, even if it is invisible.
24327 Return t when a child was found. Otherwise don't move point and
24328 return nil."
24329 (let (level (pos (point)) (re org-outline-regexp-bol))
24330 (when (ignore-errors (org-back-to-heading t))
24331 (setq level (outline-level))
24332 (forward-char 1)
24333 (if (and (re-search-forward re nil t) (> (outline-level) level))
24334 (progn (goto-char (match-beginning 0)) t)
24335 (goto-char pos) nil))))
24337 (defun org-show-hidden-entry ()
24338 "Show an entry where even the heading is hidden."
24339 (save-excursion
24340 (org-show-entry)))
24342 (defun org-flag-heading (flag &optional entry)
24343 "Flag the current heading. FLAG non-nil means make invisible.
24344 When ENTRY is non-nil, show the entire entry."
24345 (save-excursion
24346 (org-back-to-heading t)
24347 ;; Check if we should show the entire entry
24348 (if entry
24349 (progn
24350 (org-show-entry)
24351 (save-excursion
24352 (and (outline-next-heading)
24353 (org-flag-heading nil))))
24354 (outline-flag-region (max (point-min) (1- (point)))
24355 (save-excursion (outline-end-of-heading) (point))
24356 flag))))
24358 (defun org-get-next-sibling ()
24359 "Move to next heading of the same level, and return point.
24360 If there is no such heading, return nil.
24361 This is like outline-next-sibling, but invisible headings are ok."
24362 (let ((level (funcall outline-level)))
24363 (outline-next-heading)
24364 (while (and (not (eobp)) (> (funcall outline-level) level))
24365 (outline-next-heading))
24366 (if (or (eobp) (< (funcall outline-level) level))
24368 (point))))
24370 (defun org-get-last-sibling ()
24371 "Move to previous heading of the same level, and return point.
24372 If there is no such heading, return nil."
24373 (let ((opoint (point))
24374 (level (funcall outline-level)))
24375 (outline-previous-heading)
24376 (when (and (/= (point) opoint) (outline-on-heading-p t))
24377 (while (and (> (funcall outline-level) level)
24378 (not (bobp)))
24379 (outline-previous-heading))
24380 (if (< (funcall outline-level) level)
24382 (point)))))
24384 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24385 "Goto to the end of a subtree."
24386 ;; This contains an exact copy of the original function, but it uses
24387 ;; `org-back-to-heading', to make it work also in invisible
24388 ;; trees. And is uses an invisible-ok argument.
24389 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24390 ;; Furthermore, when used inside Org, finding the end of a large subtree
24391 ;; with many children and grandchildren etc, this can be much faster
24392 ;; than the outline version.
24393 (org-back-to-heading invisible-ok)
24394 (let ((first t)
24395 (level (funcall outline-level)))
24396 (if (and (derived-mode-p 'org-mode) (< level 1000))
24397 ;; A true heading (not a plain list item), in Org-mode
24398 ;; This means we can easily find the end by looking
24399 ;; only for the right number of stars. Using a regexp to do
24400 ;; this is so much faster than using a Lisp loop.
24401 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24402 (forward-char 1)
24403 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24404 ;; something else, do it the slow way
24405 (while (and (not (eobp))
24406 (or first (> (funcall outline-level) level)))
24407 (setq first nil)
24408 (outline-next-heading)))
24409 (unless to-heading
24410 (if (memq (preceding-char) '(?\n ?\^M))
24411 (progn
24412 ;; Go to end of line before heading
24413 (forward-char -1)
24414 (if (memq (preceding-char) '(?\n ?\^M))
24415 ;; leave blank line before heading
24416 (forward-char -1))))))
24417 (point))
24419 (defun org-end-of-meta-data (&optional full)
24420 "Skip planning line and properties drawer in current entry.
24421 When optional argument FULL is non-nil, also skip empty lines,
24422 clocking lines and regular drawers at the beginning of the
24423 entry."
24424 (org-back-to-heading t)
24425 (forward-line)
24426 (when (org-looking-at-p org-planning-line-re) (forward-line))
24427 (when (looking-at org-property-drawer-re)
24428 (goto-char (match-end 0))
24429 (forward-line))
24430 (when (and full (not (org-at-heading-p)))
24431 (catch 'exit
24432 (let ((end (save-excursion (outline-next-heading) (point)))
24433 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24434 (while (not (eobp))
24435 (cond ((org-looking-at-p org-drawer-regexp)
24436 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24437 (forward-line)
24438 (throw 'exit t)))
24439 ((org-looking-at-p re) (forward-line))
24440 (t (throw 'exit t))))))))
24442 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24443 "Move forward to the ARG'th subheading at same level as this one.
24444 Stop at the first and last subheadings of a superior heading.
24445 Normally this only looks at visible headings, but when INVISIBLE-OK is
24446 non-nil it will also look at invisible ones."
24447 (interactive "p")
24448 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24449 (if (and arg (< arg 0))
24450 (goto-char (point-min))
24451 (outline-next-heading))
24452 (org-at-heading-p)
24453 (let ((level (- (match-end 0) (match-beginning 0) 1))
24454 (f (if (and arg (< arg 0))
24455 're-search-backward
24456 're-search-forward))
24457 (count (if arg (abs arg) 1))
24458 (result (point)))
24459 (while (and (prog1 (> count 0)
24460 (forward-char (if (and arg (< arg 0)) -1 1)))
24461 (funcall f org-outline-regexp-bol nil 'move))
24462 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24463 (cond ((< l level) (setq count 0))
24464 ((and (= l level)
24465 (or invisible-ok
24466 (progn
24467 (goto-char (line-beginning-position))
24468 (not (outline-invisible-p)))))
24469 (setq count (1- count))
24470 (when (eq l level)
24471 (setq result (point)))))))
24472 (goto-char result))
24473 (beginning-of-line 1)))
24475 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24476 "Move backward to the ARG'th subheading at same level as this one.
24477 Stop at the first and last subheadings of a superior heading."
24478 (interactive "p")
24479 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24481 (defun org-next-visible-heading (arg)
24482 "Move to the next visible heading.
24484 This function wraps `outline-next-visible-heading' with
24485 `org-with-limited-levels' in order to skip over inline tasks and
24486 respect customization of `org-odd-levels-only'."
24487 (interactive "p")
24488 (org-with-limited-levels
24489 (outline-next-visible-heading arg)))
24491 (defun org-previous-visible-heading (arg)
24492 "Move to the next visible heading.
24494 This function wraps `outline-previous-visible-heading' with
24495 `org-with-limited-levels' in order to skip over inline tasks and
24496 respect customization of `org-odd-levels-only'."
24497 (interactive "p")
24498 (org-with-limited-levels
24499 (outline-previous-visible-heading arg)))
24501 (defun org-next-block (arg &optional backward block-regexp)
24502 "Jump to the next block.
24504 With a prefix argument ARG, jump forward ARG many blocks.
24506 When BACKWARD is non-nil, jump to the previous block.
24508 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24509 Match data is set according to this regexp when the function
24510 returns.
24512 Return point at beginning of the opening line of found block.
24513 Throw an error if no block is found."
24514 (interactive "p")
24515 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24516 (case-fold-search t)
24517 (search-fn (if backward #'re-search-backward #'re-search-forward))
24518 (count (or arg 1))
24519 (origin (point))
24520 last-element)
24521 (if backward (beginning-of-line) (end-of-line))
24522 (while (and (> count 0) (funcall search-fn re nil t))
24523 (let ((element (save-excursion
24524 (goto-char (match-beginning 0))
24525 (save-match-data (org-element-at-point)))))
24526 (when (and (memq (org-element-type element)
24527 '(center-block comment-block dynamic-block
24528 example-block export-block quote-block
24529 special-block src-block verse-block))
24530 (<= (match-beginning 0)
24531 (org-element-property :post-affiliated element)))
24532 (setq last-element element)
24533 (decf count))))
24534 (if (= count 0)
24535 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24536 (save-match-data (org-show-context)))
24537 (goto-char origin)
24538 (user-error "No %s code blocks" (if backward "previous" "further")))))
24540 (defun org-previous-block (arg &optional block-regexp)
24541 "Jump to the previous block.
24542 With a prefix argument ARG, jump backward ARG many source blocks.
24543 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24544 (interactive "p")
24545 (org-next-block arg t block-regexp))
24547 (defun org-forward-paragraph ()
24548 "Move forward to beginning of next paragraph or equivalent.
24550 The function moves point to the beginning of the next visible
24551 structural element, which can be a paragraph, a table, a list
24552 item, etc. It also provides some special moves for convenience:
24554 - On an affiliated keyword, jump to the beginning of the
24555 relative element.
24556 - On an item or a footnote definition, move to the second
24557 element inside, if any.
24558 - On a table or a property drawer, jump after it.
24559 - On a verse or source block, stop after blank lines."
24560 (interactive)
24561 (when (eobp) (user-error "Cannot move further down"))
24562 (let* ((deactivate-mark nil)
24563 (element (org-element-at-point))
24564 (type (org-element-type element))
24565 (post-affiliated (org-element-property :post-affiliated element))
24566 (contents-begin (org-element-property :contents-begin element))
24567 (contents-end (org-element-property :contents-end element))
24568 (end (let ((end (org-element-property :end element)) (parent element))
24569 (while (and (setq parent (org-element-property :parent parent))
24570 (= (org-element-property :contents-end parent) end))
24571 (setq end (org-element-property :end parent)))
24572 end)))
24573 (cond ((not element)
24574 (skip-chars-forward " \r\t\n")
24575 (or (eobp) (beginning-of-line)))
24576 ;; On affiliated keywords, move to element's beginning.
24577 ((< (point) post-affiliated)
24578 (goto-char post-affiliated))
24579 ;; At a table row, move to the end of the table. Similarly,
24580 ;; at a node property, move to the end of the property
24581 ;; drawer.
24582 ((memq type '(node-property table-row))
24583 (goto-char (org-element-property
24584 :end (org-element-property :parent element))))
24585 ((memq type '(property-drawer table)) (goto-char end))
24586 ;; Consider blank lines as separators in verse and source
24587 ;; blocks to ease editing.
24588 ((memq type '(src-block verse-block))
24589 (when (eq type 'src-block)
24590 (setq contents-end
24591 (save-excursion (goto-char end)
24592 (skip-chars-backward " \r\t\n")
24593 (line-beginning-position))))
24594 (beginning-of-line)
24595 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24596 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24597 (goto-char end)
24598 (skip-chars-forward " \r\t\n")
24599 (if (= (point) contents-end) (goto-char end)
24600 (beginning-of-line))))
24601 ;; With no contents, just skip element.
24602 ((not contents-begin) (goto-char end))
24603 ;; If contents are invisible, skip the element altogether.
24604 ((outline-invisible-p (line-end-position))
24605 (case type
24606 (headline
24607 (org-with-limited-levels (outline-next-visible-heading 1)))
24608 ;; At a plain list, make sure we move to the next item
24609 ;; instead of skipping the whole list.
24610 (plain-list (forward-char)
24611 (org-forward-paragraph))
24612 (otherwise (goto-char end))))
24613 ((>= (point) contents-end) (goto-char end))
24614 ((>= (point) contents-begin)
24615 ;; This can only happen on paragraphs and plain lists.
24616 (case type
24617 (paragraph (goto-char end))
24618 ;; At a plain list, try to move to second element in
24619 ;; first item, if possible.
24620 (plain-list (end-of-line)
24621 (org-forward-paragraph))))
24622 ;; When contents start on the middle of a line (e.g. in
24623 ;; items and footnote definitions), try to reach first
24624 ;; element starting after current line.
24625 ((> (line-end-position) contents-begin)
24626 (end-of-line)
24627 (org-forward-paragraph))
24628 (t (goto-char contents-begin)))))
24630 (defun org-backward-paragraph ()
24631 "Move backward to start of previous paragraph or equivalent.
24633 The function moves point to the beginning of the current
24634 structural element, which can be a paragraph, a table, a list
24635 item, etc., or to the beginning of the previous visible one if
24636 point is already there. It also provides some special moves for
24637 convenience:
24639 - On an affiliated keyword, jump to the first one.
24640 - On a table or a property drawer, move to its beginning.
24641 - On a verse or source block, stop before blank lines."
24642 (interactive)
24643 (when (bobp) (user-error "Cannot move further up"))
24644 (let* ((deactivate-mark nil)
24645 (element (org-element-at-point))
24646 (type (org-element-type element))
24647 (contents-begin (org-element-property :contents-begin element))
24648 (contents-end (org-element-property :contents-end element))
24649 (post-affiliated (org-element-property :post-affiliated element))
24650 (begin (org-element-property :begin element)))
24651 (cond
24652 ((not element) (goto-char (point-min)))
24653 ((= (point) begin)
24654 (backward-char)
24655 (org-backward-paragraph))
24656 ((<= (point) post-affiliated) (goto-char begin))
24657 ((memq type '(node-property table-row))
24658 (goto-char (org-element-property
24659 :post-affiliated (org-element-property :parent element))))
24660 ((memq type '(property-drawer table)) (goto-char begin))
24661 ((memq type '(src-block verse-block))
24662 (when (eq type 'src-block)
24663 (setq contents-begin
24664 (save-excursion (goto-char begin) (forward-line) (point))))
24665 (if (= (point) contents-begin) (goto-char post-affiliated)
24666 ;; Inside a verse block, see blank lines as paragraph
24667 ;; separators.
24668 (let ((origin (point)))
24669 (skip-chars-backward " \r\t\n" contents-begin)
24670 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24671 (skip-chars-forward " \r\t\n" origin)
24672 (if (= (point) origin) (goto-char contents-begin)
24673 (beginning-of-line))))))
24674 ((not contents-begin) (goto-char (or post-affiliated begin)))
24675 ((eq type 'paragraph)
24676 (goto-char contents-begin)
24677 ;; When at first paragraph in an item or a footnote definition,
24678 ;; move directly to beginning of line.
24679 (let ((parent-contents
24680 (org-element-property
24681 :contents-begin (org-element-property :parent element))))
24682 (when (and parent-contents (= parent-contents contents-begin))
24683 (beginning-of-line))))
24684 ;; At the end of a greater element, move to the beginning of the
24685 ;; last element within.
24686 ((>= (point) contents-end)
24687 (goto-char (1- contents-end))
24688 (org-backward-paragraph))
24689 (t (goto-char (or post-affiliated begin))))
24690 ;; Ensure we never leave point invisible.
24691 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24693 (defun org-forward-element ()
24694 "Move forward by one element.
24695 Move to the next element at the same level, when possible."
24696 (interactive)
24697 (cond ((eobp) (user-error "Cannot move further down"))
24698 ((org-with-limited-levels (org-at-heading-p))
24699 (let ((origin (point)))
24700 (goto-char (org-end-of-subtree nil t))
24701 (unless (org-with-limited-levels (org-at-heading-p))
24702 (goto-char origin)
24703 (user-error "Cannot move further down"))))
24705 (let* ((elem (org-element-at-point))
24706 (end (org-element-property :end elem))
24707 (parent (org-element-property :parent elem)))
24708 (cond ((and parent (= (org-element-property :contents-end parent) end))
24709 (goto-char (org-element-property :end parent)))
24710 ((integer-or-marker-p end) (goto-char end))
24711 (t (message "No element at point")))))))
24713 (defun org-backward-element ()
24714 "Move backward by one element.
24715 Move to the previous element at the same level, when possible."
24716 (interactive)
24717 (cond ((bobp) (user-error "Cannot move further up"))
24718 ((org-with-limited-levels (org-at-heading-p))
24719 ;; At a headline, move to the previous one, if any, or stay
24720 ;; here.
24721 (let ((origin (point)))
24722 (org-with-limited-levels (org-backward-heading-same-level 1))
24723 ;; When current headline has no sibling above, move to its
24724 ;; parent.
24725 (when (= (point) origin)
24726 (or (org-with-limited-levels (org-up-heading-safe))
24727 (progn (goto-char origin)
24728 (user-error "Cannot move further up"))))))
24730 (let* ((elem (org-element-at-point))
24731 (beg (org-element-property :begin elem)))
24732 (cond
24733 ;; Move to beginning of current element if point isn't
24734 ;; there already.
24735 ((null beg) (message "No element at point"))
24736 ((/= (point) beg) (goto-char beg))
24737 (t (goto-char beg)
24738 (skip-chars-backward " \r\t\n")
24739 (unless (bobp)
24740 (let ((prev (org-element-at-point)))
24741 (goto-char (org-element-property :begin prev))
24742 (while (and (setq prev (org-element-property :parent prev))
24743 (<= (org-element-property :end prev) beg))
24744 (goto-char (org-element-property :begin prev)))))))))))
24746 (defun org-up-element ()
24747 "Move to upper element."
24748 (interactive)
24749 (if (org-with-limited-levels (org-at-heading-p))
24750 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24751 (let* ((elem (org-element-at-point))
24752 (parent (org-element-property :parent elem)))
24753 (if parent (goto-char (org-element-property :begin parent))
24754 (if (org-with-limited-levels (org-before-first-heading-p))
24755 (user-error "No surrounding element")
24756 (org-with-limited-levels (org-back-to-heading)))))))
24758 (defvar org-element-greater-elements)
24759 (defun org-down-element ()
24760 "Move to inner element."
24761 (interactive)
24762 (let ((element (org-element-at-point)))
24763 (cond
24764 ((memq (org-element-type element) '(plain-list table))
24765 (goto-char (org-element-property :contents-begin element))
24766 (forward-char))
24767 ((memq (org-element-type element) org-element-greater-elements)
24768 ;; If contents are hidden, first disclose them.
24769 (when (outline-invisible-p (line-end-position)) (org-cycle))
24770 (goto-char (or (org-element-property :contents-begin element)
24771 (user-error "No content for this element"))))
24772 (t (user-error "No inner element")))))
24774 (defun org-drag-element-backward ()
24775 "Move backward element at point."
24776 (interactive)
24777 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24778 (let* ((elem (org-element-at-point))
24779 (prev-elem
24780 (save-excursion
24781 (goto-char (org-element-property :begin elem))
24782 (skip-chars-backward " \r\t\n")
24783 (unless (bobp)
24784 (let* ((beg (org-element-property :begin elem))
24785 (prev (org-element-at-point))
24786 (up prev))
24787 (while (and (setq up (org-element-property :parent up))
24788 (<= (org-element-property :end up) beg))
24789 (setq prev up))
24790 prev)))))
24791 ;; Error out if no previous element or previous element is
24792 ;; a parent of the current one.
24793 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24794 (user-error "Cannot drag element backward")
24795 (let ((pos (point)))
24796 (org-element-swap-A-B prev-elem elem)
24797 (goto-char (+ (org-element-property :begin prev-elem)
24798 (- pos (org-element-property :begin elem)))))))))
24800 (defun org-drag-element-forward ()
24801 "Move forward element at point."
24802 (interactive)
24803 (let* ((pos (point))
24804 (elem (org-element-at-point)))
24805 (when (= (point-max) (org-element-property :end elem))
24806 (user-error "Cannot drag element forward"))
24807 (goto-char (org-element-property :end elem))
24808 (let ((next-elem (org-element-at-point)))
24809 (when (or (org-element-nested-p elem next-elem)
24810 (and (eq (org-element-type next-elem) 'headline)
24811 (not (eq (org-element-type elem) 'headline))))
24812 (goto-char pos)
24813 (user-error "Cannot drag element forward"))
24814 ;; Compute new position of point: it's shifted by NEXT-ELEM
24815 ;; body's length (without final blanks) and by the length of
24816 ;; blanks between ELEM and NEXT-ELEM.
24817 (let ((size-next (- (save-excursion
24818 (goto-char (org-element-property :end next-elem))
24819 (skip-chars-backward " \r\t\n")
24820 (forward-line)
24821 ;; Small correction if buffer doesn't end
24822 ;; with a newline character.
24823 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24824 (org-element-property :begin next-elem)))
24825 (size-blank (- (org-element-property :end elem)
24826 (save-excursion
24827 (goto-char (org-element-property :end elem))
24828 (skip-chars-backward " \r\t\n")
24829 (forward-line)
24830 (point)))))
24831 (org-element-swap-A-B elem next-elem)
24832 (goto-char (+ pos size-next size-blank))))))
24834 (defun org-drag-line-forward (arg)
24835 "Drag the line at point ARG lines forward."
24836 (interactive "p")
24837 (dotimes (n (abs arg))
24838 (let ((c (current-column)))
24839 (if (< 0 arg)
24840 (progn
24841 (beginning-of-line 2)
24842 (transpose-lines 1)
24843 (beginning-of-line 0))
24844 (transpose-lines 1)
24845 (beginning-of-line -1))
24846 (org-move-to-column c))))
24848 (defun org-drag-line-backward (arg)
24849 "Drag the line at point ARG lines backward."
24850 (interactive "p")
24851 (org-drag-line-forward (- arg)))
24853 (defun org-mark-element ()
24854 "Put point at beginning of this element, mark at end.
24856 Interactively, if this command is repeated or (in Transient Mark
24857 mode) if the mark is active, it marks the next element after the
24858 ones already marked."
24859 (interactive)
24860 (let (deactivate-mark)
24861 (if (and (org-called-interactively-p 'any)
24862 (or (and (eq last-command this-command) (mark t))
24863 (and transient-mark-mode mark-active)))
24864 (set-mark
24865 (save-excursion
24866 (goto-char (mark))
24867 (goto-char (org-element-property :end (org-element-at-point)))))
24868 (let ((element (org-element-at-point)))
24869 (end-of-line)
24870 (push-mark (org-element-property :end element) t t)
24871 (goto-char (org-element-property :begin element))))))
24873 (defun org-narrow-to-element ()
24874 "Narrow buffer to current element."
24875 (interactive)
24876 (let ((elem (org-element-at-point)))
24877 (cond
24878 ((eq (car elem) 'headline)
24879 (narrow-to-region
24880 (org-element-property :begin elem)
24881 (org-element-property :end elem)))
24882 ((memq (car elem) org-element-greater-elements)
24883 (narrow-to-region
24884 (org-element-property :contents-begin elem)
24885 (org-element-property :contents-end elem)))
24887 (narrow-to-region
24888 (org-element-property :begin elem)
24889 (org-element-property :end elem))))))
24891 (defun org-transpose-element ()
24892 "Transpose current and previous elements, keeping blank lines between.
24893 Point is moved after both elements."
24894 (interactive)
24895 (org-skip-whitespace)
24896 (let ((end (org-element-property :end (org-element-at-point))))
24897 (org-drag-element-backward)
24898 (goto-char end)))
24900 (defun org-unindent-buffer ()
24901 "Un-indent the visible part of the buffer.
24902 Relative indentation (between items, inside blocks, etc.) isn't
24903 modified."
24904 (interactive)
24905 (unless (eq major-mode 'org-mode)
24906 (user-error "Cannot un-indent a buffer not in Org mode"))
24907 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
24908 unindent-tree ; For byte-compiler.
24909 (unindent-tree
24910 (function
24911 (lambda (contents)
24912 (mapc
24913 (lambda (element)
24914 (if (memq (org-element-type element) '(headline section))
24915 (funcall unindent-tree (org-element-contents element))
24916 (save-excursion
24917 (save-restriction
24918 (narrow-to-region
24919 (org-element-property :begin element)
24920 (org-element-property :end element))
24921 (org-do-remove-indentation)))))
24922 (reverse contents))))))
24923 (funcall unindent-tree (org-element-contents parse-tree))))
24925 (defun org-show-children (&optional level)
24926 "Show all direct subheadings of this heading.
24927 Prefix arg LEVEL is how many levels below the current level
24928 should be shown. Default is enough to cause the following
24929 heading to appear."
24930 (interactive "p")
24931 (save-excursion
24932 (org-back-to-heading t)
24933 (let* ((current-level (funcall outline-level))
24934 (max-level (org-get-valid-level
24935 current-level (if level (prefix-numeric-value level) 1)))
24936 (end (save-excursion (org-end-of-subtree t t)))
24937 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24938 (past-first-child nil)
24939 ;; Make sure to skip inlinetasks.
24940 (re (format regexp-fmt
24941 current-level
24942 (cond
24943 ((not (featurep 'org-inlinetask)) "")
24944 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24946 (t (1- org-inlinetask-min-level))))))
24947 ;; Display parent heading.
24948 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24949 (forward-line)
24950 ;; Display children. First child may be deeper than expected
24951 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24952 ;; MAX-LEVEL accordingly.
24953 (while (re-search-forward re end t)
24954 (unless past-first-child
24955 (setq re (format regexp-fmt
24956 current-level
24957 (max (funcall outline-level) max-level)))
24958 (setq past-first-child t))
24959 (outline-flag-region (line-end-position 0) (line-end-position) nil)))))
24961 (defun org-show-subtree ()
24962 "Show everything after this heading at deeper levels."
24963 (interactive)
24964 (outline-flag-region
24965 (point)
24966 (save-excursion
24967 (org-end-of-subtree t t))
24968 nil))
24970 (defun org-show-entry ()
24971 "Show the body directly following this heading.
24972 Show the heading too, if it is currently invisible."
24973 (interactive)
24974 (save-excursion
24975 (ignore-errors
24976 (org-back-to-heading t)
24977 (outline-flag-region
24978 (max (point-min) (1- (point)))
24979 (save-excursion
24980 (if (re-search-forward
24981 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24982 (match-beginning 1)
24983 (point-max)))
24984 nil)
24985 (org-cycle-hide-drawers 'children))))
24987 (defun org-make-options-regexp (kwds &optional extra)
24988 "Make a regular expression for keyword lines.
24989 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24990 when non-nil, is a regexp matching keywords names."
24991 (concat "^[ \t]*#\\+\\("
24992 (regexp-opt kwds)
24993 (and extra (concat (and kwds "\\|") extra))
24994 "\\):[ \t]*\\(.*\\)"))
24996 ;; Make isearch reveal the necessary context
24997 (defun org-isearch-end ()
24998 "Reveal context after isearch exits."
24999 (when isearch-success ; only if search was successful
25000 (if (featurep 'xemacs)
25001 ;; Under XEmacs, the hook is run in the correct place,
25002 ;; we directly show the context.
25003 (org-show-context 'isearch)
25004 ;; In Emacs the hook runs *before* restoring the overlays.
25005 ;; So we have to use a one-time post-command-hook to do this.
25006 ;; (Emacs 22 has a special variable, see function `org-mode')
25007 (unless (and (boundp 'isearch-mode-end-hook-quit)
25008 isearch-mode-end-hook-quit)
25009 ;; Only when the isearch was not quitted.
25010 (org-add-hook 'post-command-hook 'org-isearch-post-command
25011 'append 'local)))))
25013 (defun org-isearch-post-command ()
25014 "Remove self from hook, and show context."
25015 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
25016 (org-show-context 'isearch))
25019 ;;;; Integration with and fixes for other packages
25021 ;;; Imenu support
25023 (defvar org-imenu-markers nil
25024 "All markers currently used by Imenu.")
25025 (make-variable-buffer-local 'org-imenu-markers)
25027 (defun org-imenu-new-marker (&optional pos)
25028 "Return a new marker for use by Imenu, and remember the marker."
25029 (let ((m (make-marker)))
25030 (move-marker m (or pos (point)))
25031 (push m org-imenu-markers)
25034 (defun org-imenu-get-tree ()
25035 "Produce the index for Imenu."
25036 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
25037 (setq org-imenu-markers nil)
25038 (let* ((n org-imenu-depth)
25039 (re (concat "^" (org-get-limited-outline-regexp)))
25040 (subs (make-vector (1+ n) nil))
25041 (last-level 0)
25042 m level head0 head)
25043 (save-excursion
25044 (save-restriction
25045 (widen)
25046 (goto-char (point-max))
25047 (while (re-search-backward re nil t)
25048 (setq level (org-reduced-level (funcall outline-level)))
25049 (when (and (<= level n)
25050 (looking-at org-complex-heading-regexp)
25051 (setq head0 (org-match-string-no-properties 4)))
25052 (setq head (org-link-display-format head0)
25053 m (org-imenu-new-marker))
25054 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
25055 (if (>= level last-level)
25056 (push (cons head m) (aref subs level))
25057 (push (cons head (aref subs (1+ level))) (aref subs level))
25058 (loop for i from (1+ level) to n do (aset subs i nil)))
25059 (setq last-level level)))))
25060 (aref subs 1)))
25062 (eval-after-load "imenu"
25063 '(progn
25064 (add-hook 'imenu-after-jump-hook
25065 (lambda ()
25066 (if (derived-mode-p 'org-mode)
25067 (org-show-context 'org-goto))))))
25069 (defun org-link-display-format (link)
25070 "Replace a link with its the description.
25071 If there is no description, use the link target."
25072 (save-match-data
25073 (if (string-match org-bracket-link-analytic-regexp link)
25074 (replace-match (if (match-end 5)
25075 (match-string 5 link)
25076 (concat (match-string 1 link)
25077 (match-string 3 link)))
25078 nil t link)
25079 link)))
25081 (defun org-toggle-link-display ()
25082 "Toggle the literal or descriptive display of links."
25083 (interactive)
25084 (if org-descriptive-links
25085 (progn (org-remove-from-invisibility-spec '(org-link))
25086 (org-restart-font-lock)
25087 (setq org-descriptive-links nil))
25088 (progn (add-to-invisibility-spec '(org-link))
25089 (org-restart-font-lock)
25090 (setq org-descriptive-links t))))
25092 ;; Speedbar support
25094 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
25095 "Overlay marking the agenda restriction line in speedbar.")
25096 (overlay-put org-speedbar-restriction-lock-overlay
25097 'face 'org-agenda-restriction-lock)
25098 (overlay-put org-speedbar-restriction-lock-overlay
25099 'help-echo "Agendas are currently limited to this item.")
25100 (org-detach-overlay org-speedbar-restriction-lock-overlay)
25102 (defun org-speedbar-set-agenda-restriction ()
25103 "Restrict future agenda commands to the location at point in speedbar.
25104 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
25105 (interactive)
25106 (require 'org-agenda)
25107 (let (p m tp np dir txt)
25108 (cond
25109 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25110 'org-imenu t))
25111 (setq m (get-text-property p 'org-imenu-marker))
25112 (with-current-buffer (marker-buffer m)
25113 (goto-char m)
25114 (org-agenda-set-restriction-lock 'subtree)))
25115 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25116 'speedbar-function 'speedbar-find-file))
25117 (setq tp (previous-single-property-change
25118 (1+ p) 'speedbar-function)
25119 np (next-single-property-change
25120 tp 'speedbar-function)
25121 dir (speedbar-line-directory)
25122 txt (buffer-substring-no-properties (or tp (point-min))
25123 (or np (point-max))))
25124 (with-current-buffer (find-file-noselect
25125 (let ((default-directory dir))
25126 (expand-file-name txt)))
25127 (unless (derived-mode-p 'org-mode)
25128 (user-error "Cannot restrict to non-Org-mode file"))
25129 (org-agenda-set-restriction-lock 'file)))
25130 (t (user-error "Don't know how to restrict Org-mode's agenda")))
25131 (move-overlay org-speedbar-restriction-lock-overlay
25132 (point-at-bol) (point-at-eol))
25133 (setq current-prefix-arg nil)
25134 (org-agenda-maybe-redo)))
25136 (defvar speedbar-file-key-map)
25137 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25138 (eval-after-load "speedbar"
25139 '(progn
25140 (speedbar-add-supported-extension ".org")
25141 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25142 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25143 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25144 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25145 (add-hook 'speedbar-visiting-tag-hook
25146 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25148 ;;; Fixes and Hacks for problems with other packages
25150 (defun org--flyspell-object-check-p (element)
25151 "Non-nil when Flyspell can check object at point.
25152 ELEMENT is the element at point."
25153 (let ((object (save-excursion
25154 (when (org-looking-at-p "\\>") (backward-char))
25155 (org-element-context element))))
25156 (case (org-element-type object)
25157 ;; Prevent checks in links due to keybinding conflict with
25158 ;; Flyspell.
25159 ((code entity export-snippet inline-babel-call
25160 inline-src-block line-break latex-fragment link macro
25161 statistics-cookie target timestamp verbatim)
25162 nil)
25163 (footnote-reference
25164 ;; Only in inline footnotes, within the definition.
25165 (and (eq (org-element-property :type object) 'inline)
25166 (< (save-excursion
25167 (goto-char (org-element-property :begin object))
25168 (search-forward ":" nil t 2))
25169 (point))))
25170 (otherwise t))))
25172 (defun org-mode-flyspell-verify ()
25173 "Function used for `flyspell-generic-check-word-predicate'."
25174 (if (org-at-heading-p)
25175 ;; At a headline or an inlinetask, check title only. This is
25176 ;; faster than relying on `org-element-at-point'.
25177 (and (save-excursion (beginning-of-line)
25178 (and (let ((case-fold-search t))
25179 (not (looking-at "\\*+ END[ \t]*$")))
25180 (looking-at org-complex-heading-regexp)))
25181 (match-beginning 4)
25182 (>= (point) (match-beginning 4))
25183 (or (not (match-beginning 5))
25184 (< (point) (match-beginning 5))))
25185 (let* ((element (org-element-at-point))
25186 (post-affiliated (org-element-property :post-affiliated element)))
25187 (cond
25188 ;; Ignore checks in all affiliated keywords but captions.
25189 ((< (point) post-affiliated)
25190 (and (save-excursion
25191 (beginning-of-line)
25192 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25193 (> (point) (match-end 0))
25194 (org--flyspell-object-check-p element)))
25195 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25196 ((let ((log (org-log-into-drawer)))
25197 (and log
25198 (let ((drawer (org-element-lineage element '(drawer))))
25199 (and drawer
25200 (eq (compare-strings
25201 log nil nil
25202 (org-element-property :drawer-name drawer) nil nil t)
25203 t)))))
25204 nil)
25206 (case (org-element-type element)
25207 ((comment quote-section) t)
25208 (comment-block
25209 ;; Allow checks between block markers, not on them.
25210 (and (> (line-beginning-position) post-affiliated)
25211 (save-excursion
25212 (end-of-line)
25213 (skip-chars-forward " \r\t\n")
25214 (< (point) (org-element-property :end element)))))
25215 ;; Arbitrary list of keywords where checks are meaningful.
25216 ;; Make sure point is on the value part of the element.
25217 (keyword
25218 (and (member (org-element-property :key element)
25219 '("DESCRIPTION" "TITLE"))
25220 (save-excursion
25221 (search-backward ":" (line-beginning-position) t))))
25222 ;; Check is globally allowed in paragraphs verse blocks and
25223 ;; table rows (after affiliated keywords) but some objects
25224 ;; must not be affected.
25225 ((paragraph table-row verse-block)
25226 (let ((cbeg (org-element-property :contents-begin element))
25227 (cend (org-element-property :contents-end element)))
25228 (and cbeg (>= (point) cbeg) (< (point) cend)
25229 (org--flyspell-object-check-p element))))))))))
25230 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25232 (defun org-remove-flyspell-overlays-in (beg end)
25233 "Remove flyspell overlays in region."
25234 (and (org-bound-and-true-p flyspell-mode)
25235 (fboundp 'flyspell-delete-region-overlays)
25236 (flyspell-delete-region-overlays beg end)))
25238 (defvar flyspell-delayed-commands)
25239 (eval-after-load "flyspell"
25240 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25242 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25243 (eval-after-load "bookmark"
25244 '(if (boundp 'bookmark-after-jump-hook)
25245 ;; We can use the hook
25246 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25247 ;; Hook not available, use advice
25248 (defadvice bookmark-jump (after org-make-visible activate)
25249 "Make the position visible."
25250 (org-bookmark-jump-unhide))))
25252 ;; Make sure saveplace shows the location if it was hidden
25253 (eval-after-load "saveplace"
25254 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25255 "Make the position visible."
25256 (org-bookmark-jump-unhide)))
25258 ;; Make sure ecb shows the location if it was hidden
25259 (eval-after-load "ecb"
25260 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25261 "Make hierarchy visible when jumping into location from ECB tree buffer."
25262 (if (derived-mode-p 'org-mode)
25263 (org-show-context))))
25265 (defun org-bookmark-jump-unhide ()
25266 "Unhide the current position, to show the bookmark location."
25267 (and (derived-mode-p 'org-mode)
25268 (or (outline-invisible-p)
25269 (save-excursion (goto-char (max (point-min) (1- (point))))
25270 (outline-invisible-p)))
25271 (org-show-context 'bookmark-jump)))
25273 (defun org-mark-jump-unhide ()
25274 "Make the point visible with `org-show-context' after jumping to the mark."
25275 (when (and (derived-mode-p 'org-mode)
25276 (outline-invisible-p))
25277 (org-show-context 'mark-goto)))
25279 (eval-after-load "simple"
25280 '(defadvice pop-to-mark-command (after org-make-visible activate)
25281 "Make the point visible with `org-show-context'."
25282 (org-mark-jump-unhide)))
25284 (eval-after-load "simple"
25285 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25286 "Make the point visible with `org-show-context'."
25287 (org-mark-jump-unhide)))
25289 (eval-after-load "simple"
25290 '(defadvice pop-global-mark (after org-make-visible activate)
25291 "Make the point visible with `org-show-context'."
25292 (org-mark-jump-unhide)))
25294 ;; Make session.el ignore our circular variable
25295 (defvar session-globals-exclude)
25296 (eval-after-load "session"
25297 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25299 ;;;; Finish up
25301 (provide 'org)
25303 (run-hooks 'org-load-hook)
25305 ;;; org.el ends here