rework fix in82599d37e1 to use should-error macro
[org-mode.git] / lisp / org.el
blobdb2b6c0362134732589cec950a0a9a7953e0b27d
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2014 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 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
96 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
97 ;; some places -- e.g. see the macro `org-with-limited-levels'.
99 ;; In Org buffers, the value of `outline-regexp' is that of
100 ;; `org-outline-regexp'. The only function still directly relying on
101 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
102 ;; job when `orgstruct-mode' is active.
103 (defvar org-outline-regexp "\\*+ "
104 "Regexp to match Org headlines.")
106 (defvar org-outline-regexp-bol "^\\*+ "
107 "Regexp to match Org headlines.
108 This is similar to `org-outline-regexp' but additionally makes
109 sure that we are at the beginning of the line.")
111 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
112 "Matches a headline, putting stars and text into groups.
113 Stars are put in group 1 and the trimmed body in group 2.")
115 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
116 (unless (boundp 'calendar-view-holidays-initially-flag)
117 (org-defvaralias 'calendar-view-holidays-initially-flag
118 'view-calendar-holidays-initially))
119 (unless (boundp 'calendar-view-diary-initially-flag)
120 (org-defvaralias 'calendar-view-diary-initially-flag
121 'view-diary-entries-initially))
122 (unless (boundp 'diary-fancy-buffer)
123 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
125 (declare-function org-add-archive-files "org-archive" (files))
127 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
128 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
129 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
130 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
131 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
132 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
133 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
134 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
135 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
136 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
137 (declare-function org-clock-update-time-maybe "org-clock" ())
138 (declare-function org-clocktable-shift "org-clock" (dir n))
140 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
141 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
142 (declare-function orgtbl-mode "org-table" (&optional arg))
143 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
144 (declare-function org-beamer-mode "ox-beamer" ())
145 (declare-function org-table-blank-field "org-table" ())
146 (declare-function org-table-edit-field "org-table" (arg))
147 (declare-function org-table-insert-row "org-table" (&optional arg))
148 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
149 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
150 (declare-function org-id-get-create "org-id" (&optional force))
151 (declare-function org-add-archive-files "org-archive" (files))
152 (declare-function org-id-find-id-file "org-id" (id))
153 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
154 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
155 (declare-function org-agenda-redo "org-agenda" (&optional all))
156 (declare-function org-table-align "org-table" ())
157 (declare-function org-table-begin "org-table" (&optional table-type))
158 (declare-function org-table-blank-field "org-table" ())
159 (declare-function org-table-end "org-table" (&optional table-type))
160 (declare-function org-table-end-of-field "org-table" (&optional n))
161 (declare-function org-table-insert-row "org-table" (&optional arg))
162 (declare-function org-table-paste-rectangle "org-table" ())
163 (declare-function org-table-maybe-eval-formula "org-table" ())
164 (declare-function org-table-maybe-recalculate-line "org-table" ())
165 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
166 (declare-function org-plot/gnuplot "org-plot" (&optional params))
168 (declare-function org-element-at-point "org-element" ())
169 (declare-function org-element-cache-reset "org-element" (&optional all))
170 (declare-function org-element-cache-refresh "org-element" (pos))
171 (declare-function org-element-contents "org-element" (element))
172 (declare-function org-element-context "org-element" (&optional element))
173 (declare-function org-element-interpret-data "org-element"
174 (data &optional parent))
175 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
176 (declare-function org-element-parse-buffer "org-element"
177 (&optional granularity visible-only))
178 (declare-function org-element-property "org-element" (property element))
179 (declare-function org-element-put-property "org-element"
180 (element property value))
181 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
182 (declare-function org-element-parse-buffer "org-element"
183 (&optional granularity visible-only))
184 (declare-function org-element-type "org-element" (element))
186 (defsubst org-uniquify (list)
187 "Non-destructively remove duplicate elements from LIST."
188 (let ((res (copy-sequence list))) (delete-dups res)))
190 (defsubst org-get-at-bol (property)
191 "Get text property PROPERTY at the beginning of line."
192 (get-text-property (point-at-bol) property))
194 (defsubst org-trim (s)
195 "Remove whitespace at the beginning and the end of string S."
196 (replace-regexp-in-string
197 "\\`[ \t\n\r]+" ""
198 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
200 ;; load languages based on value of `org-babel-load-languages'
201 (defvar org-babel-load-languages)
203 ;;;###autoload
204 (defun org-babel-do-load-languages (sym value)
205 "Load the languages defined in `org-babel-load-languages'."
206 (set-default sym value)
207 (mapc (lambda (pair)
208 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
209 (if active
210 (progn
211 (require (intern (concat "ob-" lang))))
212 (progn
213 (funcall 'fmakunbound
214 (intern (concat "org-babel-execute:" lang)))
215 (funcall 'fmakunbound
216 (intern (concat "org-babel-expand-body:" lang)))))))
217 org-babel-load-languages))
219 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
220 ;;;###autoload
221 (defun org-babel-load-file (file &optional compile)
222 "Load Emacs Lisp source code blocks in the Org-mode FILE.
223 This function exports the source code using `org-babel-tangle'
224 and then loads the resulting file using `load-file'. With prefix
225 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
226 file to byte-code before it is loaded."
227 (interactive "fFile to load: \nP")
228 (let* ((age (lambda (file)
229 (float-time
230 (time-subtract (current-time)
231 (nth 5 (or (file-attributes (file-truename file))
232 (file-attributes file)))))))
233 (base-name (file-name-sans-extension file))
234 (exported-file (concat base-name ".el")))
235 ;; tangle if the org-mode file is newer than the elisp file
236 (unless (and (file-exists-p exported-file)
237 (> (funcall age file) (funcall age exported-file)))
238 (setq exported-file
239 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
240 (message "%s %s"
241 (if compile
242 (progn (byte-compile-file exported-file 'load)
243 "Compiled and loaded")
244 (progn (load-file exported-file) "Loaded"))
245 exported-file)))
247 (defcustom org-babel-load-languages '((emacs-lisp . t))
248 "Languages which can be evaluated in Org-mode buffers.
249 This list can be used to load support for any of the languages
250 below, note that each language will depend on a different set of
251 system executables and/or Emacs modes. When a language is
252 \"loaded\", then code blocks in that language can be evaluated
253 with `org-babel-execute-src-block' bound by default to C-c
254 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
255 be set to remove code block evaluation from the C-c C-c
256 keybinding. By default only Emacs Lisp (which has no
257 requirements) is loaded."
258 :group 'org-babel
259 :set 'org-babel-do-load-languages
260 :version "24.1"
261 :type '(alist :tag "Babel Languages"
262 :key-type
263 (choice
264 (const :tag "Awk" awk)
265 (const :tag "C" C)
266 (const :tag "R" R)
267 (const :tag "Asymptote" asymptote)
268 (const :tag "Calc" calc)
269 (const :tag "Clojure" clojure)
270 (const :tag "CSS" css)
271 (const :tag "Ditaa" ditaa)
272 (const :tag "Dot" dot)
273 (const :tag "Emacs Lisp" emacs-lisp)
274 (const :tag "Forth" forth)
275 (const :tag "Fortran" fortran)
276 (const :tag "Gnuplot" gnuplot)
277 (const :tag "Haskell" haskell)
278 (const :tag "IO" io)
279 (const :tag "J" J)
280 (const :tag "Java" java)
281 (const :tag "Javascript" js)
282 (const :tag "LaTeX" latex)
283 (const :tag "Ledger" ledger)
284 (const :tag "Lilypond" lilypond)
285 (const :tag "Lisp" lisp)
286 (const :tag "Makefile" makefile)
287 (const :tag "Maxima" maxima)
288 (const :tag "Matlab" matlab)
289 (const :tag "Mscgen" mscgen)
290 (const :tag "Ocaml" ocaml)
291 (const :tag "Octave" octave)
292 (const :tag "Org" org)
293 (const :tag "Perl" perl)
294 (const :tag "Pico Lisp" picolisp)
295 (const :tag "PlantUML" plantuml)
296 (const :tag "Python" python)
297 (const :tag "Ruby" ruby)
298 (const :tag "Sass" sass)
299 (const :tag "Scala" scala)
300 (const :tag "Scheme" scheme)
301 (const :tag "Screen" screen)
302 (const :tag "Shell Script" shell)
303 (const :tag "Shen" shen)
304 (const :tag "Sql" sql)
305 (const :tag "Sqlite" sqlite)
306 (const :tag "ebnf2ps" ebnf2ps))
307 :value-type (boolean :tag "Activate" :value t)))
309 ;;;; Customization variables
310 (defcustom org-clone-delete-id nil
311 "Remove ID property of clones of a subtree.
312 When non-nil, clones of a subtree don't inherit the ID property.
313 Otherwise they inherit the ID property with a new unique
314 identifier."
315 :type 'boolean
316 :version "24.1"
317 :group 'org-id)
319 ;;; Version
320 (org-check-version)
322 ;;;###autoload
323 (defun org-version (&optional here full message)
324 "Show the org-mode version.
325 Interactively, or when MESSAGE is non-nil, show it in echo area.
326 With prefix argument, or when HERE is non-nil, insert it at point.
327 In non-interactive uses, a reduced version string is output unless
328 FULL is given."
329 (interactive (list current-prefix-arg t (not current-prefix-arg)))
330 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
331 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
332 (load-suffixes (list ".el"))
333 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
334 (org-trash (or
335 (and (fboundp 'org-release) (fboundp 'org-git-version))
336 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
337 (load-suffixes save-load-suffixes)
338 (org-version (org-release))
339 (git-version (org-git-version))
340 (version (format "Org-mode version %s (%s @ %s)"
341 org-version
342 git-version
343 (if org-install-dir
344 (if (string= org-dir org-install-dir)
345 org-install-dir
346 (concat "mixed installation! " org-install-dir " and " org-dir))
347 "org-loaddefs.el can not be found!")))
348 (version1 (if full version org-version)))
349 (when here (insert version1))
350 (when message (message "%s" version1))
351 version1))
353 (defconst org-version (org-version))
356 ;;; Syntax Constants
358 ;;;; Block
360 (defconst org-block-regexp
361 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
362 "Regular expression for hiding blocks.")
364 (defconst org-dblock-start-re
365 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
366 "Matches the start line of a dynamic block, with parameters.")
368 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
369 "Matches the end of a dynamic block.")
371 ;;;; Clock and Planning
373 (defconst org-clock-string "CLOCK:"
374 "String used as prefix for timestamps clocking work hours on an item.")
376 (defconst org-closed-string "CLOSED:"
377 "String used as the prefix for timestamps logging closing a TODO entry.")
379 (defconst org-deadline-string "DEADLINE:"
380 "String to mark deadline entries.
381 A deadline is this string, followed by a time stamp. Should be a word,
382 terminated by a colon. You can insert a schedule keyword and
383 a timestamp with \\[org-deadline].")
385 (defconst org-scheduled-string "SCHEDULED:"
386 "String to mark scheduled TODO entries.
387 A schedule is this string, followed by a time stamp. Should be a word,
388 terminated by a colon. You can insert a schedule keyword and
389 a timestamp with \\[org-schedule].")
391 (defconst org-ds-keyword-length
392 (+ 2
393 (apply #'max
394 (mapcar #'length
395 (list org-deadline-string org-scheduled-string
396 org-clock-string org-closed-string))))
397 "Maximum length of the DEADLINE and SCHEDULED keywords.")
399 (defconst org-planning-line-re
400 (concat "^[ \t]*"
401 (regexp-opt
402 (list org-closed-string org-deadline-string org-scheduled-string)
404 "Matches a line with planning info.
405 Matched keyword is in group 1.")
407 (defconst org-clock-line-re
408 (concat "^[ \t]*" org-clock-string)
409 "Matches a line with clock info.")
411 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
412 "Matches the DEADLINE keyword.")
414 (defconst org-deadline-time-regexp
415 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
416 "Matches the DEADLINE keyword together with a time stamp.")
418 (defconst org-deadline-time-hour-regexp
419 (concat "\\<" org-deadline-string
420 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
421 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
423 (defconst org-deadline-line-regexp
424 (concat "\\<\\(" org-deadline-string "\\).*")
425 "Matches the DEADLINE keyword and the rest of the line.")
427 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
428 "Matches the SCHEDULED keyword.")
430 (defconst org-scheduled-time-regexp
431 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
432 "Matches the SCHEDULED keyword together with a time stamp.")
434 (defconst org-scheduled-time-hour-regexp
435 (concat "\\<" org-scheduled-string
436 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
437 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
439 (defconst org-closed-time-regexp
440 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
441 "Matches the CLOSED keyword together with a time stamp.")
443 (defconst org-keyword-time-regexp
444 (concat "\\<"
445 (regexp-opt
446 (list org-scheduled-string org-deadline-string org-closed-string
447 org-clock-string)
449 " *[[<]\\([^]>]+\\)[]>]")
450 "Matches any of the 4 keywords, together with the time stamp.")
452 (defconst org-keyword-time-not-clock-regexp
453 (concat
454 "\\<"
455 (regexp-opt
456 (list org-scheduled-string org-deadline-string org-closed-string) t)
457 " *[[<]\\([^]>]+\\)[]>]")
458 "Matches any of the 3 keywords, together with the time stamp.")
460 (defconst org-maybe-keyword-time-regexp
461 (concat "\\(\\<"
462 (regexp-opt
463 (list org-scheduled-string org-deadline-string org-closed-string
464 org-clock-string)
466 "\\)?"
467 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
468 "\\|"
469 "<%%([^\r\n>]*>\\)")
470 "Matches a timestamp, possibly preceded by a keyword.")
472 (defconst org-all-time-keywords
473 (mapcar (lambda (w) (substring w 0 -1))
474 (list org-scheduled-string org-deadline-string
475 org-clock-string org-closed-string))
476 "List of time keywords.")
478 ;;;; Drawer
480 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
481 "Matches first or last line of a hidden block.
482 Group 1 contains drawer's name or \"END\".")
484 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
485 "Regular expression matching the first line of a property drawer.")
487 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
488 "Regular expression matching the last line of a property drawer.")
490 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
491 "Regular expression matching the first line of a clock drawer.")
493 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
494 "Regular expression matching the last line of a clock drawer.")
496 (defconst org-property-drawer-re
497 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
498 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*"
499 "[ \t]*:END:[ \t]*$")
500 "Matches an entire property drawer.")
502 (defconst org-clock-drawer-re
503 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
504 org-clock-drawer-end-re "\\)\n?")
505 "Matches an entire clock drawer.")
507 ;;;; Headline
509 (defconst org-heading-keyword-regexp-format
510 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
511 "Printf format for a regexp matching a headline with some keyword.
512 This regexp will match the headline of any node which has the
513 exact keyword that is put into the format. The keyword isn't in
514 any group by default, but the stars and the body are.")
516 (defconst org-heading-keyword-maybe-regexp-format
517 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
518 "Printf format for a regexp matching a headline, possibly with some keyword.
519 This regexp can match any headline with the specified keyword, or
520 without a keyword. The keyword isn't in any group by default,
521 but the stars and the body are.")
523 (defconst org-archive-tag "ARCHIVE"
524 "The tag that marks a subtree as archived.
525 An archived subtree does not open during visibility cycling, and does
526 not contribute to the agenda listings.")
528 (defconst org-comment-string "COMMENT"
529 "Entries starting with this keyword will never be exported.
530 An entry can be toggled between COMMENT and normal with
531 \\[org-toggle-comment].")
534 ;;;; LaTeX Environments and Fragments
536 (defconst org-latex-regexps
537 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
538 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
539 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
540 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
541 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
542 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
543 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
544 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
545 "Regular expressions for matching embedded LaTeX.")
547 ;;;; Node Property
549 (defconst org-effort-property "Effort"
550 "The property that is being used to keep track of effort estimates.
551 Effort estimates given in this property need to have the format H:MM.")
553 ;;;; Table
555 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
556 "Detect an org-type or table-type table.")
558 (defconst org-table-line-regexp "^[ \t]*|"
559 "Detect an org-type table line.")
561 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
562 "Detect an org-type table line.")
564 (defconst org-table-hline-regexp "^[ \t]*|-"
565 "Detect an org-type table hline.")
567 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
568 "Detect a table-type table hline.")
570 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
571 "Detect the first line outside a table when searching from within it.
572 This works for both table types.")
574 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
575 "Detect a #+TBLFM line.")
577 ;;;; Timestamp
579 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
580 "Regular expression for fast time stamp matching.")
582 (defconst org-ts-regexp-inactive
583 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
584 "Regular expression for fast inactive time stamp matching.")
586 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
587 "Regular expression for fast time stamp matching.")
589 (defconst org-ts-regexp0
590 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
591 "Regular expression matching time strings for analysis.
592 This one does not require the space after the date, so it can be used
593 on a string that terminates immediately after the date.")
595 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
596 "Regular expression matching time strings for analysis.")
598 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
599 "Regular expression matching time stamps, with groups.")
601 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
602 "Regular expression matching time stamps (also [..]), with groups.")
604 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
605 "Regular expression matching a time stamp range.")
607 (defconst org-tr-regexp-both
608 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
609 "Regular expression matching a time stamp range.")
611 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
612 org-ts-regexp "\\)?")
613 "Regular expression matching a time stamp or time stamp range.")
615 (defconst org-tsr-regexp-both
616 (concat org-ts-regexp-both "\\(--?-?"
617 org-ts-regexp-both "\\)?")
618 "Regular expression matching a time stamp or time stamp range.
619 The time stamps may be either active or inactive.")
621 (defconst org-repeat-re
622 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
623 "Regular expression for specifying repeated events.
624 After a match, group 1 contains the repeat expression.")
626 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
627 "Formats for `format-time-string' which are used for time stamps.")
630 ;;; The custom variables
632 (defgroup org nil
633 "Outline-based notes management and organizer."
634 :tag "Org"
635 :group 'outlines
636 :group 'calendar)
638 (defcustom org-mode-hook nil
639 "Mode hook for Org-mode, run after the mode was turned on."
640 :group 'org
641 :type 'hook)
643 (defcustom org-load-hook nil
644 "Hook that is run after org.el has been loaded."
645 :group 'org
646 :type 'hook)
648 (defcustom org-log-buffer-setup-hook nil
649 "Hook that is run after an Org log buffer is created."
650 :group 'org
651 :version "24.1"
652 :type 'hook)
654 (defvar org-modules) ; defined below
655 (defvar org-modules-loaded nil
656 "Have the modules been loaded already?")
658 (defun org-load-modules-maybe (&optional force)
659 "Load all extensions listed in `org-modules'."
660 (when (or force (not org-modules-loaded))
661 (mapc (lambda (ext)
662 (condition-case nil (require ext)
663 (error (message "Problems while trying to load feature `%s'" ext))))
664 org-modules)
665 (setq org-modules-loaded t)))
667 (defun org-set-modules (var value)
668 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
669 (set var value)
670 (when (featurep 'org)
671 (org-load-modules-maybe 'force)
672 (org-element-cache-reset 'all)))
674 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
675 "Modules that should always be loaded together with org.el.
677 If a description starts with <C>, the file is not part of Emacs
678 and loading it will require that you have downloaded and properly
679 installed the Org mode distribution.
681 You can also use this system to load external packages (i.e. neither Org
682 core modules, nor modules from the CONTRIB directory). Just add symbols
683 to the end of the list. If the package is called org-xyz.el, then you need
684 to add the symbol `xyz', and the package must have a call to:
686 \(provide 'org-xyz)
688 For export specific modules, see also `org-export-backends'."
689 :group 'org
690 :set 'org-set-modules
691 :version "24.4"
692 :package-version '(Org . "8.0")
693 :type
694 '(set :greedy t
695 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
696 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
697 (const :tag " crypt: Encryption of subtrees" org-crypt)
698 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
699 (const :tag " docview: Links to doc-view buffers" org-docview)
700 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
701 (const :tag " habit: Track your consistency with habits" org-habit)
702 (const :tag " id: Global IDs for identifying entries" org-id)
703 (const :tag " info: Links to Info nodes" org-info)
704 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
705 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
706 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
707 (const :tag " mouse: Additional mouse support" org-mouse)
708 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
709 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
710 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
712 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
713 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
714 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
715 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
716 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
717 (const :tag "C collector: Collect properties into tables" org-collector)
718 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
719 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
720 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
721 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
722 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
723 (const :tag "C eval: Include command output as text" org-eval)
724 (const :tag "C eww: Store link to url of eww" org-eww)
725 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
726 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
727 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
728 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
729 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
730 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
731 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
732 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
733 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
734 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
735 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
736 (const :tag "C mew: Links to Mew folders/messages" org-mew)
737 (const :tag "C mtags: Support for muse-like tags" org-mtags)
738 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
739 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
740 (const :tag "C registry: A registry for Org-mode links" org-registry)
741 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
742 (const :tag "C secretary: Team management with org-mode" org-secretary)
743 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
744 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
745 (const :tag "C track: Keep up with Org-mode development" org-track)
746 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
747 (const :tag "C vm: Links to VM folders/messages" org-vm)
748 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
749 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
750 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
752 (defvar org-export--registered-backends) ; From ox.el.
753 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
754 (declare-function org-export-backend-name "ox" (backend))
755 (defcustom org-export-backends '(ascii html icalendar latex)
756 "List of export back-ends that should be always available.
758 If a description starts with <C>, the file is not part of Emacs
759 and loading it will require that you have downloaded and properly
760 installed the Org mode distribution.
762 Unlike to `org-modules', libraries in this list will not be
763 loaded along with Org, but only once the export framework is
764 needed.
766 This variable needs to be set before org.el is loaded. If you
767 need to make a change while Emacs is running, use the customize
768 interface or run the following code, where VAL stands for the new
769 value of the variable, after updating it:
771 \(progn
772 \(setq org-export--registered-backends
773 \(org-remove-if-not
774 \(lambda (backend)
775 \(let ((name (org-export-backend-name backend)))
776 \(or (memq name val)
777 \(catch 'parentp
778 \(dolist (b val)
779 \(and (org-export-derived-backend-p b name)
780 \(throw 'parentp t)))))))
781 org-export--registered-backends))
782 \(let ((new-list (mapcar 'org-export-backend-name
783 org-export--registered-backends)))
784 \(dolist (backend val)
785 \(cond
786 \((not (load (format \"ox-%s\" backend) t t))
787 \(message \"Problems while trying to load export back-end `%s'\"
788 backend))
789 \((not (memq backend new-list)) (push backend new-list))))
790 \(set-default 'org-export-backends new-list)))
792 Adding a back-end to this list will also pull the back-end it
793 depends on, if any."
794 :group 'org
795 :group 'org-export
796 :version "24.4"
797 :package-version '(Org . "8.0")
798 :initialize 'custom-initialize-set
799 :set (lambda (var val)
800 (if (not (featurep 'ox)) (set-default var val)
801 ;; Any back-end not required anymore (not present in VAL and not
802 ;; a parent of any back-end in the new value) is removed from the
803 ;; list of registered back-ends.
804 (setq org-export--registered-backends
805 (org-remove-if-not
806 (lambda (backend)
807 (let ((name (org-export-backend-name backend)))
808 (or (memq name val)
809 (catch 'parentp
810 (dolist (b val)
811 (and (org-export-derived-backend-p b name)
812 (throw 'parentp t)))))))
813 org-export--registered-backends))
814 ;; Now build NEW-LIST of both new back-ends and required
815 ;; parents.
816 (let ((new-list (mapcar 'org-export-backend-name
817 org-export--registered-backends)))
818 (dolist (backend val)
819 (cond
820 ((not (load (format "ox-%s" backend) t t))
821 (message "Problems while trying to load export back-end `%s'"
822 backend))
823 ((not (memq backend new-list)) (push backend new-list))))
824 ;; Set VAR to that list with fixed dependencies.
825 (set-default var new-list))))
826 :type '(set :greedy t
827 (const :tag " ascii Export buffer to ASCII format" ascii)
828 (const :tag " beamer Export buffer to Beamer presentation" beamer)
829 (const :tag " html Export buffer to HTML format" html)
830 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
831 (const :tag " latex Export buffer to LaTeX format" latex)
832 (const :tag " man Export buffer to MAN format" man)
833 (const :tag " md Export buffer to Markdown format" md)
834 (const :tag " odt Export buffer to ODT format" odt)
835 (const :tag " org Export buffer to Org format" org)
836 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
837 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
838 (const :tag "C deck Export buffer to deck.js presentations" deck)
839 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
840 (const :tag "C groff Export buffer to Groff format" groff)
841 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
842 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
843 (const :tag "C s5 Export buffer to s5 presentations" s5)
844 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
846 (eval-after-load 'ox
847 '(mapc
848 (lambda (backend)
849 (condition-case nil (require (intern (format "ox-%s" backend)))
850 (error (message "Problems while trying to load export back-end `%s'"
851 backend))))
852 org-export-backends))
854 (defcustom org-support-shift-select nil
855 "Non-nil means make shift-cursor commands select text when possible.
857 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
858 start selecting a region, or enlarge regions started in this way.
859 In Org-mode, in special contexts, these same keys are used for
860 other purposes, important enough to compete with shift selection.
861 Org tries to balance these needs by supporting `shift-select-mode'
862 outside these special contexts, under control of this variable.
864 The default of this variable is nil, to avoid confusing behavior. Shifted
865 cursor keys will then execute Org commands in the following contexts:
866 - on a headline, changing TODO state (left/right) and priority (up/down)
867 - on a time stamp, changing the time
868 - in a plain list item, changing the bullet type
869 - in a property definition line, switching between allowed values
870 - in the BEGIN line of a clock table (changing the time block).
871 Outside these contexts, the commands will throw an error.
873 When this variable is t and the cursor is not in a special
874 context, Org-mode will support shift-selection for making and
875 enlarging regions. To make this more effective, the bullet
876 cycling will no longer happen anywhere in an item line, but only
877 if the cursor is exactly on the bullet.
879 If you set this variable to the symbol `always', then the keys
880 will not be special in headlines, property lines, and item lines,
881 to make shift selection work there as well. If this is what you
882 want, you can use the following alternative commands: `C-c C-t'
883 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
884 can be used to switch TODO sets, `C-c -' to cycle item bullet
885 types, and properties can be edited by hand or in column view.
887 However, when the cursor is on a timestamp, shift-cursor commands
888 will still edit the time stamp - this is just too good to give up.
890 XEmacs user should have this variable set to nil, because
891 `shift-select-mode' is in Emacs 23 or later only."
892 :group 'org
893 :type '(choice
894 (const :tag "Never" nil)
895 (const :tag "When outside special context" t)
896 (const :tag "Everywhere except timestamps" always)))
898 (defcustom org-loop-over-headlines-in-active-region nil
899 "Shall some commands act upon headlines in the active region?
901 When set to `t', some commands will be performed in all headlines
902 within the active region.
904 When set to `start-level', some commands will be performed in all
905 headlines within the active region, provided that these headlines
906 are of the same level than the first one.
908 When set to a string, those commands will be performed on the
909 matching headlines within the active region. Such string must be
910 a tags/property/todo match as it is used in the agenda tags view.
912 The list of commands is: `org-schedule', `org-deadline',
913 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
914 `org-archive-to-archive-sibling'. The archiving commands skip
915 already archived entries."
916 :type '(choice (const :tag "Don't loop" nil)
917 (const :tag "All headlines in active region" t)
918 (const :tag "In active region, headlines at the same level than the first one" start-level)
919 (string :tag "Tags/Property/Todo matcher"))
920 :version "24.1"
921 :group 'org-todo
922 :group 'org-archive)
924 (defgroup org-startup nil
925 "Options concerning startup of Org-mode."
926 :tag "Org Startup"
927 :group 'org)
929 (defcustom org-startup-folded t
930 "Non-nil means entering Org-mode will switch to OVERVIEW.
931 This can also be configured on a per-file basis by adding one of
932 the following lines anywhere in the buffer:
934 #+STARTUP: fold (or `overview', this is equivalent)
935 #+STARTUP: nofold (or `showall', this is equivalent)
936 #+STARTUP: content
937 #+STARTUP: showeverything
939 By default, this option is ignored when Org opens agenda files
940 for the first time. If you want the agenda to honor the startup
941 option, set `org-agenda-inhibit-startup' to nil."
942 :group 'org-startup
943 :type '(choice
944 (const :tag "nofold: show all" nil)
945 (const :tag "fold: overview" t)
946 (const :tag "content: all headlines" content)
947 (const :tag "show everything, even drawers" showeverything)))
949 (defcustom org-startup-truncated t
950 "Non-nil means entering Org-mode will set `truncate-lines'.
951 This is useful since some lines containing links can be very long and
952 uninteresting. Also tables look terrible when wrapped."
953 :group 'org-startup
954 :type 'boolean)
956 (defcustom org-startup-indented nil
957 "Non-nil means turn on `org-indent-mode' on startup.
958 This can also be configured on a per-file basis by adding one of
959 the following lines anywhere in the buffer:
961 #+STARTUP: indent
962 #+STARTUP: noindent"
963 :group 'org-structure
964 :type '(choice
965 (const :tag "Not" nil)
966 (const :tag "Globally (slow on startup in large files)" t)))
968 (defcustom org-use-sub-superscripts t
969 "Non-nil means interpret \"_\" and \"^\" for display.
971 If you want to control how Org exports those characters, see
972 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
973 used to be an alias for `org-export-with-sub-superscripts' in
974 Org <8.0, it is not anymore.
976 When this option is turned on, you can use TeX-like syntax for
977 sub- and superscripts within the buffer. Several characters after
978 \"_\" or \"^\" will be considered as a single item - so grouping
979 with {} is normally not needed. For example, the following things
980 will be parsed as single sub- or superscripts:
982 10^24 or 10^tau several digits will be considered 1 item.
983 10^-12 or 10^-tau a leading sign with digits or a word
984 x^2-y^3 will be read as x^2 - y^3, because items are
985 terminated by almost any nonword/nondigit char.
986 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
988 Still, ambiguity is possible. So when in doubt, use {} to enclose
989 the sub/superscript. If you set this variable to the symbol `{}',
990 the braces are *required* in order to trigger interpretations as
991 sub/superscript. This can be helpful in documents that need \"_\"
992 frequently in plain text."
993 :group 'org-startup
994 :version "24.4"
995 :package-version '(Org . "8.0")
996 :type '(choice
997 (const :tag "Always interpret" t)
998 (const :tag "Only with braces" {})
999 (const :tag "Never interpret" nil)))
1001 (defcustom org-startup-with-beamer-mode nil
1002 "Non-nil means turn on `org-beamer-mode' on startup.
1003 This can also be configured on a per-file basis by adding one of
1004 the following lines anywhere in the buffer:
1006 #+STARTUP: beamer"
1007 :group 'org-startup
1008 :version "24.1"
1009 :type 'boolean)
1011 (defcustom org-startup-align-all-tables nil
1012 "Non-nil means align all tables when visiting a file.
1013 This is useful when the column width in tables is forced with <N> cookies
1014 in table fields. Such tables will look correct only after the first re-align.
1015 This can also be configured on a per-file basis by adding one of
1016 the following lines anywhere in the buffer:
1017 #+STARTUP: align
1018 #+STARTUP: noalign"
1019 :group 'org-startup
1020 :type 'boolean)
1022 (defcustom org-startup-with-inline-images nil
1023 "Non-nil means show inline images when loading a new Org file.
1024 This can also be configured on a per-file basis by adding one of
1025 the following lines anywhere in the buffer:
1026 #+STARTUP: inlineimages
1027 #+STARTUP: noinlineimages"
1028 :group 'org-startup
1029 :version "24.1"
1030 :type 'boolean)
1032 (defcustom org-startup-with-latex-preview nil
1033 "Non-nil means preview LaTeX fragments when loading a new Org file.
1035 This can also be configured on a per-file basis by adding one of
1036 the following lines anywhere in the buffer:
1037 #+STARTUP: latexpreview
1038 #+STARTUP: nolatexpreview"
1039 :group 'org-startup
1040 :version "24.4"
1041 :package-version '(Org . "8.0")
1042 :type 'boolean)
1044 (defcustom org-insert-mode-line-in-empty-file nil
1045 "Non-nil means insert the first line setting Org-mode in empty files.
1046 When the function `org-mode' is called interactively in an empty file, this
1047 normally means that the file name does not automatically trigger Org-mode.
1048 To ensure that the file will always be in Org-mode in the future, a
1049 line enforcing Org-mode will be inserted into the buffer, if this option
1050 has been set."
1051 :group 'org-startup
1052 :type 'boolean)
1054 (defcustom org-replace-disputed-keys nil
1055 "Non-nil means use alternative key bindings for some keys.
1056 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
1057 These keys are also used by other packages like shift-selection-mode'
1058 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1059 If you want to use Org-mode together with one of these other modes,
1060 or more generally if you would like to move some Org-mode commands to
1061 other keys, set this variable and configure the keys with the variable
1062 `org-disputed-keys'.
1064 This option is only relevant at load-time of Org-mode, and must be set
1065 *before* org.el is loaded. Changing it requires a restart of Emacs to
1066 become effective."
1067 :group 'org-startup
1068 :type 'boolean)
1070 (defcustom org-use-extra-keys nil
1071 "Non-nil means use extra key sequence definitions for certain commands.
1072 This happens automatically if you run XEmacs or if `window-system'
1073 is nil. This variable lets you do the same manually. You must
1074 set it before loading org.
1076 Example: on Carbon Emacs 22 running graphically, with an external
1077 keyboard on a Powerbook, the default way of setting M-left might
1078 not work for either Alt or ESC. Setting this variable will make
1079 it work for ESC."
1080 :group 'org-startup
1081 :type 'boolean)
1083 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1085 (defcustom org-disputed-keys
1086 '(([(shift up)] . [(meta p)])
1087 ([(shift down)] . [(meta n)])
1088 ([(shift left)] . [(meta -)])
1089 ([(shift right)] . [(meta +)])
1090 ([(control shift right)] . [(meta shift +)])
1091 ([(control shift left)] . [(meta shift -)]))
1092 "Keys for which Org-mode and other modes compete.
1093 This is an alist, cars are the default keys, second element specifies
1094 the alternative to use when `org-replace-disputed-keys' is t.
1096 Keys can be specified in any syntax supported by `define-key'.
1097 The value of this option takes effect only at Org-mode's startup,
1098 therefore you'll have to restart Emacs to apply it after changing."
1099 :group 'org-startup
1100 :type 'alist)
1102 (defun org-key (key)
1103 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1104 Or return the original if not disputed.
1105 Also apply the translations defined in `org-xemacs-key-equivalents'."
1106 (when org-replace-disputed-keys
1107 (let* ((nkey (key-description key))
1108 (x (org-find-if (lambda (x)
1109 (equal (key-description (car x)) nkey))
1110 org-disputed-keys)))
1111 (setq key (if x (cdr x) key))))
1112 (when (featurep 'xemacs)
1113 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1114 key)
1116 (defun org-find-if (predicate seq)
1117 (catch 'exit
1118 (while seq
1119 (if (funcall predicate (car seq))
1120 (throw 'exit (car seq))
1121 (pop seq)))))
1123 (defun org-defkey (keymap key def)
1124 "Define a key, possibly translated, as returned by `org-key'."
1125 (define-key keymap (org-key key) def))
1127 (defcustom org-ellipsis nil
1128 "The ellipsis to use in the Org-mode outline.
1129 When nil, just use the standard three dots.
1130 When a string, use that string instead.
1131 When a face, use the standard 3 dots, but with the specified face.
1132 The change affects only Org-mode (which will then use its own display table).
1133 Changing this requires executing \\[org-mode] in a buffer to become
1134 effective."
1135 :group 'org-startup
1136 :type '(choice (const :tag "Default" nil)
1137 (face :tag "Face" :value org-warning)
1138 (string :tag "String" :value "...#")))
1140 (defvar org-display-table nil
1141 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1143 (defgroup org-keywords nil
1144 "Keywords in Org-mode."
1145 :tag "Org Keywords"
1146 :group 'org)
1148 (defcustom org-closed-keep-when-no-todo nil
1149 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1150 :group 'org-todo
1151 :group 'org-keywords
1152 :version "24.4"
1153 :package-version '(Org . "8.0")
1154 :type 'boolean)
1156 (defgroup org-structure nil
1157 "Options concerning the general structure of Org-mode files."
1158 :tag "Org Structure"
1159 :group 'org)
1161 (defgroup org-reveal-location nil
1162 "Options about how to make context of a location visible."
1163 :tag "Org Reveal Location"
1164 :group 'org-structure)
1166 (defconst org-context-choice
1167 '(choice
1168 (const :tag "Always" t)
1169 (const :tag "Never" nil)
1170 (repeat :greedy t :tag "Individual contexts"
1171 (cons
1172 (choice :tag "Context"
1173 (const agenda)
1174 (const org-goto)
1175 (const occur-tree)
1176 (const tags-tree)
1177 (const link-search)
1178 (const mark-goto)
1179 (const bookmark-jump)
1180 (const isearch)
1181 (const default))
1182 (boolean))))
1183 "Contexts for the reveal options.")
1185 (defcustom org-show-hierarchy-above '((default . t))
1186 "Non-nil means show full hierarchy when revealing a location.
1187 Org-mode often shows locations in an org-mode file which might have
1188 been invisible before. When this is set, the hierarchy of headings
1189 above the exposed location is shown.
1190 Turning this off for example for sparse trees makes them very compact.
1191 Instead of t, this can also be an alist specifying this option for different
1192 contexts. Valid contexts are
1193 agenda when exposing an entry from the agenda
1194 org-goto when using the command `org-goto' on key C-c C-j
1195 occur-tree when using the command `org-occur' on key C-c /
1196 tags-tree when constructing a sparse tree based on tags matches
1197 link-search when exposing search matches associated with a link
1198 mark-goto when exposing the jump goal of a mark
1199 bookmark-jump when exposing a bookmark location
1200 isearch when exiting from an incremental search
1201 default default for all contexts not set explicitly"
1202 :group 'org-reveal-location
1203 :type org-context-choice)
1205 (defcustom org-show-following-heading '((default . nil))
1206 "Non-nil means show following heading when revealing a location.
1207 Org-mode often shows locations in an org-mode file which might have
1208 been invisible before. When this is set, the heading following the
1209 match is shown.
1210 Turning this off for example for sparse trees makes them very compact,
1211 but makes it harder to edit the location of the match. In such a case,
1212 use the command \\[org-reveal] to show more context.
1213 Instead of t, this can also be an alist specifying this option for different
1214 contexts. See `org-show-hierarchy-above' for valid contexts."
1215 :group 'org-reveal-location
1216 :type org-context-choice)
1218 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
1219 "Non-nil means show all sibling heading when revealing a location.
1220 Org-mode often shows locations in an org-mode file which might have
1221 been invisible before. When this is set, the sibling of the current entry
1222 heading are all made visible. If `org-show-hierarchy-above' is t,
1223 the same happens on each level of the hierarchy above the current entry.
1225 By default this is on for the isearch context, off for all other contexts.
1226 Turning this off for example for sparse trees makes them very compact,
1227 but makes it harder to edit the location of the match. In such a case,
1228 use the command \\[org-reveal] to show more context.
1229 Instead of t, this can also be an alist specifying this option for different
1230 contexts. See `org-show-hierarchy-above' for valid contexts."
1231 :group 'org-reveal-location
1232 :type org-context-choice
1233 :version "24.4"
1234 :package-version '(Org . "8.0"))
1236 (defcustom org-show-entry-below '((default . nil))
1237 "Non-nil means show the entry below a headline when revealing a location.
1238 Org-mode often shows locations in an org-mode file which might have
1239 been invisible before. When this is set, the text below the headline that is
1240 exposed is also shown.
1242 By default this is off for all contexts.
1243 Instead of t, this can also be an alist specifying this option for different
1244 contexts. See `org-show-hierarchy-above' for valid contexts."
1245 :group 'org-reveal-location
1246 :type org-context-choice)
1248 (defcustom org-indirect-buffer-display 'other-window
1249 "How should indirect tree buffers be displayed?
1250 This applies to indirect buffers created with the commands
1251 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1252 Valid values are:
1253 current-window Display in the current window
1254 other-window Just display in another window.
1255 dedicated-frame Create one new frame, and re-use it each time.
1256 new-frame Make a new frame each time. Note that in this case
1257 previously-made indirect buffers are kept, and you need to
1258 kill these buffers yourself."
1259 :group 'org-structure
1260 :group 'org-agenda-windows
1261 :type '(choice
1262 (const :tag "In current window" current-window)
1263 (const :tag "In current frame, other window" other-window)
1264 (const :tag "Each time a new frame" new-frame)
1265 (const :tag "One dedicated frame" dedicated-frame)))
1267 (defcustom org-use-speed-commands nil
1268 "Non-nil means activate single letter commands at beginning of a headline.
1269 This may also be a function to test for appropriate locations where speed
1270 commands should be active.
1272 For example, to activate speed commands when the point is on any
1273 star at the beginning of the headline, you can do this:
1275 (setq org-use-speed-commands
1276 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1277 :group 'org-structure
1278 :type '(choice
1279 (const :tag "Never" nil)
1280 (const :tag "At beginning of headline stars" t)
1281 (function)))
1283 (defcustom org-speed-commands-user nil
1284 "Alist of additional speed commands.
1285 This list will be checked before `org-speed-commands-default'
1286 when the variable `org-use-speed-commands' is non-nil
1287 and when the cursor is at the beginning of a headline.
1288 The car if each entry is a string with a single letter, which must
1289 be assigned to `self-insert-command' in the global map.
1290 The cdr is either a command to be called interactively, a function
1291 to be called, or a form to be evaluated.
1292 An entry that is just a list with a single string will be interpreted
1293 as a descriptive headline that will be added when listing the speed
1294 commands in the Help buffer using the `?' speed command."
1295 :group 'org-structure
1296 :type '(repeat :value ("k" . ignore)
1297 (choice :value ("k" . ignore)
1298 (list :tag "Descriptive Headline" (string :tag "Headline"))
1299 (cons :tag "Letter and Command"
1300 (string :tag "Command letter")
1301 (choice
1302 (function)
1303 (sexp))))))
1305 (defcustom org-bookmark-names-plist
1306 '(:last-capture "org-capture-last-stored"
1307 :last-refile "org-refile-last-stored"
1308 :last-capture-marker "org-capture-last-stored-marker")
1309 "Names for bookmarks automatically set by some Org commands.
1310 This can provide strings as names for a number of bookmarks Org sets
1311 automatically. The following keys are currently implemented:
1312 :last-capture
1313 :last-capture-marker
1314 :last-refile
1315 When a key does not show up in the property list, the corresponding bookmark
1316 is not set."
1317 :group 'org-structure
1318 :type 'plist)
1320 (defgroup org-cycle nil
1321 "Options concerning visibility cycling in Org-mode."
1322 :tag "Org Cycle"
1323 :group 'org-structure)
1325 (defcustom org-cycle-skip-children-state-if-no-children t
1326 "Non-nil means skip CHILDREN state in entries that don't have any."
1327 :group 'org-cycle
1328 :type 'boolean)
1330 (defcustom org-cycle-max-level nil
1331 "Maximum level which should still be subject to visibility cycling.
1332 Levels higher than this will, for cycling, be treated as text, not a headline.
1333 When `org-odd-levels-only' is set, a value of N in this variable actually
1334 means 2N-1 stars as the limiting headline.
1335 When nil, cycle all levels.
1336 Note that the limiting level of cycling is also influenced by
1337 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1338 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1339 than its value."
1340 :group 'org-cycle
1341 :type '(choice
1342 (const :tag "No limit" nil)
1343 (integer :tag "Maximum level")))
1345 (defcustom org-hide-block-startup nil
1346 "Non-nil means entering Org-mode will fold all blocks.
1347 This can also be set in on a per-file basis with
1349 #+STARTUP: hideblocks
1350 #+STARTUP: showblocks"
1351 :group 'org-startup
1352 :group 'org-cycle
1353 :type 'boolean)
1355 (defcustom org-cycle-global-at-bob nil
1356 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1357 This makes it possible to do global cycling without having to use S-TAB or
1358 \\[universal-argument] TAB. For this special case to work, the first line
1359 of the buffer must not be a headline -- it may be empty or some other text.
1360 When used in this way, `org-cycle-hook' is disabled temporarily to make
1361 sure the cursor stays at the beginning of the buffer. When this option is
1362 nil, don't do anything special at the beginning of the buffer."
1363 :group 'org-cycle
1364 :type 'boolean)
1366 (defcustom org-cycle-level-after-item/entry-creation t
1367 "Non-nil means cycle entry level or item indentation in new empty entries.
1369 When the cursor is at the end of an empty headline, i.e., with only stars
1370 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1371 and then all possible ancestor states, before returning to the original state.
1372 This makes data entry extremely fast: M-RET to create a new headline,
1373 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1375 When the cursor is at the end of an empty plain list item, one TAB will
1376 make it a subitem, two or more tabs will back up to make this an item
1377 higher up in the item hierarchy."
1378 :group 'org-cycle
1379 :type 'boolean)
1381 (defcustom org-cycle-emulate-tab t
1382 "Where should `org-cycle' emulate TAB.
1383 nil Never
1384 white Only in completely white lines
1385 whitestart Only at the beginning of lines, before the first non-white char
1386 t Everywhere except in headlines
1387 exc-hl-bol Everywhere except at the start of a headline
1388 If TAB is used in a place where it does not emulate TAB, the current subtree
1389 visibility is cycled."
1390 :group 'org-cycle
1391 :type '(choice (const :tag "Never" nil)
1392 (const :tag "Only in completely white lines" white)
1393 (const :tag "Before first char in a line" whitestart)
1394 (const :tag "Everywhere except in headlines" t)
1395 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1397 (defcustom org-cycle-separator-lines 2
1398 "Number of empty lines needed to keep an empty line between collapsed trees.
1399 If you leave an empty line between the end of a subtree and the following
1400 headline, this empty line is hidden when the subtree is folded.
1401 Org-mode will leave (exactly) one empty line visible if the number of
1402 empty lines is equal or larger to the number given in this variable.
1403 So the default 2 means at least 2 empty lines after the end of a subtree
1404 are needed to produce free space between a collapsed subtree and the
1405 following headline.
1407 If the number is negative, and the number of empty lines is at least -N,
1408 all empty lines are shown.
1410 Special case: when 0, never leave empty lines in collapsed view."
1411 :group 'org-cycle
1412 :type 'integer)
1413 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1415 (defcustom org-pre-cycle-hook nil
1416 "Hook that is run before visibility cycling is happening.
1417 The function(s) in this hook must accept a single argument which indicates
1418 the new state that will be set right after running this hook. The
1419 argument is a symbol. Before a global state change, it can have the values
1420 `overview', `content', or `all'. Before a local state change, it can have
1421 the values `folded', `children', or `subtree'."
1422 :group 'org-cycle
1423 :type 'hook)
1425 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1426 org-cycle-hide-drawers
1427 org-cycle-hide-inline-tasks
1428 org-cycle-show-empty-lines
1429 org-optimize-window-after-visibility-change)
1430 "Hook that is run after `org-cycle' has changed the buffer visibility.
1431 The function(s) in this hook must accept a single argument which indicates
1432 the new state that was set by the most recent `org-cycle' command. The
1433 argument is a symbol. After a global state change, it can have the values
1434 `overview', `contents', or `all'. After a local state change, it can have
1435 the values `folded', `children', or `subtree'."
1436 :group 'org-cycle
1437 :type 'hook)
1439 (defgroup org-edit-structure nil
1440 "Options concerning structure editing in Org-mode."
1441 :tag "Org Edit Structure"
1442 :group 'org-structure)
1444 (defcustom org-odd-levels-only nil
1445 "Non-nil means skip even levels and only use odd levels for the outline.
1446 This has the effect that two stars are being added/taken away in
1447 promotion/demotion commands. It also influences how levels are
1448 handled by the exporters.
1449 Changing it requires restart of `font-lock-mode' to become effective
1450 for fontification also in regions already fontified.
1451 You may also set this on a per-file basis by adding one of the following
1452 lines to the buffer:
1454 #+STARTUP: odd
1455 #+STARTUP: oddeven"
1456 :group 'org-edit-structure
1457 :group 'org-appearance
1458 :type 'boolean)
1460 (defcustom org-adapt-indentation t
1461 "Non-nil means adapt indentation to outline node level.
1463 When this variable is set, Org assumes that you write outlines by
1464 indenting text in each node to align with the headline (after the
1465 stars). The following issues are influenced by this variable:
1467 - The indentation is increased by one space in a demotion
1468 command, and decreased by one in a promotion command. However,
1469 in the latter case, if shifting some line in the entry body
1470 would alter document structure (e.g., insert a new headline),
1471 indentation is not changed at all.
1473 - Property drawers and planning information is inserted indented
1474 when this variable is set. When nil, they will not be indented.
1476 - TAB indents a line relative to current level. The lines below
1477 a headline will be indented when this variable is set.
1479 Note that this is all about true indentation, by adding and
1480 removing space characters. See also `org-indent.el' which does
1481 level-dependent indentation in a virtual way, i.e. at display
1482 time in Emacs."
1483 :group 'org-edit-structure
1484 :type 'boolean)
1486 (defcustom org-special-ctrl-a/e nil
1487 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1489 When t, `C-a' will bring back the cursor to the beginning of the
1490 headline text, i.e. after the stars and after a possible TODO
1491 keyword. In an item, this will be the position after bullet and
1492 check-box, if any. When the cursor is already at that position,
1493 another `C-a' will bring it to the beginning of the line.
1495 `C-e' will jump to the end of the headline, ignoring the presence
1496 of tags in the headline. A second `C-e' will then jump to the
1497 true end of the line, after any tags. This also means that, when
1498 this variable is non-nil, `C-e' also will never jump beyond the
1499 end of the heading of a folded section, i.e. not after the
1500 ellipses.
1502 When set to the symbol `reversed', the first `C-a' or `C-e' works
1503 normally, going to the true line boundary first. Only a directly
1504 following, identical keypress will bring the cursor to the
1505 special positions.
1507 This may also be a cons cell where the behavior for `C-a' and
1508 `C-e' is set separately."
1509 :group 'org-edit-structure
1510 :type '(choice
1511 (const :tag "off" nil)
1512 (const :tag "on: after stars/bullet and before tags first" t)
1513 (const :tag "reversed: true line boundary first" reversed)
1514 (cons :tag "Set C-a and C-e separately"
1515 (choice :tag "Special C-a"
1516 (const :tag "off" nil)
1517 (const :tag "on: after stars/bullet first" t)
1518 (const :tag "reversed: before stars/bullet first" reversed))
1519 (choice :tag "Special C-e"
1520 (const :tag "off" nil)
1521 (const :tag "on: before tags first" t)
1522 (const :tag "reversed: after tags first" reversed)))))
1523 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1525 (defcustom org-special-ctrl-k nil
1526 "Non-nil means `C-k' will behave specially in headlines.
1527 When nil, `C-k' will call the default `kill-line' command.
1528 When t, the following will happen while the cursor is in the headline:
1530 - When the cursor is at the beginning of a headline, kill the entire
1531 line and possible the folded subtree below the line.
1532 - When in the middle of the headline text, kill the headline up to the tags.
1533 - When after the headline text, kill the tags."
1534 :group 'org-edit-structure
1535 :type 'boolean)
1537 (defcustom org-ctrl-k-protect-subtree nil
1538 "Non-nil means, do not delete a hidden subtree with C-k.
1539 When set to the symbol `error', simply throw an error when C-k is
1540 used to kill (part-of) a headline that has hidden text behind it.
1541 Any other non-nil value will result in a query to the user, if it is
1542 OK to kill that hidden subtree. When nil, kill without remorse."
1543 :group 'org-edit-structure
1544 :version "24.1"
1545 :type '(choice
1546 (const :tag "Do not protect hidden subtrees" nil)
1547 (const :tag "Protect hidden subtrees with a security query" t)
1548 (const :tag "Never kill a hidden subtree with C-k" error)))
1550 (defcustom org-special-ctrl-o t
1551 "Non-nil means, make `C-o' insert a row in tables."
1552 :group 'org-edit-structure
1553 :type 'boolean)
1555 (defcustom org-catch-invisible-edits nil
1556 "Check if in invisible region before inserting or deleting a character.
1557 Valid values are:
1559 nil Do not check, so just do invisible edits.
1560 error Throw an error and do nothing.
1561 show Make point visible, and do the requested edit.
1562 show-and-error Make point visible, then throw an error and abort the edit.
1563 smart Make point visible, and do insertion/deletion if it is
1564 adjacent to visible text and the change feels predictable.
1565 Never delete a previously invisible character or add in the
1566 middle or right after an invisible region. Basically, this
1567 allows insertion and backward-delete right before ellipses.
1568 FIXME: maybe in this case we should not even show?"
1569 :group 'org-edit-structure
1570 :version "24.1"
1571 :type '(choice
1572 (const :tag "Do not check" nil)
1573 (const :tag "Throw error when trying to edit" error)
1574 (const :tag "Unhide, but do not do the edit" show-and-error)
1575 (const :tag "Show invisible part and do the edit" show)
1576 (const :tag "Be smart and do the right thing" smart)))
1578 (defcustom org-yank-folded-subtrees t
1579 "Non-nil means when yanking subtrees, fold them.
1580 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1581 it starts with a heading and all other headings in it are either children
1582 or siblings, then fold all the subtrees. However, do this only if no
1583 text after the yank would be swallowed into a folded tree by this action."
1584 :group 'org-edit-structure
1585 :type 'boolean)
1587 (defcustom org-yank-adjusted-subtrees nil
1588 "Non-nil means when yanking subtrees, adjust the level.
1589 With this setting, `org-paste-subtree' is used to insert the subtree, see
1590 this function for details."
1591 :group 'org-edit-structure
1592 :type 'boolean)
1594 (defcustom org-M-RET-may-split-line '((default . t))
1595 "Non-nil means M-RET will split the line at the cursor position.
1596 When nil, it will go to the end of the line before making a
1597 new line.
1598 You may also set this option in a different way for different
1599 contexts. Valid contexts are:
1601 headline when creating a new headline
1602 item when creating a new item
1603 table in a table field
1604 default the value to be used for all contexts not explicitly
1605 customized"
1606 :group 'org-structure
1607 :group 'org-table
1608 :type '(choice
1609 (const :tag "Always" t)
1610 (const :tag "Never" nil)
1611 (repeat :greedy t :tag "Individual contexts"
1612 (cons
1613 (choice :tag "Context"
1614 (const headline)
1615 (const item)
1616 (const table)
1617 (const default))
1618 (boolean)))))
1621 (defcustom org-insert-heading-respect-content nil
1622 "Non-nil means insert new headings after the current subtree.
1623 When nil, the new heading is created directly after the current line.
1624 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1625 this variable on for the duration of the command."
1626 :group 'org-structure
1627 :type 'boolean)
1629 (defcustom org-blank-before-new-entry '((heading . auto)
1630 (plain-list-item . auto))
1631 "Should `org-insert-heading' leave a blank line before new heading/item?
1632 The value is an alist, with `heading' and `plain-list-item' as CAR,
1633 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1634 which case Org will look at the surrounding headings/items and try to
1635 make an intelligent decision whether to insert a blank line or not.
1637 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1638 the setting here is ignored and no empty line is inserted to avoid breaking
1639 the list structure."
1640 :group 'org-edit-structure
1641 :type '(list
1642 (cons (const heading)
1643 (choice (const :tag "Never" nil)
1644 (const :tag "Always" t)
1645 (const :tag "Auto" auto)))
1646 (cons (const plain-list-item)
1647 (choice (const :tag "Never" nil)
1648 (const :tag "Always" t)
1649 (const :tag "Auto" auto)))))
1651 (defcustom org-insert-heading-hook nil
1652 "Hook being run after inserting a new heading."
1653 :group 'org-edit-structure
1654 :type 'hook)
1656 (defcustom org-enable-fixed-width-editor t
1657 "Non-nil means lines starting with \":\" are treated as fixed-width.
1658 This currently only means they are never auto-wrapped.
1659 When nil, such lines will be treated like ordinary lines."
1660 :group 'org-edit-structure
1661 :type 'boolean)
1663 (defcustom org-goto-auto-isearch t
1664 "Non-nil means typing characters in `org-goto' starts incremental search.
1665 When nil, you can use these keybindings to navigate the buffer:
1667 q Quit the org-goto interface
1668 n Go to the next visible heading
1669 p Go to the previous visible heading
1670 f Go one heading forward on same level
1671 b Go one heading backward on same level
1672 u Go one heading up"
1673 :group 'org-edit-structure
1674 :type 'boolean)
1676 (defgroup org-sparse-trees nil
1677 "Options concerning sparse trees in Org-mode."
1678 :tag "Org Sparse Trees"
1679 :group 'org-structure)
1681 (defcustom org-highlight-sparse-tree-matches t
1682 "Non-nil means highlight all matches that define a sparse tree.
1683 The highlights will automatically disappear the next time the buffer is
1684 changed by an edit command."
1685 :group 'org-sparse-trees
1686 :type 'boolean)
1688 (defcustom org-remove-highlights-with-change t
1689 "Non-nil means any change to the buffer will remove temporary highlights.
1690 Such highlights are created by `org-occur' and `org-clock-display'.
1691 When nil, `C-c C-c' needs to be used to get rid of the highlights.
1692 The highlights created by `org-toggle-latex-fragment' always need
1693 `C-c C-x C-l' to be removed."
1694 :group 'org-sparse-trees
1695 :group 'org-time
1696 :type 'boolean)
1699 (defcustom org-occur-hook '(org-first-headline-recenter)
1700 "Hook that is run after `org-occur' has constructed a sparse tree.
1701 This can be used to recenter the window to show as much of the structure
1702 as possible."
1703 :group 'org-sparse-trees
1704 :type 'hook)
1706 (defgroup org-imenu-and-speedbar nil
1707 "Options concerning imenu and speedbar in Org-mode."
1708 :tag "Org Imenu and Speedbar"
1709 :group 'org-structure)
1711 (defcustom org-imenu-depth 2
1712 "The maximum level for Imenu access to Org-mode headlines.
1713 This also applied for speedbar access."
1714 :group 'org-imenu-and-speedbar
1715 :type 'integer)
1717 (defgroup org-table nil
1718 "Options concerning tables in Org-mode."
1719 :tag "Org Table"
1720 :group 'org)
1722 (defcustom org-enable-table-editor 'optimized
1723 "Non-nil means lines starting with \"|\" are handled by the table editor.
1724 When nil, such lines will be treated like ordinary lines.
1726 When equal to the symbol `optimized', the table editor will be optimized to
1727 do the following:
1728 - Automatic overwrite mode in front of whitespace in table fields.
1729 This makes the structure of the table stay in tact as long as the edited
1730 field does not exceed the column width.
1731 - Minimize the number of realigns. Normally, the table is aligned each time
1732 TAB or RET are pressed to move to another field. With optimization this
1733 happens only if changes to a field might have changed the column width.
1734 Optimization requires replacing the functions `self-insert-command',
1735 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1736 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1737 very good at guessing when a re-align will be necessary, but you can always
1738 force one with \\[org-ctrl-c-ctrl-c].
1740 If you would like to use the optimized version in Org-mode, but the
1741 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1743 This variable can be used to turn on and off the table editor during a session,
1744 but in order to toggle optimization, a restart is required.
1746 See also the variable `org-table-auto-blank-field'."
1747 :group 'org-table
1748 :type '(choice
1749 (const :tag "off" nil)
1750 (const :tag "on" t)
1751 (const :tag "on, optimized" optimized)))
1753 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1754 (version<= emacs-version "24.1"))
1755 "Non-nil means cluster self-insert commands for undo when possible.
1756 If this is set, then, like in the Emacs command loop, 20 consecutive
1757 characters will be undone together.
1758 This is configurable, because there is some impact on typing performance."
1759 :group 'org-table
1760 :type 'boolean)
1762 (defcustom org-table-tab-recognizes-table.el t
1763 "Non-nil means TAB will automatically notice a table.el table.
1764 When it sees such a table, it moves point into it and - if necessary -
1765 calls `table-recognize-table'."
1766 :group 'org-table-editing
1767 :type 'boolean)
1769 (defgroup org-link nil
1770 "Options concerning links in Org-mode."
1771 :tag "Org Link"
1772 :group 'org)
1774 (defvar org-link-abbrev-alist-local nil
1775 "Buffer-local version of `org-link-abbrev-alist', which see.
1776 The value of this is taken from the #+LINK lines.")
1777 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1779 (defcustom org-link-abbrev-alist nil
1780 "Alist of link abbreviations.
1781 The car of each element is a string, to be replaced at the start of a link.
1782 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1783 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1785 [[linkkey:tag][description]]
1787 The 'linkkey' must be a word word, starting with a letter, followed
1788 by letters, numbers, '-' or '_'.
1790 If REPLACE is a string, the tag will simply be appended to create the link.
1791 If the string contains \"%s\", the tag will be inserted there. If the string
1792 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1793 at that point (see the function `url-hexify-string'). If the string contains
1794 the specifier \"%(my-function)\", then the custom function `my-function' will
1795 be invoked: this function takes the tag as its only argument and must return
1796 a string.
1798 REPLACE may also be a function that will be called with the tag as the
1799 only argument to create the link, which should be returned as a string.
1801 See the manual for examples."
1802 :group 'org-link
1803 :type '(repeat
1804 (cons
1805 (string :tag "Protocol")
1806 (choice
1807 (string :tag "Format")
1808 (function)))))
1810 (defcustom org-descriptive-links t
1811 "Non-nil means Org will display descriptive links.
1812 E.g. [[http://orgmode.org][Org website]] will be displayed as
1813 \"Org Website\", hiding the link itself and just displaying its
1814 description. When set to `nil', Org will display the full links
1815 literally.
1817 You can interactively set the value of this variable by calling
1818 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1819 :group 'org-link
1820 :type 'boolean)
1822 (defcustom org-link-file-path-type 'adaptive
1823 "How the path name in file links should be stored.
1824 Valid values are:
1826 relative Relative to the current directory, i.e. the directory of the file
1827 into which the link is being inserted.
1828 absolute Absolute path, if possible with ~ for home directory.
1829 noabbrev Absolute path, no abbreviation of home directory.
1830 adaptive Use relative path for files in the current directory and sub-
1831 directories of it. For other files, use an absolute path."
1832 :group 'org-link
1833 :type '(choice
1834 (const relative)
1835 (const absolute)
1836 (const noabbrev)
1837 (const adaptive)))
1839 (defvaralias 'org-activate-links 'org-highlight-links)
1840 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1841 "Types of links that should be highlighted in Org-mode files.
1843 This is a list of symbols, each one of them leading to the
1844 highlighting of a certain link type.
1846 You can still open links that are not highlighted.
1848 In principle, it does not hurt to turn on highlighting for all
1849 link types. There may be a small gain when turning off unused
1850 link types. The types are:
1852 bracket The recommended [[link][description]] or [[link]] links with hiding.
1853 angle Links in angular brackets that may contain whitespace like
1854 <bbdb:Carsten Dominik>.
1855 plain Plain links in normal text, no whitespace, like http://google.com.
1856 radio Text that is matched by a radio target, see manual for details.
1857 tag Tag settings in a headline (link to tag search).
1858 date Time stamps (link to calendar).
1859 footnote Footnote labels.
1861 If you set this variable during an Emacs session, use `org-mode-restart'
1862 in the Org buffer so that the change takes effect."
1863 :group 'org-link
1864 :group 'org-appearance
1865 :type '(set :greedy t
1866 (const :tag "Double bracket links" bracket)
1867 (const :tag "Angular bracket links" angle)
1868 (const :tag "Plain text links" plain)
1869 (const :tag "Radio target matches" radio)
1870 (const :tag "Tags" tag)
1871 (const :tag "Timestamps" date)
1872 (const :tag "Footnotes" footnote)))
1874 (defcustom org-make-link-description-function nil
1875 "Function to use for generating link descriptions from links.
1876 When nil, the link location will be used. This function must take
1877 two parameters: the first one is the link, the second one is the
1878 description generated by `org-insert-link'. The function should
1879 return the description to use."
1880 :group 'org-link
1881 :type '(choice (const nil) (function)))
1883 (defgroup org-link-store nil
1884 "Options concerning storing links in Org-mode."
1885 :tag "Org Store Link"
1886 :group 'org-link)
1888 (defcustom org-url-hexify-p t
1889 "When non-nil, hexify URL when creating a link."
1890 :type 'boolean
1891 :version "24.3"
1892 :group 'org-link-store)
1894 (defcustom org-email-link-description-format "Email %c: %.30s"
1895 "Format of the description part of a link to an email or usenet message.
1896 The following %-escapes will be replaced by corresponding information:
1898 %F full \"From\" field
1899 %f name, taken from \"From\" field, address if no name
1900 %T full \"To\" field
1901 %t first name in \"To\" field, address if no name
1902 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1903 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1904 %s subject
1905 %d date
1906 %m message-id.
1908 You may use normal field width specification between the % and the letter.
1909 This is for example useful to limit the length of the subject.
1911 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1912 :group 'org-link-store
1913 :type 'string)
1915 (defcustom org-from-is-user-regexp
1916 (let (r1 r2)
1917 (when (and user-mail-address (not (string= user-mail-address "")))
1918 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1919 (when (and user-full-name (not (string= user-full-name "")))
1920 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1921 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1922 "Regexp matched against the \"From:\" header of an email or usenet message.
1923 It should match if the message is from the user him/herself."
1924 :group 'org-link-store
1925 :type 'regexp)
1927 (defcustom org-context-in-file-links t
1928 "Non-nil means file links from `org-store-link' contain context.
1929 A search string will be added to the file name with :: as separator and
1930 used to find the context when the link is activated by the command
1931 `org-open-at-point'. When this option is t, the entire active region
1932 will be placed in the search string of the file link. If set to a
1933 positive integer, only the first n lines of context will be stored.
1935 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1936 negates this setting for the duration of the command."
1937 :group 'org-link-store
1938 :type '(choice boolean integer))
1940 (defcustom org-keep-stored-link-after-insertion nil
1941 "Non-nil means keep link in list for entire session.
1943 The command `org-store-link' adds a link pointing to the current
1944 location to an internal list. These links accumulate during a session.
1945 The command `org-insert-link' can be used to insert links into any
1946 Org-mode file (offering completion for all stored links). When this
1947 option is nil, every link which has been inserted once using \\[org-insert-link]
1948 will be removed from the list, to make completing the unused links
1949 more efficient."
1950 :group 'org-link-store
1951 :type 'boolean)
1953 (defgroup org-link-follow nil
1954 "Options concerning following links in Org-mode."
1955 :tag "Org Follow Link"
1956 :group 'org-link)
1958 (defcustom org-link-translation-function nil
1959 "Function to translate links with different syntax to Org syntax.
1960 This can be used to translate links created for example by the Planner
1961 or emacs-wiki packages to Org syntax.
1962 The function must accept two parameters, a TYPE containing the link
1963 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1964 which is everything after the link protocol. It should return a cons
1965 with possibly modified values of type and path.
1966 Org contains a function for this, so if you set this variable to
1967 `org-translate-link-from-planner', you should be able follow many
1968 links created by planner."
1969 :group 'org-link-follow
1970 :type '(choice (const nil) (function)))
1972 (defcustom org-follow-link-hook nil
1973 "Hook that is run after a link has been followed."
1974 :group 'org-link-follow
1975 :type 'hook)
1977 (defcustom org-tab-follows-link nil
1978 "Non-nil means on links TAB will follow the link.
1979 Needs to be set before org.el is loaded.
1980 This really should not be used, it does not make sense, and the
1981 implementation is bad."
1982 :group 'org-link-follow
1983 :type 'boolean)
1985 (defcustom org-return-follows-link nil
1986 "Non-nil means on links RET will follow the link.
1987 In tables, the special behavior of RET has precedence."
1988 :group 'org-link-follow
1989 :type 'boolean)
1991 (defcustom org-mouse-1-follows-link
1992 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1993 "Non-nil means mouse-1 on a link will follow the link.
1994 A longer mouse click will still set point. Does not work on XEmacs.
1995 Needs to be set before org.el is loaded."
1996 :group 'org-link-follow
1997 :version "24.4"
1998 :package-version '(Org . "8.3")
1999 :type '(choice
2000 (const :tag "A double click follows the link" double)
2001 (const :tag "Unconditionally follow the link with mouse-1" t)
2002 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2004 (defcustom org-mark-ring-length 4
2005 "Number of different positions to be recorded in the ring.
2006 Changing this requires a restart of Emacs to work correctly."
2007 :group 'org-link-follow
2008 :type 'integer)
2010 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2011 "Non-nil means internal links in Org files must exactly match a headline.
2012 When nil, the link search tries to match a phrase with all words
2013 in the search text."
2014 :group 'org-link-follow
2015 :version "24.1"
2016 :type '(choice
2017 (const :tag "Use fuzzy text search" nil)
2018 (const :tag "Match only exact headline" t)
2019 (const :tag "Match exact headline or query to create it"
2020 query-to-create)))
2022 (defcustom org-link-frame-setup
2023 '((vm . vm-visit-folder-other-frame)
2024 (vm-imap . vm-visit-imap-folder-other-frame)
2025 (gnus . org-gnus-no-new-news)
2026 (file . find-file-other-window)
2027 (wl . wl-other-frame))
2028 "Setup the frame configuration for following links.
2029 When following a link with Emacs, it may often be useful to display
2030 this link in another window or frame. This variable can be used to
2031 set this up for the different types of links.
2032 For VM, use any of
2033 `vm-visit-folder'
2034 `vm-visit-folder-other-window'
2035 `vm-visit-folder-other-frame'
2036 For Gnus, use any of
2037 `gnus'
2038 `gnus-other-frame'
2039 `org-gnus-no-new-news'
2040 For FILE, use any of
2041 `find-file'
2042 `find-file-other-window'
2043 `find-file-other-frame'
2044 For Wanderlust use any of
2045 `wl'
2046 `wl-other-frame'
2047 For the calendar, use the variable `calendar-setup'.
2048 For BBDB, it is currently only possible to display the matches in
2049 another window."
2050 :group 'org-link-follow
2051 :type '(list
2052 (cons (const vm)
2053 (choice
2054 (const vm-visit-folder)
2055 (const vm-visit-folder-other-window)
2056 (const vm-visit-folder-other-frame)))
2057 (cons (const vm-imap)
2058 (choice
2059 (const vm-visit-imap-folder)
2060 (const vm-visit-imap-folder-other-window)
2061 (const vm-visit-imap-folder-other-frame)))
2062 (cons (const gnus)
2063 (choice
2064 (const gnus)
2065 (const gnus-other-frame)
2066 (const org-gnus-no-new-news)))
2067 (cons (const file)
2068 (choice
2069 (const find-file)
2070 (const find-file-other-window)
2071 (const find-file-other-frame)))
2072 (cons (const wl)
2073 (choice
2074 (const wl)
2075 (const wl-other-frame)))))
2077 (defcustom org-display-internal-link-with-indirect-buffer nil
2078 "Non-nil means use indirect buffer to display infile links.
2079 Activating internal links (from one location in a file to another location
2080 in the same file) normally just jumps to the location. When the link is
2081 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2082 is displayed in
2083 another window. When this option is set, the other window actually displays
2084 an indirect buffer clone of the current buffer, to avoid any visibility
2085 changes to the current buffer."
2086 :group 'org-link-follow
2087 :type 'boolean)
2089 (defcustom org-open-non-existing-files nil
2090 "Non-nil means `org-open-file' will open non-existing files.
2091 When nil, an error will be generated.
2092 This variable applies only to external applications because they
2093 might choke on non-existing files. If the link is to a file that
2094 will be opened in Emacs, the variable is ignored."
2095 :group 'org-link-follow
2096 :type 'boolean)
2098 (defcustom org-open-directory-means-index-dot-org nil
2099 "Non-nil means a link to a directory really means to index.org.
2100 When nil, following a directory link will run dired or open a finder/explorer
2101 window on that directory."
2102 :group 'org-link-follow
2103 :type 'boolean)
2105 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2106 "Non-nil means ask for confirmation before executing shell links.
2107 Shell links can be dangerous: just think about a link
2109 [[shell:rm -rf ~/*][Google Search]]
2111 This link would show up in your Org-mode document as \"Google Search\",
2112 but really it would remove your entire home directory.
2113 Therefore we advise against setting this variable to nil.
2114 Just change it to `y-or-n-p' if you want to confirm with a
2115 single keystroke rather than having to type \"yes\"."
2116 :group 'org-link-follow
2117 :type '(choice
2118 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2119 (const :tag "with y-or-n (faster)" y-or-n-p)
2120 (const :tag "no confirmation (dangerous)" nil)))
2121 (put 'org-confirm-shell-link-function
2122 'safe-local-variable
2123 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2125 (defcustom org-confirm-shell-link-not-regexp ""
2126 "A regexp to skip confirmation for shell links."
2127 :group 'org-link-follow
2128 :version "24.1"
2129 :type 'regexp)
2131 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2132 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2133 Elisp links can be dangerous: just think about a link
2135 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2137 This link would show up in your Org-mode document as \"Google Search\",
2138 but really it would remove your entire home directory.
2139 Therefore we advise against setting this variable to nil.
2140 Just change it to `y-or-n-p' if you want to confirm with a
2141 single keystroke rather than having to type \"yes\"."
2142 :group 'org-link-follow
2143 :type '(choice
2144 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2145 (const :tag "with y-or-n (faster)" y-or-n-p)
2146 (const :tag "no confirmation (dangerous)" nil)))
2147 (put 'org-confirm-shell-link-function
2148 'safe-local-variable
2149 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2151 (defcustom org-confirm-elisp-link-not-regexp ""
2152 "A regexp to skip confirmation for Elisp links."
2153 :group 'org-link-follow
2154 :version "24.1"
2155 :type 'regexp)
2157 (defconst org-file-apps-defaults-gnu
2158 '((remote . emacs)
2159 (system . mailcap)
2160 (t . mailcap))
2161 "Default file applications on a UNIX or GNU/Linux system.
2162 See `org-file-apps'.")
2164 (defconst org-file-apps-defaults-macosx
2165 '((remote . emacs)
2166 (t . "open %s")
2167 (system . "open %s")
2168 ("ps.gz" . "gv %s")
2169 ("eps.gz" . "gv %s")
2170 ("dvi" . "xdvi %s")
2171 ("fig" . "xfig %s"))
2172 "Default file applications on a MacOS X system.
2173 The system \"open\" is known as a default, but we use X11 applications
2174 for some files for which the OS does not have a good default.
2175 See `org-file-apps'.")
2177 (defconst org-file-apps-defaults-windowsnt
2178 (list
2179 '(remote . emacs)
2180 (cons t
2181 (list (if (featurep 'xemacs)
2182 'mswindows-shell-execute
2183 'w32-shell-execute)
2184 "open" 'file))
2185 (cons 'system
2186 (list (if (featurep 'xemacs)
2187 'mswindows-shell-execute
2188 'w32-shell-execute)
2189 "open" 'file)))
2190 "Default file applications on a Windows NT system.
2191 The system \"open\" is used for most files.
2192 See `org-file-apps'.")
2194 (defcustom org-file-apps
2195 '((auto-mode . emacs)
2196 ("\\.mm\\'" . default)
2197 ("\\.x?html?\\'" . default)
2198 ("\\.pdf\\'" . default))
2199 "External applications for opening `file:path' items in a document.
2200 Org-mode uses system defaults for different file types, but
2201 you can use this variable to set the application for a given file
2202 extension. The entries in this list are cons cells where the car identifies
2203 files and the cdr the corresponding command. Possible values for the
2204 file identifier are
2205 \"string\" A string as a file identifier can be interpreted in different
2206 ways, depending on its contents:
2208 - Alphanumeric characters only:
2209 Match links with this file extension.
2210 Example: (\"pdf\" . \"evince %s\")
2211 to open PDFs with evince.
2213 - Regular expression: Match links where the
2214 filename matches the regexp. If you want to
2215 use groups here, use shy groups.
2217 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2218 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2219 to open *.html and *.xhtml with firefox.
2221 - Regular expression which contains (non-shy) groups:
2222 Match links where the whole link, including \"::\", and
2223 anything after that, matches the regexp.
2224 In a custom command string, %1, %2, etc. are replaced with
2225 the parts of the link that were matched by the groups.
2226 For backwards compatibility, if a command string is given
2227 that does not use any of the group matches, this case is
2228 handled identically to the second one (i.e. match against
2229 file name only).
2230 In a custom lisp form, you can access the group matches with
2231 (match-string n link).
2233 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2234 to open [[file:document.pdf::5]] with evince at page 5.
2236 `directory' Matches a directory
2237 `remote' Matches a remote file, accessible through tramp or efs.
2238 Remote files most likely should be visited through Emacs
2239 because external applications cannot handle such paths.
2240 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2241 so all files Emacs knows how to handle. Using this with
2242 command `emacs' will open most files in Emacs. Beware that this
2243 will also open html files inside Emacs, unless you add
2244 (\"html\" . default) to the list as well.
2245 t Default for files not matched by any of the other options.
2246 `system' The system command to open files, like `open' on Windows
2247 and Mac OS X, and mailcap under GNU/Linux. This is the command
2248 that will be selected if you call `C-c C-o' with a double
2249 \\[universal-argument] \\[universal-argument] prefix.
2251 Possible values for the command are:
2252 `emacs' The file will be visited by the current Emacs process.
2253 `default' Use the default application for this file type, which is the
2254 association for t in the list, most likely in the system-specific
2255 part.
2256 This can be used to overrule an unwanted setting in the
2257 system-specific variable.
2258 `system' Use the system command for opening files, like \"open\".
2259 This command is specified by the entry whose car is `system'.
2260 Most likely, the system-specific version of this variable
2261 does define this command, but you can overrule/replace it
2262 here.
2263 string A command to be executed by a shell; %s will be replaced
2264 by the path to the file.
2265 sexp A Lisp form which will be evaluated. The file path will
2266 be available in the Lisp variable `file'.
2267 For more examples, see the system specific constants
2268 `org-file-apps-defaults-macosx'
2269 `org-file-apps-defaults-windowsnt'
2270 `org-file-apps-defaults-gnu'."
2271 :group 'org-link-follow
2272 :type '(repeat
2273 (cons (choice :value ""
2274 (string :tag "Extension")
2275 (const :tag "System command to open files" system)
2276 (const :tag "Default for unrecognized files" t)
2277 (const :tag "Remote file" remote)
2278 (const :tag "Links to a directory" directory)
2279 (const :tag "Any files that have Emacs modes"
2280 auto-mode))
2281 (choice :value ""
2282 (const :tag "Visit with Emacs" emacs)
2283 (const :tag "Use default" default)
2284 (const :tag "Use the system command" system)
2285 (string :tag "Command")
2286 (sexp :tag "Lisp form")))))
2288 (defcustom org-doi-server-url "http://dx.doi.org/"
2289 "The URL of the DOI server."
2290 :type 'string
2291 :version "24.3"
2292 :group 'org-link-follow)
2294 (defgroup org-refile nil
2295 "Options concerning refiling entries in Org-mode."
2296 :tag "Org Refile"
2297 :group 'org)
2299 (defcustom org-directory "~/org"
2300 "Directory with org files.
2301 This is just a default location to look for Org files. There is no need
2302 at all to put your files into this directory. It is only used in the
2303 following situations:
2305 1. When a capture template specifies a target file that is not an
2306 absolute path. The path will then be interpreted relative to
2307 `org-directory'
2308 2. When a capture note is filed away in an interactive way (when exiting the
2309 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2310 with `org-directory' as the default path."
2311 :group 'org-refile
2312 :group 'org-capture
2313 :type 'directory)
2315 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2316 "Default target for storing notes.
2317 Used as a fall back file for org-capture.el, for templates that
2318 do not specify a target file."
2319 :group 'org-refile
2320 :group 'org-capture
2321 :type '(choice
2322 (const :tag "Default from remember-data-file" nil)
2323 file))
2325 (defcustom org-goto-interface 'outline
2326 "The default interface to be used for `org-goto'.
2327 Allowed values are:
2328 outline The interface shows an outline of the relevant file
2329 and the correct heading is found by moving through
2330 the outline or by searching with incremental search.
2331 outline-path-completion Headlines in the current buffer are offered via
2332 completion. This is the interface also used by
2333 the refile command."
2334 :group 'org-refile
2335 :type '(choice
2336 (const :tag "Outline" outline)
2337 (const :tag "Outline-path-completion" outline-path-completion)))
2339 (defcustom org-goto-max-level 5
2340 "Maximum target level when running `org-goto' with refile interface."
2341 :group 'org-refile
2342 :type 'integer)
2344 (defcustom org-reverse-note-order nil
2345 "Non-nil means store new notes at the beginning of a file or entry.
2346 When nil, new notes will be filed to the end of a file or entry.
2347 This can also be a list with cons cells of regular expressions that
2348 are matched against file names, and values."
2349 :group 'org-capture
2350 :group 'org-refile
2351 :type '(choice
2352 (const :tag "Reverse always" t)
2353 (const :tag "Reverse never" nil)
2354 (repeat :tag "By file name regexp"
2355 (cons regexp boolean))))
2357 (defcustom org-log-refile nil
2358 "Information to record when a task is refiled.
2360 Possible values are:
2362 nil Don't add anything
2363 time Add a time stamp to the task
2364 note Prompt for a note and add it with template `org-log-note-headings'
2366 This option can also be set with on a per-file-basis with
2368 #+STARTUP: nologrefile
2369 #+STARTUP: logrefile
2370 #+STARTUP: lognoterefile
2372 You can have local logging settings for a subtree by setting the LOGGING
2373 property to one or more of these keywords.
2375 When bulk-refiling from the agenda, the value `note' is forbidden and
2376 will temporarily be changed to `time'."
2377 :group 'org-refile
2378 :group 'org-progress
2379 :version "24.1"
2380 :type '(choice
2381 (const :tag "No logging" nil)
2382 (const :tag "Record timestamp" time)
2383 (const :tag "Record timestamp with note." note)))
2385 (defcustom org-refile-targets nil
2386 "Targets for refiling entries with \\[org-refile].
2387 This is a list of cons cells. Each cell contains:
2388 - a specification of the files to be considered, either a list of files,
2389 or a symbol whose function or variable value will be used to retrieve
2390 a file name or a list of file names. If you use `org-agenda-files' for
2391 that, all agenda files will be scanned for targets. Nil means consider
2392 headings in the current buffer.
2393 - A specification of how to find candidate refile targets. This may be
2394 any of:
2395 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2396 This tag has to be present in all target headlines, inheritance will
2397 not be considered.
2398 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2399 todo keyword.
2400 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2401 headlines that are refiling targets.
2402 - a cons cell (:level . N). Any headline of level N is considered a target.
2403 Note that, when `org-odd-levels-only' is set, level corresponds to
2404 order in hierarchy, not to the number of stars.
2405 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2406 Note that, when `org-odd-levels-only' is set, level corresponds to
2407 order in hierarchy, not to the number of stars.
2409 Each element of this list generates a set of possible targets.
2410 The union of these sets is presented (with completion) to
2411 the user by `org-refile'.
2413 You can set the variable `org-refile-target-verify-function' to a function
2414 to verify each headline found by the simple criteria above.
2416 When this variable is nil, all top-level headlines in the current buffer
2417 are used, equivalent to the value `((nil . (:level . 1))'."
2418 :group 'org-refile
2419 :type '(repeat
2420 (cons
2421 (choice :value org-agenda-files
2422 (const :tag "All agenda files" org-agenda-files)
2423 (const :tag "Current buffer" nil)
2424 (function) (variable) (file))
2425 (choice :tag "Identify target headline by"
2426 (cons :tag "Specific tag" (const :value :tag) (string))
2427 (cons :tag "TODO keyword" (const :value :todo) (string))
2428 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2429 (cons :tag "Level number" (const :value :level) (integer))
2430 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2432 (defcustom org-refile-target-verify-function nil
2433 "Function to verify if the headline at point should be a refile target.
2434 The function will be called without arguments, with point at the
2435 beginning of the headline. It should return t and leave point
2436 where it is if the headline is a valid target for refiling.
2438 If the target should not be selected, the function must return nil.
2439 In addition to this, it may move point to a place from where the search
2440 should be continued. For example, the function may decide that the entire
2441 subtree of the current entry should be excluded and move point to the end
2442 of the subtree."
2443 :group 'org-refile
2444 :type '(choice
2445 (const nil)
2446 (function)))
2448 (defcustom org-refile-use-cache nil
2449 "Non-nil means cache refile targets to speed up the process.
2450 The cache for a particular file will be updated automatically when
2451 the buffer has been killed, or when any of the marker used for flagging
2452 refile targets no longer points at a live buffer.
2453 If you have added new entries to a buffer that might themselves be targets,
2454 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2455 find that easier, `C-u C-u C-u C-c C-w'."
2456 :group 'org-refile
2457 :version "24.1"
2458 :type 'boolean)
2460 (defcustom org-refile-use-outline-path nil
2461 "Non-nil means provide refile targets as paths.
2462 So a level 3 headline will be available as level1/level2/level3.
2464 When the value is `file', also include the file name (without directory)
2465 into the path. In this case, you can also stop the completion after
2466 the file name, to get entries inserted as top level in the file.
2468 When `full-file-path', include the full file path."
2469 :group 'org-refile
2470 :type '(choice
2471 (const :tag "Not" nil)
2472 (const :tag "Yes" t)
2473 (const :tag "Start with file name" file)
2474 (const :tag "Start with full file path" full-file-path)))
2476 (defcustom org-outline-path-complete-in-steps t
2477 "Non-nil means complete the outline path in hierarchical steps.
2478 When Org-mode uses the refile interface to select an outline path
2479 \(see variable `org-refile-use-outline-path'), the completion of
2480 the path can be done is a single go, or if can be done in steps down
2481 the headline hierarchy. Going in steps is probably the best if you
2482 do not use a special completion package like `ido' or `icicles'.
2483 However, when using these packages, going in one step can be very
2484 fast, while still showing the whole path to the entry."
2485 :group 'org-refile
2486 :type 'boolean)
2488 (defcustom org-refile-allow-creating-parent-nodes nil
2489 "Non-nil means allow to create new nodes as refile targets.
2490 New nodes are then created by adding \"/new node name\" to the completion
2491 of an existing node. When the value of this variable is `confirm',
2492 new node creation must be confirmed by the user (recommended).
2493 When nil, the completion must match an existing entry.
2495 Note that, if the new heading is not seen by the criteria
2496 listed in `org-refile-targets', multiple instances of the same
2497 heading would be created by trying again to file under the new
2498 heading."
2499 :group 'org-refile
2500 :type '(choice
2501 (const :tag "Never" nil)
2502 (const :tag "Always" t)
2503 (const :tag "Prompt for confirmation" confirm)))
2505 (defcustom org-refile-active-region-within-subtree nil
2506 "Non-nil means also refile active region within a subtree.
2508 By default `org-refile' doesn't allow refiling regions if they
2509 don't contain a set of subtrees, but it might be convenient to
2510 do so sometimes: in that case, the first line of the region is
2511 converted to a headline before refiling."
2512 :group 'org-refile
2513 :version "24.1"
2514 :type 'boolean)
2516 (defgroup org-todo nil
2517 "Options concerning TODO items in Org-mode."
2518 :tag "Org TODO"
2519 :group 'org)
2521 (defgroup org-progress nil
2522 "Options concerning Progress logging in Org-mode."
2523 :tag "Org Progress"
2524 :group 'org-time)
2526 (defvar org-todo-interpretation-widgets
2527 '((:tag "Sequence (cycling hits every state)" sequence)
2528 (:tag "Type (cycling directly to DONE)" type))
2529 "The available interpretation symbols for customizing `org-todo-keywords'.
2530 Interested libraries should add to this list.")
2532 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2533 "List of TODO entry keyword sequences and their interpretation.
2534 \\<org-mode-map>This is a list of sequences.
2536 Each sequence starts with a symbol, either `sequence' or `type',
2537 indicating if the keywords should be interpreted as a sequence of
2538 action steps, or as different types of TODO items. The first
2539 keywords are states requiring action - these states will select a headline
2540 for inclusion into the global TODO list Org-mode produces. If one of
2541 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2542 signify that no further action is necessary. If \"|\" is not found,
2543 the last keyword is treated as the only DONE state of the sequence.
2545 The command \\[org-todo] cycles an entry through these states, and one
2546 additional state where no keyword is present. For details about this
2547 cycling, see the manual.
2549 TODO keywords and interpretation can also be set on a per-file basis with
2550 the special #+SEQ_TODO and #+TYP_TODO lines.
2552 Each keyword can optionally specify a character for fast state selection
2553 \(in combination with the variable `org-use-fast-todo-selection')
2554 and specifiers for state change logging, using the same syntax that
2555 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2556 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2557 indicates to record a time stamp each time this state is selected.
2559 Each keyword may also specify if a timestamp or a note should be
2560 recorded when entering or leaving the state, by adding additional
2561 characters in the parenthesis after the keyword. This looks like this:
2562 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2563 record only the time of the state change. With X and Y being either
2564 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2565 Y when leaving the state if and only if the *target* state does not
2566 define X. You may omit any of the fast-selection key or X or /Y,
2567 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2569 For backward compatibility, this variable may also be just a list
2570 of keywords. In this case the interpretation (sequence or type) will be
2571 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2572 :group 'org-todo
2573 :group 'org-keywords
2574 :type '(choice
2575 (repeat :tag "Old syntax, just keywords"
2576 (string :tag "Keyword"))
2577 (repeat :tag "New syntax"
2578 (cons
2579 (choice
2580 :tag "Interpretation"
2581 ;;Quick and dirty way to see
2582 ;;`org-todo-interpretations'. This takes the
2583 ;;place of item arguments
2584 :convert-widget
2585 (lambda (widget)
2586 (widget-put widget
2587 :args (mapcar
2588 (lambda (x)
2589 (widget-convert
2590 (cons 'const x)))
2591 org-todo-interpretation-widgets))
2592 widget))
2593 (repeat
2594 (string :tag "Keyword"))))))
2596 (defvar org-todo-keywords-1 nil
2597 "All TODO and DONE keywords active in a buffer.")
2598 (make-variable-buffer-local 'org-todo-keywords-1)
2599 (defvar org-todo-keywords-for-agenda nil)
2600 (defvar org-done-keywords-for-agenda nil)
2601 (defvar org-todo-keyword-alist-for-agenda nil)
2602 (defvar org-tag-alist-for-agenda nil
2603 "Alist of all tags from all agenda files.")
2604 (defvar org-tag-groups-alist-for-agenda nil
2605 "Alist of all groups tags from all current agenda files.")
2606 (defvar org-tag-groups-alist nil)
2607 (make-variable-buffer-local 'org-tag-groups-alist)
2608 (defvar org-agenda-contributing-files nil)
2609 (defvar org-not-done-keywords nil)
2610 (make-variable-buffer-local 'org-not-done-keywords)
2611 (defvar org-done-keywords nil)
2612 (make-variable-buffer-local 'org-done-keywords)
2613 (defvar org-todo-heads nil)
2614 (make-variable-buffer-local 'org-todo-heads)
2615 (defvar org-todo-sets nil)
2616 (make-variable-buffer-local 'org-todo-sets)
2617 (defvar org-todo-log-states nil)
2618 (make-variable-buffer-local 'org-todo-log-states)
2619 (defvar org-todo-kwd-alist nil)
2620 (make-variable-buffer-local 'org-todo-kwd-alist)
2621 (defvar org-todo-key-alist nil)
2622 (make-variable-buffer-local 'org-todo-key-alist)
2623 (defvar org-todo-key-trigger nil)
2624 (make-variable-buffer-local 'org-todo-key-trigger)
2626 (defcustom org-todo-interpretation 'sequence
2627 "Controls how TODO keywords are interpreted.
2628 This variable is in principle obsolete and is only used for
2629 backward compatibility, if the interpretation of todo keywords is
2630 not given already in `org-todo-keywords'. See that variable for
2631 more information."
2632 :group 'org-todo
2633 :group 'org-keywords
2634 :type '(choice (const sequence)
2635 (const type)))
2637 (defcustom org-use-fast-todo-selection t
2638 "Non-nil means use the fast todo selection scheme with C-c C-t.
2639 This variable describes if and under what circumstances the cycling
2640 mechanism for TODO keywords will be replaced by a single-key, direct
2641 selection scheme.
2643 When nil, fast selection is never used.
2645 When the symbol `prefix', it will be used when `org-todo' is called
2646 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2647 `C-u t' in an agenda buffer.
2649 When t, fast selection is used by default. In this case, the prefix
2650 argument forces cycling instead.
2652 In all cases, the special interface is only used if access keys have
2653 actually been assigned by the user, i.e. if keywords in the configuration
2654 are followed by a letter in parenthesis, like TODO(t)."
2655 :group 'org-todo
2656 :type '(choice
2657 (const :tag "Never" nil)
2658 (const :tag "By default" t)
2659 (const :tag "Only with C-u C-c C-t" prefix)))
2661 (defcustom org-provide-todo-statistics t
2662 "Non-nil means update todo statistics after insert and toggle.
2663 ALL-HEADLINES means update todo statistics by including headlines
2664 with no TODO keyword as well, counting them as not done.
2665 A list of TODO keywords means the same, but skip keywords that are
2666 not in this list.
2667 When set to a list of two lists, the first list contains keywords
2668 to consider as TODO keywords, the second list contains keywords
2669 to consider as DONE keywords.
2671 When this is set, todo statistics is updated in the parent of the
2672 current entry each time a todo state is changed."
2673 :group 'org-todo
2674 :type '(choice
2675 (const :tag "Yes, only for TODO entries" t)
2676 (const :tag "Yes, including all entries" all-headlines)
2677 (repeat :tag "Yes, for TODOs in this list"
2678 (string :tag "TODO keyword"))
2679 (list :tag "Yes, for TODOs and DONEs in these lists"
2680 (repeat (string :tag "TODO keyword"))
2681 (repeat (string :tag "DONE keyword")))
2682 (other :tag "No TODO statistics" nil)))
2684 (defcustom org-hierarchical-todo-statistics t
2685 "Non-nil means TODO statistics covers just direct children.
2686 When nil, all entries in the subtree are considered.
2687 This has only an effect if `org-provide-todo-statistics' is set.
2688 To set this to nil for only a single subtree, use a COOKIE_DATA
2689 property and include the word \"recursive\" into the value."
2690 :group 'org-todo
2691 :type 'boolean)
2693 (defcustom org-after-todo-state-change-hook nil
2694 "Hook which is run after the state of a TODO item was changed.
2695 The new state (a string with a TODO keyword, or nil) is available in the
2696 Lisp variable `org-state'."
2697 :group 'org-todo
2698 :type 'hook)
2700 (defvar org-blocker-hook nil
2701 "Hook for functions that are allowed to block a state change.
2703 Functions in this hook should not modify the buffer.
2704 Each function gets as its single argument a property list,
2705 see `org-trigger-hook' for more information about this list.
2707 If any of the functions in this hook returns nil, the state change
2708 is blocked.")
2710 (defvar org-trigger-hook nil
2711 "Hook for functions that are triggered by a state change.
2713 Each function gets as its single argument a property list with at
2714 least the following elements:
2716 (:type type-of-change :position pos-at-entry-start
2717 :from old-state :to new-state)
2719 Depending on the type, more properties may be present.
2721 This mechanism is currently implemented for:
2723 TODO state changes
2724 ------------------
2725 :type todo-state-change
2726 :from previous state (keyword as a string), or nil, or a symbol
2727 'todo' or 'done', to indicate the general type of state.
2728 :to new state, like in :from")
2730 (defcustom org-enforce-todo-dependencies nil
2731 "Non-nil means undone TODO entries will block switching the parent to DONE.
2732 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2733 be blocked if any prior sibling is not yet done.
2734 Finally, if the parent is blocked because of ordered siblings of its own,
2735 the child will also be blocked."
2736 :set (lambda (var val)
2737 (set var val)
2738 (if val
2739 (add-hook 'org-blocker-hook
2740 'org-block-todo-from-children-or-siblings-or-parent)
2741 (remove-hook 'org-blocker-hook
2742 'org-block-todo-from-children-or-siblings-or-parent)))
2743 :group 'org-todo
2744 :type 'boolean)
2746 (defcustom org-enforce-todo-checkbox-dependencies nil
2747 "Non-nil means unchecked boxes will block switching the parent to DONE.
2748 When this is nil, checkboxes have no influence on switching TODO states.
2749 When non-nil, you first need to check off all check boxes before the TODO
2750 entry can be switched to DONE.
2751 This variable needs to be set before org.el is loaded, and you need to
2752 restart Emacs after a change to make the change effective. The only way
2753 to change is while Emacs is running is through the customize interface."
2754 :set (lambda (var val)
2755 (set var val)
2756 (if val
2757 (add-hook 'org-blocker-hook
2758 'org-block-todo-from-checkboxes)
2759 (remove-hook 'org-blocker-hook
2760 'org-block-todo-from-checkboxes)))
2761 :group 'org-todo
2762 :type 'boolean)
2764 (defcustom org-treat-insert-todo-heading-as-state-change nil
2765 "Non-nil means inserting a TODO heading is treated as state change.
2766 So when the command \\[org-insert-todo-heading] is used, state change
2767 logging will apply if appropriate. When nil, the new TODO item will
2768 be inserted directly, and no logging will take place."
2769 :group 'org-todo
2770 :type 'boolean)
2772 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2773 "Non-nil means switching TODO states with S-cursor counts as state change.
2774 This is the default behavior. However, setting this to nil allows a
2775 convenient way to select a TODO state and bypass any logging associated
2776 with that."
2777 :group 'org-todo
2778 :type 'boolean)
2780 (defcustom org-todo-state-tags-triggers nil
2781 "Tag changes that should be triggered by TODO state changes.
2782 This is a list. Each entry is
2784 (state-change (tag . flag) .......)
2786 State-change can be a string with a state, and empty string to indicate the
2787 state that has no TODO keyword, or it can be one of the symbols `todo'
2788 or `done', meaning any not-done or done state, respectively."
2789 :group 'org-todo
2790 :group 'org-tags
2791 :type '(repeat
2792 (cons (choice :tag "When changing to"
2793 (const :tag "Not-done state" todo)
2794 (const :tag "Done state" done)
2795 (string :tag "State"))
2796 (repeat
2797 (cons :tag "Tag action"
2798 (string :tag "Tag")
2799 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2801 (defcustom org-log-done nil
2802 "Information to record when a task moves to the DONE state.
2804 Possible values are:
2806 nil Don't add anything, just change the keyword
2807 time Add a time stamp to the task
2808 note Prompt for a note and add it with template `org-log-note-headings'
2810 This option can also be set with on a per-file-basis with
2812 #+STARTUP: nologdone
2813 #+STARTUP: logdone
2814 #+STARTUP: lognotedone
2816 You can have local logging settings for a subtree by setting the LOGGING
2817 property to one or more of these keywords."
2818 :group 'org-todo
2819 :group 'org-progress
2820 :type '(choice
2821 (const :tag "No logging" nil)
2822 (const :tag "Record CLOSED timestamp" time)
2823 (const :tag "Record CLOSED timestamp with note." note)))
2825 ;; Normalize old uses of org-log-done.
2826 (cond
2827 ((eq org-log-done t) (setq org-log-done 'time))
2828 ((and (listp org-log-done) (memq 'done org-log-done))
2829 (setq org-log-done 'note)))
2831 (defcustom org-log-reschedule nil
2832 "Information to record when the scheduling date of a tasks is modified.
2834 Possible values are:
2836 nil Don't add anything, just change the date
2837 time Add a time stamp to the task
2838 note Prompt for a note and add it with template `org-log-note-headings'
2840 This option can also be set with on a per-file-basis with
2842 #+STARTUP: nologreschedule
2843 #+STARTUP: logreschedule
2844 #+STARTUP: lognotereschedule"
2845 :group 'org-todo
2846 :group 'org-progress
2847 :type '(choice
2848 (const :tag "No logging" nil)
2849 (const :tag "Record timestamp" time)
2850 (const :tag "Record timestamp with note." note)))
2852 (defcustom org-log-redeadline nil
2853 "Information to record when the deadline date of a tasks is modified.
2855 Possible values are:
2857 nil Don't add anything, just change the date
2858 time Add a time stamp to the task
2859 note Prompt for a note and add it with template `org-log-note-headings'
2861 This option can also be set with on a per-file-basis with
2863 #+STARTUP: nologredeadline
2864 #+STARTUP: logredeadline
2865 #+STARTUP: lognoteredeadline
2867 You can have local logging settings for a subtree by setting the LOGGING
2868 property to one or more of these keywords."
2869 :group 'org-todo
2870 :group 'org-progress
2871 :type '(choice
2872 (const :tag "No logging" nil)
2873 (const :tag "Record timestamp" time)
2874 (const :tag "Record timestamp with note." note)))
2876 (defcustom org-log-note-clock-out nil
2877 "Non-nil means record a note when clocking out of an item.
2878 This can also be configured on a per-file basis by adding one of
2879 the following lines anywhere in the buffer:
2881 #+STARTUP: lognoteclock-out
2882 #+STARTUP: nolognoteclock-out"
2883 :group 'org-todo
2884 :group 'org-progress
2885 :type 'boolean)
2887 (defcustom org-log-done-with-time t
2888 "Non-nil means the CLOSED time stamp will contain date and time.
2889 When nil, only the date will be recorded."
2890 :group 'org-progress
2891 :type 'boolean)
2893 (defcustom org-log-note-headings
2894 '((done . "CLOSING NOTE %t")
2895 (state . "State %-12s from %-12S %t")
2896 (note . "Note taken on %t")
2897 (reschedule . "Rescheduled from %S on %t")
2898 (delschedule . "Not scheduled, was %S on %t")
2899 (redeadline . "New deadline from %S on %t")
2900 (deldeadline . "Removed deadline, was %S on %t")
2901 (refile . "Refiled on %t")
2902 (clock-out . ""))
2903 "Headings for notes added to entries.
2904 The value is an alist, with the car being a symbol indicating the note
2905 context, and the cdr is the heading to be used. The heading may also be the
2906 empty string.
2907 %t in the heading will be replaced by a time stamp.
2908 %T will be an active time stamp instead the default inactive one
2909 %d will be replaced by a short-format time stamp.
2910 %D will be replaced by an active short-format time stamp.
2911 %s will be replaced by the new TODO state, in double quotes.
2912 %S will be replaced by the old TODO state, in double quotes.
2913 %u will be replaced by the user name.
2914 %U will be replaced by the full user name.
2916 In fact, it is not a good idea to change the `state' entry, because
2917 agenda log mode depends on the format of these entries."
2918 :group 'org-todo
2919 :group 'org-progress
2920 :type '(list :greedy t
2921 (cons (const :tag "Heading when closing an item" done) string)
2922 (cons (const :tag
2923 "Heading when changing todo state (todo sequence only)"
2924 state) string)
2925 (cons (const :tag "Heading when just taking a note" note) string)
2926 (cons (const :tag "Heading when rescheduling" reschedule) string)
2927 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2928 (cons (const :tag "Heading when changing deadline" redeadline) string)
2929 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2930 (cons (const :tag "Heading when refiling" refile) string)
2931 (cons (const :tag "Heading when clocking out" clock-out) string)))
2933 (unless (assq 'note org-log-note-headings)
2934 (push '(note . "%t") org-log-note-headings))
2936 (defcustom org-log-into-drawer nil
2937 "Non-nil means insert state change notes and time stamps into a drawer.
2938 When nil, state changes notes will be inserted after the headline and
2939 any scheduling and clock lines, but not inside a drawer.
2941 The value of this variable should be the name of the drawer to use.
2942 LOGBOOK is proposed as the default drawer for this purpose, you can
2943 also set this to a string to define the drawer of your choice.
2945 A value of t is also allowed, representing \"LOGBOOK\".
2947 A value of t or nil can also be set with on a per-file-basis with
2949 #+STARTUP: logdrawer
2950 #+STARTUP: nologdrawer
2952 If this variable is set, `org-log-state-notes-insert-after-drawers'
2953 will be ignored.
2955 You can set the property LOG_INTO_DRAWER to overrule this setting for
2956 a subtree.
2958 Do not check directly this variable in a Lisp program. Call
2959 function `org-log-into-drawer' instead."
2960 :group 'org-todo
2961 :group 'org-progress
2962 :type '(choice
2963 (const :tag "Not into a drawer" nil)
2964 (const :tag "LOGBOOK" t)
2965 (string :tag "Other")))
2967 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2969 (defun org-log-into-drawer ()
2970 "Name of the log drawer, as a string, or nil.
2971 This is the value of `org-log-into-drawer'. However, if the
2972 current entry has or inherits a LOG_INTO_DRAWER property, it will
2973 be used instead of the default value."
2974 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2975 (cond ((equal p "nil") nil)
2976 ((equal p "t") "LOGBOOK")
2977 ((stringp p) p)
2978 (p "LOGBOOK")
2979 ((stringp org-log-into-drawer) org-log-into-drawer)
2980 (org-log-into-drawer "LOGBOOK"))))
2982 (defcustom org-log-state-notes-insert-after-drawers nil
2983 "Non-nil means insert state change notes after any drawers in entry.
2984 Only the drawers that *immediately* follow the headline and the
2985 deadline/scheduled line are skipped.
2986 When nil, insert notes right after the heading and perhaps the line
2987 with deadline/scheduling if present.
2989 This variable will have no effect if `org-log-into-drawer' is
2990 set."
2991 :group 'org-todo
2992 :group 'org-progress
2993 :type 'boolean)
2995 (defcustom org-log-states-order-reversed t
2996 "Non-nil means the latest state note will be directly after heading.
2997 When nil, the state change notes will be ordered according to time.
2999 This option can also be set with on a per-file-basis with
3001 #+STARTUP: logstatesreversed
3002 #+STARTUP: nologstatesreversed"
3003 :group 'org-todo
3004 :group 'org-progress
3005 :type 'boolean)
3007 (defcustom org-todo-repeat-to-state nil
3008 "The TODO state to which a repeater should return the repeating task.
3009 By default this is the first task in a TODO sequence, or the previous state
3010 in a TODO_TYP set. But you can specify another task here.
3011 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3012 :group 'org-todo
3013 :version "24.1"
3014 :type '(choice (const :tag "Head of sequence" nil)
3015 (string :tag "Specific state")))
3017 (defcustom org-log-repeat 'time
3018 "Non-nil means record moving through the DONE state when triggering repeat.
3019 An auto-repeating task is immediately switched back to TODO when
3020 marked DONE. If you are not logging state changes (by adding \"@\"
3021 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3022 record a closing note, there will be no record of the task moving
3023 through DONE. This variable forces taking a note anyway.
3025 nil Don't force a record
3026 time Record a time stamp
3027 note Prompt for a note and add it with template `org-log-note-headings'
3029 This option can also be set with on a per-file-basis with
3031 #+STARTUP: nologrepeat
3032 #+STARTUP: logrepeat
3033 #+STARTUP: lognoterepeat
3035 You can have local logging settings for a subtree by setting the LOGGING
3036 property to one or more of these keywords."
3037 :group 'org-todo
3038 :group 'org-progress
3039 :type '(choice
3040 (const :tag "Don't force a record" nil)
3041 (const :tag "Force recording the DONE state" time)
3042 (const :tag "Force recording a note with the DONE state" note)))
3045 (defgroup org-priorities nil
3046 "Priorities in Org-mode."
3047 :tag "Org Priorities"
3048 :group 'org-todo)
3050 (defcustom org-enable-priority-commands t
3051 "Non-nil means priority commands are active.
3052 When nil, these commands will be disabled, so that you never accidentally
3053 set a priority."
3054 :group 'org-priorities
3055 :type 'boolean)
3057 (defcustom org-highest-priority ?A
3058 "The highest priority of TODO items. A character like ?A, ?B etc.
3059 Must have a smaller ASCII number than `org-lowest-priority'."
3060 :group 'org-priorities
3061 :type 'character)
3063 (defcustom org-lowest-priority ?C
3064 "The lowest priority of TODO items. A character like ?A, ?B etc.
3065 Must have a larger ASCII number than `org-highest-priority'."
3066 :group 'org-priorities
3067 :type 'character)
3069 (defcustom org-default-priority ?B
3070 "The default priority of TODO items.
3071 This is the priority an item gets if no explicit priority is given.
3072 When starting to cycle on an empty priority the first step in the cycle
3073 depends on `org-priority-start-cycle-with-default'. The resulting first
3074 step priority must not exceed the range from `org-highest-priority' to
3075 `org-lowest-priority' which means that `org-default-priority' has to be
3076 in this range exclusive or inclusive the range boundaries. Else the
3077 first step refuses to set the default and the second will fall back
3078 to (depending on the command used) the highest or lowest priority."
3079 :group 'org-priorities
3080 :type 'character)
3082 (defcustom org-priority-start-cycle-with-default t
3083 "Non-nil means start with default priority when starting to cycle.
3084 When this is nil, the first step in the cycle will be (depending on the
3085 command used) one higher or lower than the default priority.
3086 See also `org-default-priority'."
3087 :group 'org-priorities
3088 :type 'boolean)
3090 (defcustom org-get-priority-function nil
3091 "Function to extract the priority from a string.
3092 The string is normally the headline. If this is nil Org computes the
3093 priority from the priority cookie like [#A] in the headline. It returns
3094 an integer, increasing by 1000 for each priority level.
3095 The user can set a different function here, which should take a string
3096 as an argument and return the numeric priority."
3097 :group 'org-priorities
3098 :version "24.1"
3099 :type '(choice
3100 (const nil)
3101 (function)))
3103 (defgroup org-time nil
3104 "Options concerning time stamps and deadlines in Org-mode."
3105 :tag "Org Time"
3106 :group 'org)
3108 (defcustom org-time-stamp-rounding-minutes '(0 5)
3109 "Number of minutes to round time stamps to.
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 `C-c .' or `C-c !',
3120 and by using a prefix arg to `S-up/down' to specify the exact number
3121 of minutes to shift."
3122 :group 'org-time
3123 :get (lambda (var) ; Make sure both elements are there
3124 (if (integerp (default-value var))
3125 (list (default-value var) 5)
3126 (default-value var)))
3127 :type '(list
3128 (integer :tag "when inserting times")
3129 (integer :tag "when modifying times")))
3131 ;; Normalize old customizations of this variable.
3132 (when (integerp org-time-stamp-rounding-minutes)
3133 (setq org-time-stamp-rounding-minutes
3134 (list org-time-stamp-rounding-minutes
3135 org-time-stamp-rounding-minutes)))
3137 (defcustom org-display-custom-times nil
3138 "Non-nil means overlay custom formats over all time stamps.
3139 The formats are defined through the variable `org-time-stamp-custom-formats'.
3140 To turn this on on a per-file basis, insert anywhere in the file:
3141 #+STARTUP: customtime"
3142 :group 'org-time
3143 :set 'set-default
3144 :type 'sexp)
3145 (make-variable-buffer-local 'org-display-custom-times)
3147 (defcustom org-time-stamp-custom-formats
3148 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3149 "Custom formats for time stamps. See `format-time-string' for the syntax.
3150 These are overlaid over the default ISO format if the variable
3151 `org-display-custom-times' is set. Time like %H:%M should be at the
3152 end of the second format. The custom formats are also honored by export
3153 commands, if custom time display is turned on at the time of export."
3154 :group 'org-time
3155 :type 'sexp)
3157 (defun org-time-stamp-format (&optional long inactive)
3158 "Get the right format for a time string."
3159 (let ((f (if long (cdr org-time-stamp-formats)
3160 (car org-time-stamp-formats))))
3161 (if inactive
3162 (concat "[" (substring f 1 -1) "]")
3163 f)))
3165 (defcustom org-time-clocksum-format
3166 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3167 "The format string used when creating CLOCKSUM lines.
3168 This is also used when Org mode generates a time duration.
3170 The value can be a single format string containing two
3171 %-sequences, which will be filled with the number of hours and
3172 minutes in that order.
3174 Alternatively, the value can be a plist associating any of the
3175 keys :years, :months, :weeks, :days, :hours or :minutes with
3176 format strings. The time duration is formatted using only the
3177 time components that are needed and concatenating the results.
3178 If a time unit in absent, it falls back to the next smallest
3179 unit.
3181 The keys :require-years, :require-months, :require-days,
3182 :require-weeks, :require-hours, :require-minutes are also
3183 meaningful. A non-nil value for these keys indicates that the
3184 corresponding time component should always be included, even if
3185 its value is 0.
3188 For example,
3190 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3191 :require-minutes t)
3193 means durations longer than a day will be expressed in days,
3194 hours and minutes, and durations less than a day will always be
3195 expressed in hours and minutes (even for durations less than an
3196 hour).
3198 The value
3200 \(:days \"%dd\" :minutes \"%dm\")
3202 means durations longer than a day will be expressed in days and
3203 minutes, and durations less than a day will be expressed entirely
3204 in minutes (even for durations longer than an hour)."
3205 :group 'org-time
3206 :group 'org-clock
3207 :version "24.4"
3208 :package-version '(Org . "8.0")
3209 :type '(choice (string :tag "Format string")
3210 (set :tag "Plist"
3211 (group :inline t (const :tag "Years" :years)
3212 (string :tag "Format string"))
3213 (group :inline t
3214 (const :tag "Always show years" :require-years)
3215 (const t))
3216 (group :inline t (const :tag "Months" :months)
3217 (string :tag "Format string"))
3218 (group :inline t
3219 (const :tag "Always show months" :require-months)
3220 (const t))
3221 (group :inline t (const :tag "Weeks" :weeks)
3222 (string :tag "Format string"))
3223 (group :inline t
3224 (const :tag "Always show weeks" :require-weeks)
3225 (const t))
3226 (group :inline t (const :tag "Days" :days)
3227 (string :tag "Format string"))
3228 (group :inline t
3229 (const :tag "Always show days" :require-days)
3230 (const t))
3231 (group :inline t (const :tag "Hours" :hours)
3232 (string :tag "Format string"))
3233 (group :inline t
3234 (const :tag "Always show hours" :require-hours)
3235 (const t))
3236 (group :inline t (const :tag "Minutes" :minutes)
3237 (string :tag "Format string"))
3238 (group :inline t
3239 (const :tag "Always show minutes" :require-minutes)
3240 (const t)))))
3242 (defcustom org-time-clocksum-use-fractional nil
3243 "When non-nil, \\[org-clock-display] uses fractional times.
3244 See `org-time-clocksum-format' for more on time clock formats."
3245 :group 'org-time
3246 :group 'org-clock
3247 :version "24.3"
3248 :type 'boolean)
3250 (defcustom org-time-clocksum-use-effort-durations nil
3251 "When non-nil, \\[org-clock-display] uses effort durations.
3252 E.g. by default, one day is considered to be a 8 hours effort,
3253 so a task that has been clocked for 16 hours will be displayed
3254 as during 2 days in the clock display or in the clocktable.
3256 See `org-effort-durations' on how to set effort durations
3257 and `org-time-clocksum-format' for more on time clock formats."
3258 :group 'org-time
3259 :group 'org-clock
3260 :version "24.4"
3261 :package-version '(Org . "8.0")
3262 :type 'boolean)
3264 (defcustom org-time-clocksum-fractional-format "%.2f"
3265 "The format string used when creating CLOCKSUM lines,
3266 or when Org mode generates a time duration, if
3267 `org-time-clocksum-use-fractional' is enabled.
3269 The value can be a single format string containing one
3270 %-sequence, which will be filled with the number of hours as
3271 a float.
3273 Alternatively, the value can be a plist associating any of the
3274 keys :years, :months, :weeks, :days, :hours or :minutes with
3275 a format string. The time duration is formatted using the
3276 largest time unit which gives a non-zero integer part. If all
3277 specified formats have zero integer part, the smallest time unit
3278 is used."
3279 :group 'org-time
3280 :type '(choice (string :tag "Format string")
3281 (set (group :inline t (const :tag "Years" :years)
3282 (string :tag "Format string"))
3283 (group :inline t (const :tag "Months" :months)
3284 (string :tag "Format string"))
3285 (group :inline t (const :tag "Weeks" :weeks)
3286 (string :tag "Format string"))
3287 (group :inline t (const :tag "Days" :days)
3288 (string :tag "Format string"))
3289 (group :inline t (const :tag "Hours" :hours)
3290 (string :tag "Format string"))
3291 (group :inline t (const :tag "Minutes" :minutes)
3292 (string :tag "Format string")))))
3294 (defcustom org-deadline-warning-days 14
3295 "Number of days before expiration during which a deadline becomes active.
3296 This variable governs the display in sparse trees and in the agenda.
3297 When 0 or negative, it means use this number (the absolute value of it)
3298 even if a deadline has a different individual lead time specified.
3300 Custom commands can set this variable in the options section."
3301 :group 'org-time
3302 :group 'org-agenda-daily/weekly
3303 :type 'integer)
3305 (defcustom org-scheduled-delay-days 0
3306 "Number of days before a scheduled item becomes active.
3307 This variable governs the display in sparse trees and in the agenda.
3308 The default value (i.e. 0) means: don't delay scheduled item.
3309 When negative, it means use this number (the absolute value of it)
3310 even if a scheduled item has a different individual delay time
3311 specified.
3313 Custom commands can set this variable in the options section."
3314 :group 'org-time
3315 :group 'org-agenda-daily/weekly
3316 :version "24.4"
3317 :package-version '(Org . "8.0")
3318 :type 'integer)
3320 (defcustom org-read-date-prefer-future t
3321 "Non-nil means assume future for incomplete date input from user.
3322 This affects the following situations:
3323 1. The user gives a month but not a year.
3324 For example, if it is April and you enter \"feb 2\", this will be read
3325 as Feb 2, *next* year. \"May 5\", however, will be this year.
3326 2. The user gives a day, but no month.
3327 For example, if today is the 15th, and you enter \"3\", Org-mode will
3328 read this as the third of *next* month. However, if you enter \"17\",
3329 it will be considered as *this* month.
3331 If you set this variable to the symbol `time', then also the following
3332 will work:
3334 3. If the user gives a time.
3335 If the time is before now, it will be interpreted as tomorrow.
3337 Currently none of this works for ISO week specifications.
3339 When this option is nil, the current day, month and year will always be
3340 used as defaults.
3342 See also `org-agenda-jump-prefer-future'."
3343 :group 'org-time
3344 :type '(choice
3345 (const :tag "Never" nil)
3346 (const :tag "Check month and day" t)
3347 (const :tag "Check month, day, and time" time)))
3349 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3350 "Should the agenda jump command prefer the future for incomplete dates?
3351 The default is to do the same as configured in `org-read-date-prefer-future'.
3352 But you can also set a deviating value here.
3353 This may t or nil, or the symbol `org-read-date-prefer-future'."
3354 :group 'org-agenda
3355 :group 'org-time
3356 :version "24.1"
3357 :type '(choice
3358 (const :tag "Use org-read-date-prefer-future"
3359 org-read-date-prefer-future)
3360 (const :tag "Never" nil)
3361 (const :tag "Always" t)))
3363 (defcustom org-read-date-force-compatible-dates t
3364 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3366 Depending on the system Emacs is running on, certain dates cannot
3367 be represented with the type used internally to represent time.
3368 Dates between 1970-1-1 and 2038-1-1 can always be represented
3369 correctly. Some systems allow for earlier dates, some for later,
3370 some for both. One way to find out it to insert any date into an
3371 Org buffer, putting the cursor on the year and hitting S-up and
3372 S-down to test the range.
3374 When this variable is set to t, the date/time prompt will not let
3375 you specify dates outside the 1970-2037 range, so it is certain that
3376 these dates will work in whatever version of Emacs you are
3377 running, and also that you can move a file from one Emacs implementation
3378 to another. WHenever Org is forcing the year for you, it will display
3379 a message and beep.
3381 When this variable is nil, Org will check if the date is
3382 representable in the specific Emacs implementation you are using.
3383 If not, it will force a year, usually the current year, and beep
3384 to remind you. Currently this setting is not recommended because
3385 the likelihood that you will open your Org files in an Emacs that
3386 has limited date range is not negligible.
3388 A workaround for this problem is to use diary sexp dates for time
3389 stamps outside of this range."
3390 :group 'org-time
3391 :version "24.1"
3392 :type 'boolean)
3394 (defcustom org-read-date-display-live t
3395 "Non-nil means display current interpretation of date prompt live.
3396 This display will be in an overlay, in the minibuffer."
3397 :group 'org-time
3398 :type 'boolean)
3400 (defcustom org-read-date-popup-calendar t
3401 "Non-nil means pop up a calendar when prompting for a date.
3402 In the calendar, the date can be selected with mouse-1. However, the
3403 minibuffer will also be active, and you can simply enter the date as well.
3404 When nil, only the minibuffer will be available."
3405 :group 'org-time
3406 :type 'boolean)
3407 (org-defvaralias 'org-popup-calendar-for-date-prompt
3408 'org-read-date-popup-calendar)
3410 (make-obsolete-variable
3411 'org-read-date-minibuffer-setup-hook
3412 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3413 (defcustom org-read-date-minibuffer-setup-hook nil
3414 "Hook to be used to set up keys for the date/time interface.
3415 Add key definitions to `minibuffer-local-map', which will be a
3416 temporary copy.
3418 WARNING: This option is obsolete, you should use
3419 `org-read-date-minibuffer-local-map' to set up keys."
3420 :group 'org-time
3421 :type 'hook)
3423 (defcustom org-extend-today-until 0
3424 "The hour when your day really ends. Must be an integer.
3425 This has influence for the following applications:
3426 - When switching the agenda to \"today\". It it is still earlier than
3427 the time given here, the day recognized as TODAY is actually yesterday.
3428 - When a date is read from the user and it is still before the time given
3429 here, the current date and time will be assumed to be yesterday, 23:59.
3430 Also, timestamps inserted in capture templates follow this rule.
3432 IMPORTANT: This is a feature whose implementation is and likely will
3433 remain incomplete. Really, it is only here because past midnight seems to
3434 be the favorite working time of John Wiegley :-)"
3435 :group 'org-time
3436 :type 'integer)
3438 (defcustom org-use-effective-time nil
3439 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3440 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3441 \"effective time\" of any timestamps between midnight and 8am will be
3442 23:59 of the previous day."
3443 :group 'org-time
3444 :version "24.1"
3445 :type 'boolean)
3447 (defcustom org-use-last-clock-out-time-as-effective-time nil
3448 "When non-nil, use the last clock out time for `org-todo'.
3449 Note that this option has precedence over the combined use of
3450 `org-use-effective-time' and `org-extend-today-until'."
3451 :group 'org-time
3452 :version "24.4"
3453 :package-version '(Org . "8.0")
3454 :type 'boolean)
3456 (defcustom org-edit-timestamp-down-means-later nil
3457 "Non-nil means S-down will increase the time in a time stamp.
3458 When nil, S-up will increase."
3459 :group 'org-time
3460 :type 'boolean)
3462 (defcustom org-calendar-follow-timestamp-change t
3463 "Non-nil means make the calendar window follow timestamp changes.
3464 When a timestamp is modified and the calendar window is visible, it will be
3465 moved to the new date."
3466 :group 'org-time
3467 :type 'boolean)
3469 (defgroup org-tags nil
3470 "Options concerning tags in Org-mode."
3471 :tag "Org Tags"
3472 :group 'org)
3474 (defcustom org-tag-alist nil
3475 "List of tags allowed in Org-mode files.
3476 When this list is nil, Org-mode will base TAG input on what is already in the
3477 buffer.
3478 The value of this variable is an alist, the car of each entry must be a
3479 keyword as a string, the cdr may be a character that is used to select
3480 that tag through the fast-tag-selection interface.
3481 See the manual for details."
3482 :group 'org-tags
3483 :type '(repeat
3484 (choice
3485 (cons (string :tag "Tag name")
3486 (character :tag "Access char"))
3487 (list :tag "Start radio group"
3488 (const :startgroup)
3489 (option (string :tag "Group description")))
3490 (list :tag "Group tags delimiter"
3491 (const :grouptags))
3492 (list :tag "End radio group"
3493 (const :endgroup)
3494 (option (string :tag "Group description")))
3495 (const :tag "New line" (:newline)))))
3497 (defcustom org-tag-persistent-alist nil
3498 "List of tags that will always appear in all Org-mode files.
3499 This is in addition to any in buffer settings or customizations
3500 of `org-tag-alist'.
3501 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3502 The value of this variable is an alist, the car of each entry must be a
3503 keyword as a string, the cdr may be a character that is used to select
3504 that tag through the fast-tag-selection interface.
3505 See the manual for details.
3506 To disable these tags on a per-file basis, insert anywhere in the file:
3507 #+STARTUP: noptag"
3508 :group 'org-tags
3509 :type '(repeat
3510 (choice
3511 (cons (string :tag "Tag name")
3512 (character :tag "Access char"))
3513 (const :tag "Start radio group" (:startgroup))
3514 (const :tag "Group tags delimiter" (:grouptags))
3515 (const :tag "End radio group" (:endgroup))
3516 (const :tag "New line" (:newline)))))
3518 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3519 "If non-nil, always offer completion for all tags of all agenda files.
3520 Instead of customizing this variable directly, you might want to
3521 set it locally for capture buffers, because there no list of
3522 tags in that file can be created dynamically (there are none).
3524 (add-hook 'org-capture-mode-hook
3525 (lambda ()
3526 (set (make-local-variable
3527 'org-complete-tags-always-offer-all-agenda-tags)
3528 t)))"
3529 :group 'org-tags
3530 :version "24.1"
3531 :type 'boolean)
3533 (defvar org-file-tags nil
3534 "List of tags that can be inherited by all entries in the file.
3535 The tags will be inherited if the variable `org-use-tag-inheritance'
3536 says they should be.
3537 This variable is populated from #+FILETAGS lines.")
3539 (defcustom org-use-fast-tag-selection 'auto
3540 "Non-nil means use fast tag selection scheme.
3541 This is a special interface to select and deselect tags with single keys.
3542 When nil, fast selection is never used.
3543 When the symbol `auto', fast selection is used if and only if selection
3544 characters for tags have been configured, either through the variable
3545 `org-tag-alist' or through a #+TAGS line in the buffer.
3546 When t, fast selection is always used and selection keys are assigned
3547 automatically if necessary."
3548 :group 'org-tags
3549 :type '(choice
3550 (const :tag "Always" t)
3551 (const :tag "Never" nil)
3552 (const :tag "When selection characters are configured" auto)))
3554 (defcustom org-fast-tag-selection-single-key nil
3555 "Non-nil means fast tag selection exits after first change.
3556 When nil, you have to press RET to exit it.
3557 During fast tag selection, you can toggle this flag with `C-c'.
3558 This variable can also have the value `expert'. In this case, the window
3559 displaying the tags menu is not even shown, until you press C-c again."
3560 :group 'org-tags
3561 :type '(choice
3562 (const :tag "No" nil)
3563 (const :tag "Yes" t)
3564 (const :tag "Expert" expert)))
3566 (defvar org-fast-tag-selection-include-todo nil
3567 "Non-nil means fast tags selection interface will also offer TODO states.
3568 This is an undocumented feature, you should not rely on it.")
3570 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3571 "The column to which tags should be indented in a headline.
3572 If this number is positive, it specifies the column. If it is negative,
3573 it means that the tags should be flushright to that column. For example,
3574 -80 works well for a normal 80 character screen.
3575 When 0, place tags directly after headline text, with only one space in
3576 between."
3577 :group 'org-tags
3578 :type 'integer)
3580 (defcustom org-auto-align-tags t
3581 "Non-nil keeps tags aligned when modifying headlines.
3582 Some operations (i.e. demoting) change the length of a headline and
3583 therefore shift the tags around. With this option turned on, after
3584 each such operation the tags are again aligned to `org-tags-column'."
3585 :group 'org-tags
3586 :type 'boolean)
3588 (defcustom org-use-tag-inheritance t
3589 "Non-nil means tags in levels apply also for sublevels.
3590 When nil, only the tags directly given in a specific line apply there.
3591 This may also be a list of tags that should be inherited, or a regexp that
3592 matches tags that should be inherited. Additional control is possible
3593 with the variable `org-tags-exclude-from-inheritance' which gives an
3594 explicit list of tags to be excluded from inheritance, even if the value of
3595 `org-use-tag-inheritance' would select it for inheritance.
3597 If this option is t, a match early-on in a tree can lead to a large
3598 number of matches in the subtree when constructing the agenda or creating
3599 a sparse tree. If you only want to see the first match in a tree during
3600 a search, check out the variable `org-tags-match-list-sublevels'."
3601 :group 'org-tags
3602 :type '(choice
3603 (const :tag "Not" nil)
3604 (const :tag "Always" t)
3605 (repeat :tag "Specific tags" (string :tag "Tag"))
3606 (regexp :tag "Tags matched by regexp")))
3608 (defcustom org-tags-exclude-from-inheritance nil
3609 "List of tags that should never be inherited.
3610 This is a way to exclude a few tags from inheritance. For way to do
3611 the opposite, to actively allow inheritance for selected tags,
3612 see the variable `org-use-tag-inheritance'."
3613 :group 'org-tags
3614 :type '(repeat (string :tag "Tag")))
3616 (defun org-tag-inherit-p (tag)
3617 "Check if TAG is one that should be inherited."
3618 (cond
3619 ((member tag org-tags-exclude-from-inheritance) nil)
3620 ((eq org-use-tag-inheritance t) t)
3621 ((not org-use-tag-inheritance) nil)
3622 ((stringp org-use-tag-inheritance)
3623 (string-match org-use-tag-inheritance tag))
3624 ((listp org-use-tag-inheritance)
3625 (member tag org-use-tag-inheritance))
3626 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3628 (defcustom org-tags-match-list-sublevels t
3629 "Non-nil means list also sublevels of headlines matching a search.
3630 This variable applies to tags/property searches, and also to stuck
3631 projects because this search is based on a tags match as well.
3633 When set to the symbol `indented', sublevels are indented with
3634 leading dots.
3636 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3637 the sublevels of a headline matching a tag search often also match
3638 the same search. Listing all of them can create very long lists.
3639 Setting this variable to nil causes subtrees of a match to be skipped.
3641 This variable is semi-obsolete and probably should always be true. It
3642 is better to limit inheritance to certain tags using the variables
3643 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3644 :group 'org-tags
3645 :type '(choice
3646 (const :tag "No, don't list them" nil)
3647 (const :tag "Yes, do list them" t)
3648 (const :tag "List them, indented with leading dots" indented)))
3650 (defcustom org-tags-sort-function nil
3651 "When set, tags are sorted using this function as a comparator."
3652 :group 'org-tags
3653 :type '(choice
3654 (const :tag "No sorting" nil)
3655 (const :tag "Alphabetical" string<)
3656 (const :tag "Reverse alphabetical" string>)
3657 (function :tag "Custom function" nil)))
3659 (defvar org-tags-history nil
3660 "History of minibuffer reads for tags.")
3661 (defvar org-last-tags-completion-table nil
3662 "The last used completion table for tags.")
3663 (defvar org-after-tags-change-hook nil
3664 "Hook that is run after the tags in a line have changed.")
3666 (defgroup org-properties nil
3667 "Options concerning properties in Org-mode."
3668 :tag "Org Properties"
3669 :group 'org)
3671 (defcustom org-property-format "%-10s %s"
3672 "How property key/value pairs should be formatted by `indent-line'.
3673 When `indent-line' hits a property definition, it will format the line
3674 according to this format, mainly to make sure that the values are
3675 lined-up with respect to each other."
3676 :group 'org-properties
3677 :type 'string)
3679 (defcustom org-properties-postprocess-alist nil
3680 "Alist of properties and functions to adjust inserted values.
3681 Elements of this alist must be of the form
3683 ([string] [function])
3685 where [string] must be a property name and [function] must be a
3686 lambda expression: this lambda expression must take one argument,
3687 the value to adjust, and return the new value as a string.
3689 For example, this element will allow the property \"Remaining\"
3690 to be updated wrt the relation between the \"Effort\" property
3691 and the clock summary:
3693 ((\"Remaining\" (lambda(value)
3694 (let ((clocksum (org-clock-sum-current-item))
3695 (effort (org-duration-string-to-minutes
3696 (org-entry-get (point) \"Effort\"))))
3697 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3698 :group 'org-properties
3699 :version "24.1"
3700 :type '(alist :key-type (string :tag "Property")
3701 :value-type (function :tag "Function")))
3703 (defcustom org-use-property-inheritance nil
3704 "Non-nil means properties apply also for sublevels.
3706 This setting is chiefly used during property searches. Turning it on can
3707 cause significant overhead when doing a search, which is why it is not
3708 on by default.
3710 When nil, only the properties directly given in the current entry count.
3711 When t, every property is inherited. The value may also be a list of
3712 properties that should have inheritance, or a regular expression matching
3713 properties that should be inherited.
3715 However, note that some special properties use inheritance under special
3716 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3717 and the properties ending in \"_ALL\" when they are used as descriptor
3718 for valid values of a property.
3720 Note for programmers:
3721 When querying an entry with `org-entry-get', you can control if inheritance
3722 should be used. By default, `org-entry-get' looks only at the local
3723 properties. You can request inheritance by setting the inherit argument
3724 to t (to force inheritance) or to `selective' (to respect the setting
3725 in this variable)."
3726 :group 'org-properties
3727 :type '(choice
3728 (const :tag "Not" nil)
3729 (const :tag "Always" t)
3730 (repeat :tag "Specific properties" (string :tag "Property"))
3731 (regexp :tag "Properties matched by regexp")))
3733 (defun org-property-inherit-p (property)
3734 "Check if PROPERTY is one that should be inherited."
3735 (cond
3736 ((eq org-use-property-inheritance t) t)
3737 ((not org-use-property-inheritance) nil)
3738 ((stringp org-use-property-inheritance)
3739 (string-match org-use-property-inheritance property))
3740 ((listp org-use-property-inheritance)
3741 (member property org-use-property-inheritance))
3742 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3744 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3745 "The default column format, if no other format has been defined.
3746 This variable can be set on the per-file basis by inserting a line
3748 #+COLUMNS: %25ITEM ....."
3749 :group 'org-properties
3750 :type 'string)
3752 (defcustom org-columns-ellipses ".."
3753 "The ellipses to be used when a field in column view is truncated.
3754 When this is the empty string, as many characters as possible are shown,
3755 but then there will be no visual indication that the field has been truncated.
3756 When this is a string of length N, the last N characters of a truncated
3757 field are replaced by this string. If the column is narrower than the
3758 ellipses string, only part of the ellipses string will be shown."
3759 :group 'org-properties
3760 :type 'string)
3762 (defcustom org-columns-modify-value-for-display-function nil
3763 "Function that modifies values for display in column view.
3764 For example, it can be used to cut out a certain part from a time stamp.
3765 The function must take 2 arguments:
3767 column-title The title of the column (*not* the property name)
3768 value The value that should be modified.
3770 The function should return the value that should be displayed,
3771 or nil if the normal value should be used."
3772 :group 'org-properties
3773 :type '(choice (const nil) (function)))
3775 (defconst org-global-properties-fixed
3776 '(("VISIBILITY_ALL" . "folded children content all")
3777 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3778 "List of property/value pairs that can be inherited by any entry.
3780 These are fixed values, for the preset properties. The user variable
3781 that can be used to add to this list is `org-global-properties'.
3783 The entries in this list are cons cells where the car is a property
3784 name and cdr is a string with the value. If the value represents
3785 multiple items like an \"_ALL\" property, separate the items by
3786 spaces.")
3788 (defcustom org-global-properties nil
3789 "List of property/value pairs that can be inherited by any entry.
3791 This list will be combined with the constant `org-global-properties-fixed'.
3793 The entries in this list are cons cells where the car is a property
3794 name and cdr is a string with the value.
3796 You can set buffer-local values for the same purpose in the variable
3797 `org-file-properties' this by adding lines like
3799 #+PROPERTY: NAME VALUE"
3800 :group 'org-properties
3801 :type '(repeat
3802 (cons (string :tag "Property")
3803 (string :tag "Value"))))
3805 (defvar org-file-properties nil
3806 "List of property/value pairs that can be inherited by any entry.
3807 Valid for the current buffer.
3808 This variable is populated from #+PROPERTY lines.")
3809 (make-variable-buffer-local 'org-file-properties)
3811 (defgroup org-agenda nil
3812 "Options concerning agenda views in Org-mode."
3813 :tag "Org Agenda"
3814 :group 'org)
3816 (defvar org-category nil
3817 "Variable used by org files to set a category for agenda display.
3818 Such files should use a file variable to set it, for example
3820 # -*- mode: org; org-category: \"ELisp\"
3822 or contain a special line
3824 #+CATEGORY: ELisp
3826 If the file does not specify a category, then file's base name
3827 is used instead.")
3828 (make-variable-buffer-local 'org-category)
3829 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3831 (defcustom org-agenda-files nil
3832 "The files to be used for agenda display.
3833 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3834 \\[org-remove-file]. You can also use customize to edit the list.
3836 If an entry is a directory, all files in that directory that are matched by
3837 `org-agenda-file-regexp' will be part of the file list.
3839 If the value of the variable is not a list but a single file name, then
3840 the list of agenda files is actually stored and maintained in that file, one
3841 agenda file per line. In this file paths can be given relative to
3842 `org-directory'. Tilde expansion and environment variable substitution
3843 are also made."
3844 :group 'org-agenda
3845 :type '(choice
3846 (repeat :tag "List of files and directories" file)
3847 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3849 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3850 "Regular expression to match files for `org-agenda-files'.
3851 If any element in the list in that variable contains a directory instead
3852 of a normal file, all files in that directory that are matched by this
3853 regular expression will be included."
3854 :group 'org-agenda
3855 :type 'regexp)
3857 (defcustom org-agenda-text-search-extra-files nil
3858 "List of extra files to be searched by text search commands.
3859 These files will be searched in addition to the agenda files by the
3860 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3861 Note that these files will only be searched for text search commands,
3862 not for the other agenda views like todo lists, tag searches or the weekly
3863 agenda. This variable is intended to list notes and possibly archive files
3864 that should also be searched by these two commands.
3865 In fact, if the first element in the list is the symbol `agenda-archives',
3866 then all archive files of all agenda files will be added to the search
3867 scope."
3868 :group 'org-agenda
3869 :type '(set :greedy t
3870 (const :tag "Agenda Archives" agenda-archives)
3871 (repeat :inline t (file))))
3873 (org-defvaralias 'org-agenda-multi-occur-extra-files
3874 'org-agenda-text-search-extra-files)
3876 (defcustom org-agenda-skip-unavailable-files nil
3877 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3878 A nil value means to remove them, after a query, from the list."
3879 :group 'org-agenda
3880 :type 'boolean)
3882 (defcustom org-calendar-to-agenda-key [?c]
3883 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3884 The command `org-calendar-goto-agenda' will be bound to this key. The
3885 default is the character `c' because then `c' can be used to switch back and
3886 forth between agenda and calendar."
3887 :group 'org-agenda
3888 :type 'sexp)
3890 (defcustom org-calendar-insert-diary-entry-key [?i]
3891 "The key to be installed in `calendar-mode-map' for adding diary entries.
3892 This option is irrelevant until `org-agenda-diary-file' has been configured
3893 to point to an Org-mode file. When that is the case, the command
3894 `org-agenda-diary-entry' will be bound to the key given here, by default
3895 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3896 if you want to continue doing this, you need to change this to a different
3897 key."
3898 :group 'org-agenda
3899 :type 'sexp)
3901 (defcustom org-agenda-diary-file 'diary-file
3902 "File to which to add new entries with the `i' key in agenda and calendar.
3903 When this is the symbol `diary-file', the functionality in the Emacs
3904 calendar will be used to add entries to the `diary-file'. But when this
3905 points to a file, `org-agenda-diary-entry' will be used instead."
3906 :group 'org-agenda
3907 :type '(choice
3908 (const :tag "The standard Emacs diary file" diary-file)
3909 (file :tag "Special Org file diary entries")))
3911 (eval-after-load "calendar"
3912 '(progn
3913 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3914 'org-calendar-goto-agenda)
3915 (add-hook 'calendar-mode-hook
3916 (lambda ()
3917 (unless (eq org-agenda-diary-file 'diary-file)
3918 (define-key calendar-mode-map
3919 org-calendar-insert-diary-entry-key
3920 'org-agenda-diary-entry))))))
3922 (defgroup org-latex nil
3923 "Options for embedding LaTeX code into Org-mode."
3924 :tag "Org LaTeX"
3925 :group 'org)
3927 (defcustom org-format-latex-options
3928 '(:foreground default :background default :scale 1.0
3929 :html-foreground "Black" :html-background "Transparent"
3930 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3931 "Options for creating images from LaTeX fragments.
3932 This is a property list with the following properties:
3933 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3934 `default' means use the foreground of the default face.
3935 `auto' means use the foreground from the text face.
3936 :background the background color, or \"Transparent\".
3937 `default' means use the background of the default face.
3938 `auto' means use the background from the text face.
3939 :scale a scaling factor for the size of the images, to get more pixels
3940 :html-foreground, :html-background, :html-scale
3941 the same numbers for HTML export.
3942 :matchers a list indicating which matchers should be used to
3943 find LaTeX fragments. Valid members of this list are:
3944 \"begin\" find environments
3945 \"$1\" find single characters surrounded by $.$
3946 \"$\" find math expressions surrounded by $...$
3947 \"$$\" find math expressions surrounded by $$....$$
3948 \"\\(\" find math expressions surrounded by \\(...\\)
3949 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3950 :group 'org-latex
3951 :type 'plist)
3953 (defcustom org-format-latex-signal-error t
3954 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3955 When nil, just push out a message."
3956 :group 'org-latex
3957 :version "24.1"
3958 :type 'boolean)
3960 (defcustom org-latex-to-mathml-jar-file nil
3961 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3962 Use this to specify additional executable file say a jar file.
3964 When using MathToWeb as the converter, specify the full-path to
3965 your mathtoweb.jar file."
3966 :group 'org-latex
3967 :version "24.1"
3968 :type '(choice
3969 (const :tag "None" nil)
3970 (file :tag "JAR file" :must-match t)))
3972 (defcustom org-latex-to-mathml-convert-command nil
3973 "Command to convert LaTeX fragments to MathML.
3974 Replace format-specifiers in the command as noted below and use
3975 `shell-command' to convert LaTeX to MathML.
3976 %j: Executable file in fully expanded form as specified by
3977 `org-latex-to-mathml-jar-file'.
3978 %I: Input LaTeX file in fully expanded form
3979 %o: Output MathML file
3980 This command is used by `org-create-math-formula'.
3982 When using MathToWeb as the converter, set this to
3983 \"java -jar %j -unicode -force -df %o %I\"."
3984 :group 'org-latex
3985 :version "24.1"
3986 :type '(choice
3987 (const :tag "None" nil)
3988 (string :tag "\nShell command")))
3990 (defcustom org-latex-create-formula-image-program 'dvipng
3991 "Program to convert LaTeX fragments with.
3993 dvipng Process the LaTeX fragments to dvi file, then convert
3994 dvi files to png files using dvipng.
3995 This will also include processing of non-math environments.
3996 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3997 to convert pdf files to png files"
3998 :group 'org-latex
3999 :version "24.1"
4000 :type '(choice
4001 (const :tag "dvipng" dvipng)
4002 (const :tag "imagemagick" imagemagick)))
4004 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
4005 "Path to store latex preview images.
4006 A relative path here creates many directories relative to the
4007 processed org files paths. An absolute path puts all preview
4008 images at the same place."
4009 :group 'org-latex
4010 :version "24.3"
4011 :type 'string)
4013 (defun org-format-latex-mathml-available-p ()
4014 "Return t if `org-latex-to-mathml-convert-command' is usable."
4015 (save-match-data
4016 (when (and (boundp 'org-latex-to-mathml-convert-command)
4017 org-latex-to-mathml-convert-command)
4018 (let ((executable (car (split-string
4019 org-latex-to-mathml-convert-command))))
4020 (when (executable-find executable)
4021 (if (string-match
4022 "%j" org-latex-to-mathml-convert-command)
4023 (file-readable-p org-latex-to-mathml-jar-file)
4024 t))))))
4026 (defcustom org-format-latex-header "\\documentclass{article}
4027 \\usepackage[usenames]{color}
4028 \[PACKAGES]
4029 \[DEFAULT-PACKAGES]
4030 \\pagestyle{empty} % do not remove
4031 % The settings below are copied from fullpage.sty
4032 \\setlength{\\textwidth}{\\paperwidth}
4033 \\addtolength{\\textwidth}{-3cm}
4034 \\setlength{\\oddsidemargin}{1.5cm}
4035 \\addtolength{\\oddsidemargin}{-2.54cm}
4036 \\setlength{\\evensidemargin}{\\oddsidemargin}
4037 \\setlength{\\textheight}{\\paperheight}
4038 \\addtolength{\\textheight}{-\\headheight}
4039 \\addtolength{\\textheight}{-\\headsep}
4040 \\addtolength{\\textheight}{-\\footskip}
4041 \\addtolength{\\textheight}{-3cm}
4042 \\setlength{\\topmargin}{1.5cm}
4043 \\addtolength{\\topmargin}{-2.54cm}"
4044 "The document header used for processing LaTeX fragments.
4045 It is imperative that this header make sure that no page number
4046 appears on the page. The package defined in the variables
4047 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4048 will either replace the placeholder \"[PACKAGES]\" in this
4049 header, or they will be appended."
4050 :group 'org-latex
4051 :type 'string)
4053 (defun org-set-packages-alist (var val)
4054 "Set the packages alist and make sure it has 3 elements per entry."
4055 (set var (mapcar (lambda (x)
4056 (if (and (consp x) (= (length x) 2))
4057 (list (car x) (nth 1 x) t)
4059 val)))
4061 (defun org-get-packages-alist (var)
4062 "Get the packages alist and make sure it has 3 elements per entry."
4063 (mapcar (lambda (x)
4064 (if (and (consp x) (= (length x) 2))
4065 (list (car x) (nth 1 x) t)
4067 (default-value var)))
4069 (defcustom org-latex-default-packages-alist
4070 '(("AUTO" "inputenc" t)
4071 ("T1" "fontenc" t)
4072 ("" "fixltx2e" nil)
4073 ("" "graphicx" t)
4074 ("" "longtable" nil)
4075 ("" "float" nil)
4076 ("" "wrapfig" nil)
4077 ("" "rotating" nil)
4078 ("normalem" "ulem" t)
4079 ("" "amsmath" t)
4080 ("" "textcomp" t)
4081 ("" "marvosym" t)
4082 ("" "wasysym" t)
4083 ("" "amssymb" t)
4084 ("" "capt-of" nil)
4085 ("" "hyperref" nil)
4086 "\\tolerance=1000")
4087 "Alist of default packages to be inserted in the header.
4089 Change this only if one of the packages here causes an
4090 incompatibility with another package you are using.
4092 The packages in this list are needed by one part or another of
4093 Org mode to function properly:
4095 - inputenc, fontenc: for basic font and character selection
4096 - fixltx2e: Important patches of LaTeX itself
4097 - graphicx: for including images
4098 - longtable: For multipage tables
4099 - float, wrapfig: for figure placement
4100 - rotating: for sideways figures and tables
4101 - ulem: for underline and strike-through
4102 - amsmath: for subscript and superscript and math environments
4103 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4104 for interpreting the entities in `org-entities'. You can skip
4105 some of these packages if you don't use any of their symbols.
4106 - capt-of: for captions outside of floats
4107 - hyperref: for cross references
4109 Therefore you should not modify this variable unless you know
4110 what you are doing. The one reason to change it anyway is that
4111 you might be loading some other package that conflicts with one
4112 of the default packages. Each element is either a cell or
4113 a string.
4115 A cell is of the format:
4117 \( \"options\" \"package\" SNIPPET-FLAG).
4119 If SNIPPET-FLAG is non-nil, the package also needs to be included
4120 when compiling LaTeX snippets into images for inclusion into
4121 non-LaTeX output.
4123 A string will be inserted as-is in the header of the document."
4124 :group 'org-latex
4125 :group 'org-export-latex
4126 :set 'org-set-packages-alist
4127 :get 'org-get-packages-alist
4128 :version "24.1"
4129 :type '(repeat
4130 (choice
4131 (list :tag "options/package pair"
4132 (string :tag "options")
4133 (string :tag "package")
4134 (boolean :tag "Snippet"))
4135 (string :tag "A line of LaTeX"))))
4137 (defcustom org-latex-packages-alist nil
4138 "Alist of packages to be inserted in every LaTeX header.
4140 These will be inserted after `org-latex-default-packages-alist'.
4141 Each element is either a cell or a string.
4143 A cell is of the format:
4145 \(\"options\" \"package\" SNIPPET-FLAG)
4147 SNIPPET-FLAG, when non-nil, indicates that this package is also
4148 needed when turning LaTeX snippets into images for inclusion into
4149 non-LaTeX output.
4151 A string will be inserted as-is in the header of the document.
4153 Make sure that you only list packages here which:
4155 - you want in every file;
4156 - do not conflict with the setup in `org-format-latex-header';
4157 - do not conflict with the default packages in
4158 `org-latex-default-packages-alist'."
4159 :group 'org-latex
4160 :group 'org-export-latex
4161 :set 'org-set-packages-alist
4162 :get 'org-get-packages-alist
4163 :type '(repeat
4164 (choice
4165 (list :tag "options/package pair"
4166 (string :tag "options")
4167 (string :tag "package")
4168 (boolean :tag "Snippet"))
4169 (string :tag "A line of LaTeX"))))
4171 (defgroup org-appearance nil
4172 "Settings for Org-mode appearance."
4173 :tag "Org Appearance"
4174 :group 'org)
4176 (defcustom org-level-color-stars-only nil
4177 "Non-nil means fontify only the stars in each headline.
4178 When nil, the entire headline is fontified.
4179 Changing it requires restart of `font-lock-mode' to become effective
4180 also in regions already fontified."
4181 :group 'org-appearance
4182 :type 'boolean)
4184 (defcustom org-hide-leading-stars nil
4185 "Non-nil means hide the first N-1 stars in a headline.
4186 This works by using the face `org-hide' for these stars. This
4187 face is white for a light background, and black for a dark
4188 background. You may have to customize the face `org-hide' to
4189 make this work.
4190 Changing it requires restart of `font-lock-mode' to become effective
4191 also in regions already fontified.
4192 You may also set this on a per-file basis by adding one of the following
4193 lines to the buffer:
4195 #+STARTUP: hidestars
4196 #+STARTUP: showstars"
4197 :group 'org-appearance
4198 :type 'boolean)
4200 (defcustom org-hidden-keywords nil
4201 "List of symbols corresponding to keywords to be hidden the org buffer.
4202 For example, a value '(title) for this list will make the document's title
4203 appear in the buffer without the initial #+TITLE: keyword."
4204 :group 'org-appearance
4205 :version "24.1"
4206 :type '(set (const :tag "#+AUTHOR" author)
4207 (const :tag "#+DATE" date)
4208 (const :tag "#+EMAIL" email)
4209 (const :tag "#+TITLE" title)))
4211 (defcustom org-custom-properties nil
4212 "List of properties (as strings) with a special meaning.
4213 The default use of these custom properties is to let the user
4214 hide them with `org-toggle-custom-properties-visibility'."
4215 :group 'org-properties
4216 :group 'org-appearance
4217 :version "24.3"
4218 :type '(repeat (string :tag "Property Name")))
4220 (defcustom org-fontify-done-headline nil
4221 "Non-nil means change the face of a headline if it is marked DONE.
4222 Normally, only the TODO/DONE keyword indicates the state of a headline.
4223 When this is non-nil, the headline after the keyword is set to the
4224 `org-headline-done' as an additional indication."
4225 :group 'org-appearance
4226 :type 'boolean)
4228 (defcustom org-fontify-emphasized-text t
4229 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4230 Changing this variable requires a restart of Emacs to take effect."
4231 :group 'org-appearance
4232 :type 'boolean)
4234 (defcustom org-fontify-whole-heading-line nil
4235 "Non-nil means fontify the whole line for headings.
4236 This is useful when setting a background color for the
4237 org-level-* faces."
4238 :group 'org-appearance
4239 :type 'boolean)
4241 (defcustom org-highlight-latex-and-related nil
4242 "Non-nil means highlight LaTeX related syntax in the buffer.
4243 When non nil, the value should be a list containing any of the
4244 following symbols:
4245 `latex' Highlight LaTeX snippets and environments.
4246 `script' Highlight subscript and superscript.
4247 `entities' Highlight entities."
4248 :group 'org-appearance
4249 :version "24.4"
4250 :package-version '(Org . "8.0")
4251 :type '(choice
4252 (const :tag "No highlighting" nil)
4253 (set :greedy t :tag "Highlight"
4254 (const :tag "LaTeX snippets and environments" latex)
4255 (const :tag "Subscript and superscript" script)
4256 (const :tag "Entities" entities))))
4258 (defcustom org-hide-emphasis-markers nil
4259 "Non-nil mean font-lock should hide the emphasis marker characters."
4260 :group 'org-appearance
4261 :type 'boolean)
4263 (defcustom org-hide-macro-markers nil
4264 "Non-nil mean font-lock should hide the brackets marking macro calls."
4265 :group 'org-appearance
4266 :type 'boolean)
4268 (defcustom org-pretty-entities nil
4269 "Non-nil means show entities as UTF8 characters.
4270 When nil, the \\name form remains in the buffer."
4271 :group 'org-appearance
4272 :version "24.1"
4273 :type 'boolean)
4275 (defcustom org-pretty-entities-include-sub-superscripts t
4276 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4277 :group 'org-appearance
4278 :version "24.1"
4279 :type 'boolean)
4281 (defvar org-emph-re nil
4282 "Regular expression for matching emphasis.
4283 After a match, the match groups contain these elements:
4284 0 The match of the full regular expression, including the characters
4285 before and after the proper match
4286 1 The character before the proper match, or empty at beginning of line
4287 2 The proper match, including the leading and trailing markers
4288 3 The leading marker like * or /, indicating the type of highlighting
4289 4 The text between the emphasis markers, not including the markers
4290 5 The character after the match, empty at the end of a line")
4291 (defvar org-verbatim-re nil
4292 "Regular expression for matching verbatim text.")
4293 (defvar org-emphasis-regexp-components) ; defined just below
4294 (defvar org-emphasis-alist) ; defined just below
4295 (defun org-set-emph-re (var val)
4296 "Set variable and compute the emphasis regular expression."
4297 (set var val)
4298 (when (and (boundp 'org-emphasis-alist)
4299 (boundp 'org-emphasis-regexp-components)
4300 org-emphasis-alist org-emphasis-regexp-components)
4301 (let* ((e org-emphasis-regexp-components)
4302 (pre (car e))
4303 (post (nth 1 e))
4304 (border (nth 2 e))
4305 (body (nth 3 e))
4306 (nl (nth 4 e))
4307 (body1 (concat body "*?"))
4308 (markers (mapconcat 'car org-emphasis-alist ""))
4309 (vmarkers (mapconcat
4310 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4311 org-emphasis-alist "")))
4312 ;; make sure special characters appear at the right position in the class
4313 (if (string-match "\\^" markers)
4314 (setq markers (concat (replace-match "" t t markers) "^")))
4315 (if (string-match "-" markers)
4316 (setq markers (concat (replace-match "" t t markers) "-")))
4317 (if (string-match "\\^" vmarkers)
4318 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4319 (if (string-match "-" vmarkers)
4320 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4321 (if (> nl 0)
4322 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4323 (int-to-string nl) "\\}")))
4324 ;; Make the regexp
4325 (setq org-emph-re
4326 (concat "\\([" pre "]\\|^\\)"
4327 "\\("
4328 "\\([" markers "]\\)"
4329 "\\("
4330 "[^" border "]\\|"
4331 "[^" border "]"
4332 body1
4333 "[^" border "]"
4334 "\\)"
4335 "\\3\\)"
4336 "\\([" post "]\\|$\\)"))
4337 (setq org-verbatim-re
4338 (concat "\\([" pre "]\\|^\\)"
4339 "\\("
4340 "\\([" vmarkers "]\\)"
4341 "\\("
4342 "[^" border "]\\|"
4343 "[^" border "]"
4344 body1
4345 "[^" border "]"
4346 "\\)"
4347 "\\3\\)"
4348 "\\([" post "]\\|$\\)")))))
4350 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4351 ;; set this option proved cumbersome. See this message/thread:
4352 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4353 (defvar org-emphasis-regexp-components
4354 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n,\"'" "." 1)
4355 "Components used to build the regular expression for emphasis.
4356 This is a list with five entries. Terminology: In an emphasis string
4357 like \" *strong word* \", we call the initial space PREMATCH, the final
4358 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4359 and \"trong wor\" is the body. The different components in this variable
4360 specify what is allowed/forbidden in each part:
4362 pre Chars allowed as prematch. Beginning of line will be allowed too.
4363 post Chars allowed as postmatch. End of line will be allowed too.
4364 border The chars *forbidden* as border characters.
4365 body-regexp A regexp like \".\" to match a body character. Don't use
4366 non-shy groups here, and don't allow newline here.
4367 newline The maximum number of newlines allowed in an emphasis exp.
4369 You need to reload Org or to restart Emacs after customizing this.")
4371 (defcustom org-emphasis-alist
4372 `(("*" bold)
4373 ("/" italic)
4374 ("_" underline)
4375 ("=" org-verbatim verbatim)
4376 ("~" org-code verbatim)
4377 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4378 "Alist of characters and faces to emphasize text.
4379 Text starting and ending with a special character will be emphasized,
4380 for example *bold*, _underlined_ and /italic/. This variable sets the
4381 marker characters and the face to be used by font-lock for highlighting
4382 in Org-mode Emacs buffers.
4384 You need to reload Org or to restart Emacs after customizing this."
4385 :group 'org-appearance
4386 :set 'org-set-emph-re
4387 :version "24.4"
4388 :package-version '(Org . "8.0")
4389 :type '(repeat
4390 (list
4391 (string :tag "Marker character")
4392 (choice
4393 (face :tag "Font-lock-face")
4394 (plist :tag "Face property list"))
4395 (option (const verbatim)))))
4397 (defvar org-protecting-blocks
4398 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4399 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4400 This is needed for font-lock setup.")
4402 ;;; Miscellaneous options
4404 (defgroup org-completion nil
4405 "Completion in Org-mode."
4406 :tag "Org Completion"
4407 :group 'org)
4409 (defcustom org-completion-use-ido nil
4410 "Non-nil means use ido completion wherever possible.
4411 Note that `ido-mode' must be active for this variable to be relevant.
4412 If you decide to turn this variable on, you might well want to turn off
4413 `org-outline-path-complete-in-steps'.
4414 See also `org-completion-use-iswitchb'."
4415 :group 'org-completion
4416 :type 'boolean)
4418 (defcustom org-completion-use-iswitchb nil
4419 "Non-nil means use iswitchb completion wherever possible.
4420 Note that `iswitchb-mode' must be active for this variable to be relevant.
4421 If you decide to turn this variable on, you might well want to turn off
4422 `org-outline-path-complete-in-steps'.
4423 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4424 :group 'org-completion
4425 :type 'boolean)
4427 (defcustom org-completion-fallback-command 'hippie-expand
4428 "The expansion command called by \\[pcomplete] in normal context.
4429 Normal means, no org-mode-specific context."
4430 :group 'org-completion
4431 :type 'function)
4433 ;;; Functions and variables from their packages
4434 ;; Declared here to avoid compiler warnings
4436 ;; XEmacs only
4437 (defvar outline-mode-menu-heading)
4438 (defvar outline-mode-menu-show)
4439 (defvar outline-mode-menu-hide)
4440 (defvar zmacs-regions) ; XEmacs regions
4442 ;; Emacs only
4443 (defvar mark-active)
4445 ;; Various packages
4446 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4447 (declare-function calendar-forward-day "cal-move" (arg))
4448 (declare-function calendar-goto-date "cal-move" (date))
4449 (declare-function calendar-goto-today "cal-move" ())
4450 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4451 (defvar calc-embedded-close-formula)
4452 (defvar calc-embedded-open-formula)
4453 (declare-function cdlatex-tab "ext:cdlatex" ())
4454 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4455 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4456 (defvar font-lock-unfontify-region-function)
4457 (declare-function iswitchb-read-buffer "iswitchb"
4458 (prompt &optional default require-match start matches-set))
4459 (defvar iswitchb-temp-buflist)
4460 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4461 (defvar org-agenda-tags-todo-honor-ignore-options)
4462 (declare-function org-agenda-skip "org-agenda" ())
4463 (declare-function
4464 org-agenda-format-item "org-agenda"
4465 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4466 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4467 (declare-function org-agenda-change-all-lines "org-agenda"
4468 (newhead hdmarker &optional fixface just-this))
4469 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4470 (declare-function org-agenda-maybe-redo "org-agenda" ())
4471 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4472 (beg end))
4473 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4474 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4475 "org-agenda" (&optional end))
4476 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4477 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4478 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4479 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4480 (declare-function org-indent-mode "org-indent" (&optional arg))
4481 (declare-function parse-time-string "parse-time" (string))
4482 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4483 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4484 (defvar remember-data-file)
4485 (defvar texmathp-why)
4486 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4487 (declare-function table--at-cell-p "table" (position &optional object at-column))
4488 (declare-function calc-eval "calc" (str &optional separator &rest args))
4490 ;;;###autoload
4491 (defun turn-on-orgtbl ()
4492 "Unconditionally turn on `orgtbl-mode'."
4493 (require 'org-table)
4494 (orgtbl-mode 1))
4496 (defun org-at-table-p (&optional table-type)
4497 "Return t if the cursor is inside an org-type table.
4498 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4499 (if org-enable-table-editor
4500 (save-excursion
4501 (beginning-of-line 1)
4502 (looking-at (if table-type org-table-any-line-regexp
4503 org-table-line-regexp)))
4504 nil))
4505 (defsubst org-table-p () (org-at-table-p))
4507 (defun org-at-table.el-p ()
4508 "Return t if and only if we are at a table.el table."
4509 (and (org-at-table-p 'any)
4510 (save-excursion
4511 (goto-char (org-table-begin 'any))
4512 (looking-at org-table1-hline-regexp))))
4514 (defun org-table-recognize-table.el ()
4515 "If there is a table.el table nearby, recognize it and move into it."
4516 (if org-table-tab-recognizes-table.el
4517 (if (org-at-table.el-p)
4518 (progn
4519 (beginning-of-line 1)
4520 (if (looking-at org-table-dataline-regexp)
4522 (if (looking-at org-table1-hline-regexp)
4523 (progn
4524 (beginning-of-line 2)
4525 (if (looking-at org-table-any-border-regexp)
4526 (beginning-of-line -1)))))
4527 (if (re-search-forward "|" (org-table-end t) t)
4528 (progn
4529 (require 'table)
4530 (if (table--at-cell-p (point))
4532 (message "recognizing table.el table...")
4533 (table-recognize-table)
4534 (message "recognizing table.el table...done")))
4535 (error "This should not happen"))
4537 nil)
4538 nil))
4540 (defun org-at-table-hline-p ()
4541 "Return t if the cursor is inside a hline in a table."
4542 (if org-enable-table-editor
4543 (save-excursion
4544 (beginning-of-line 1)
4545 (looking-at org-table-hline-regexp))
4546 nil))
4548 (defun org-table-map-tables (function &optional quietly)
4549 "Apply FUNCTION to the start of all tables in the buffer."
4550 (save-excursion
4551 (save-restriction
4552 (widen)
4553 (goto-char (point-min))
4554 (while (re-search-forward org-table-any-line-regexp nil t)
4555 (unless quietly
4556 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4557 (beginning-of-line 1)
4558 (when (and (looking-at org-table-line-regexp)
4559 ;; Exclude tables in src/example/verbatim/clocktable blocks
4560 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4561 (save-excursion (funcall function))
4562 (or (looking-at org-table-line-regexp)
4563 (forward-char 1)))
4564 (re-search-forward org-table-any-border-regexp nil 1))))
4565 (unless quietly (message "Mapping tables: done")))
4567 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4568 (declare-function org-clock-update-mode-line "org-clock" ())
4569 (declare-function org-resolve-clocks "org-clock"
4570 (&optional also-non-dangling-p prompt last-valid))
4572 (defun org-at-TBLFM-p (&optional pos)
4573 "Return t when point (or POS) is in #+TBLFM line."
4574 (save-excursion
4575 (let ((pos pos)))
4576 (goto-char (or pos (point)))
4577 (beginning-of-line 1)
4578 (looking-at org-TBLFM-regexp)))
4580 (defvar org-clock-start-time)
4581 (defvar org-clock-marker (make-marker)
4582 "Marker recording the last clock-in.")
4583 (defvar org-clock-hd-marker (make-marker)
4584 "Marker recording the last clock-in, but the headline position.")
4585 (defvar org-clock-heading ""
4586 "The heading of the current clock entry.")
4587 (defun org-clock-is-active ()
4588 "Return the buffer where the clock is currently running.
4589 Return nil if no clock is running."
4590 (marker-buffer org-clock-marker))
4592 (defun org-check-running-clock ()
4593 "Check if the current buffer contains the running clock.
4594 If yes, offer to stop it and to save the buffer with the changes."
4595 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4596 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4597 (buffer-name))))
4598 (org-clock-out)
4599 (when (y-or-n-p "Save changed buffer?")
4600 (save-buffer))))
4602 (defun org-clocktable-try-shift (dir n)
4603 "Check if this line starts a clock table, if yes, shift the time block."
4604 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4605 (org-clocktable-shift dir n)))
4607 ;;;###autoload
4608 (defun org-clock-persistence-insinuate ()
4609 "Set up hooks for clock persistence."
4610 (require 'org-clock)
4611 (add-hook 'org-mode-hook 'org-clock-load)
4612 (add-hook 'kill-emacs-hook 'org-clock-save))
4614 (defgroup org-archive nil
4615 "Options concerning archiving in Org-mode."
4616 :tag "Org Archive"
4617 :group 'org-structure)
4619 (defcustom org-archive-location "%s_archive::"
4620 "The location where subtrees should be archived.
4622 The value of this variable is a string, consisting of two parts,
4623 separated by a double-colon. The first part is a filename and
4624 the second part is a headline.
4626 When the filename is omitted, archiving happens in the same file.
4627 %s in the filename will be replaced by the current file
4628 name (without the directory part). Archiving to a different file
4629 is useful to keep archived entries from contributing to the
4630 Org-mode Agenda.
4632 The archived entries will be filed as subtrees of the specified
4633 headline. When the headline is omitted, the subtrees are simply
4634 filed away at the end of the file, as top-level entries. Also in
4635 the heading you can use %s to represent the file name, this can be
4636 useful when using the same archive for a number of different files.
4638 Here are a few examples:
4639 \"%s_archive::\"
4640 If the current file is Projects.org, archive in file
4641 Projects.org_archive, as top-level trees. This is the default.
4643 \"::* Archived Tasks\"
4644 Archive in the current file, under the top-level headline
4645 \"* Archived Tasks\".
4647 \"~/org/archive.org::\"
4648 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4650 \"~/org/archive.org::* From %s\"
4651 Archive in file ~/org/archive.org (absolute path), under headlines
4652 \"From FILENAME\" where file name is the current file name.
4654 \"~/org/datetree.org::datetree/* Finished Tasks\"
4655 The \"datetree/\" string is special, signifying to archive
4656 items to the datetree. Items are placed in either the CLOSED
4657 date of the item, or the current date if there is no CLOSED date.
4658 The heading will be a subentry to the current date. There doesn't
4659 need to be a heading, but there always needs to be a slash after
4660 datetree. For example, to store archived items directly in the
4661 datetree, use \"~/org/datetree.org::datetree/\".
4663 \"basement::** Finished Tasks\"
4664 Archive in file ./basement (relative path), as level 3 trees
4665 below the level 2 heading \"** Finished Tasks\".
4667 You may set this option on a per-file basis by adding to the buffer a
4668 line like
4670 #+ARCHIVE: basement::** Finished Tasks
4672 You may also define it locally for a subtree by setting an ARCHIVE property
4673 in the entry. If such a property is found in an entry, or anywhere up
4674 the hierarchy, it will be used."
4675 :group 'org-archive
4676 :type 'string)
4678 (defcustom org-agenda-skip-archived-trees t
4679 "Non-nil means the agenda will skip any items located in archived trees.
4680 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4681 variable is no longer recommended, you should leave it at the value t.
4682 Instead, use the key `v' to cycle the archives-mode in the agenda."
4683 :group 'org-archive
4684 :group 'org-agenda-skip
4685 :type 'boolean)
4687 (defcustom org-columns-skip-archived-trees t
4688 "Non-nil means ignore archived trees when creating column view."
4689 :group 'org-archive
4690 :group 'org-properties
4691 :type 'boolean)
4693 (defcustom org-cycle-open-archived-trees nil
4694 "Non-nil means `org-cycle' will open archived trees.
4695 An archived tree is a tree marked with the tag ARCHIVE.
4696 When nil, archived trees will stay folded. You can still open them with
4697 normal outline commands like `show-all', but not with the cycling commands."
4698 :group 'org-archive
4699 :group 'org-cycle
4700 :type 'boolean)
4702 (defcustom org-sparse-tree-open-archived-trees nil
4703 "Non-nil means sparse tree construction shows matches in archived trees.
4704 When nil, matches in these trees are highlighted, but the trees are kept in
4705 collapsed state."
4706 :group 'org-archive
4707 :group 'org-sparse-trees
4708 :type 'boolean)
4710 (defcustom org-sparse-tree-default-date-type nil
4711 "The default date type when building a sparse tree.
4712 When this is nil, a date is a scheduled or a deadline timestamp.
4713 Otherwise, these types are allowed:
4715 all: all timestamps
4716 active: only active timestamps (<...>)
4717 inactive: only inactive timestamps ([...])
4718 scheduled: only scheduled timestamps
4719 deadline: only deadline timestamps"
4720 :type '(choice (const :tag "Scheduled or deadline" nil)
4721 (const :tag "All timestamps" all)
4722 (const :tag "Only active timestamps" active)
4723 (const :tag "Only inactive timestamps" inactive)
4724 (const :tag "Only scheduled timestamps" scheduled)
4725 (const :tag "Only deadline timestamps" deadline)
4726 (const :tag "Only closed timestamps" closed))
4727 :version "25.1"
4728 :package-version '(Org . "8.3")
4729 :group 'org-sparse-trees)
4731 (defun org-cycle-hide-archived-subtrees (state)
4732 "Re-hide all archived subtrees after a visibility state change."
4733 (when (and (not org-cycle-open-archived-trees)
4734 (not (memq state '(overview folded))))
4735 (save-excursion
4736 (let* ((globalp (memq state '(contents all)))
4737 (beg (if globalp (point-min) (point)))
4738 (end (if globalp (point-max) (org-end-of-subtree t))))
4739 (org-hide-archived-subtrees beg end)
4740 (goto-char beg)
4741 (if (looking-at (concat ".*:" org-archive-tag ":"))
4742 (message "%s" (substitute-command-keys
4743 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4745 (defun org-force-cycle-archived ()
4746 "Cycle subtree even if it is archived."
4747 (interactive)
4748 (setq this-command 'org-cycle)
4749 (let ((org-cycle-open-archived-trees t))
4750 (call-interactively 'org-cycle)))
4752 (defun org-hide-archived-subtrees (beg end)
4753 "Re-hide all archived subtrees after a visibility state change."
4754 (org-with-wide-buffer
4755 (let ((case-fold-search nil)
4756 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4757 (goto-char beg)
4758 (while (and (< (point) end) (re-search-forward re end t))
4759 (when (member org-archive-tag (org-get-tags))
4760 (org-flag-subtree t)
4761 (org-end-of-subtree t))))))
4763 (declare-function outline-end-of-heading "outline" ())
4764 (declare-function outline-flag-region "outline" (from to flag))
4765 (defun org-flag-subtree (flag)
4766 (save-excursion
4767 (org-back-to-heading t)
4768 (outline-end-of-heading)
4769 (outline-flag-region (point)
4770 (progn (org-end-of-subtree t) (point))
4771 flag)))
4773 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4775 ;; Declare Column View Code
4777 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4778 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4779 (declare-function org-columns-compute "org-colview" (property))
4781 ;; Declare ID code
4783 (declare-function org-id-store-link "org-id")
4784 (declare-function org-id-locations-load "org-id")
4785 (declare-function org-id-locations-save "org-id")
4786 (defvar org-id-track-globally)
4788 ;;; Variables for pre-computed regular expressions, all buffer local
4790 (defvar org-todo-regexp nil
4791 "Matches any of the TODO state keywords.")
4792 (make-variable-buffer-local 'org-todo-regexp)
4793 (defvar org-not-done-regexp nil
4794 "Matches any of the TODO state keywords except the last one.")
4795 (make-variable-buffer-local 'org-not-done-regexp)
4796 (defvar org-not-done-heading-regexp nil
4797 "Matches a TODO headline that is not done.")
4798 (make-variable-buffer-local 'org-not-done-regexp)
4799 (defvar org-todo-line-regexp nil
4800 "Matches a headline and puts TODO state into group 2 if present.")
4801 (make-variable-buffer-local 'org-todo-line-regexp)
4802 (defvar org-complex-heading-regexp nil
4803 "Matches a headline and puts everything into groups:
4804 group 1: the stars
4805 group 2: The todo keyword, maybe
4806 group 3: Priority cookie
4807 group 4: True headline
4808 group 5: Tags")
4809 (make-variable-buffer-local 'org-complex-heading-regexp)
4810 (defvar org-complex-heading-regexp-format nil
4811 "Printf format to make regexp to match an exact headline.
4812 This regexp will match the headline of any node which has the
4813 exact headline text that is put into the format, but may have any
4814 TODO state, priority and tags.")
4815 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4816 (defvar org-todo-line-tags-regexp nil
4817 "Matches a headline and puts TODO state into group 2 if present.
4818 Also put tags into group 4 if tags are present.")
4819 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4821 (defconst org-plain-time-of-day-regexp
4822 (concat
4823 "\\(\\<[012]?[0-9]"
4824 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4825 "\\(--?"
4826 "\\(\\<[012]?[0-9]"
4827 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4828 "\\)?")
4829 "Regular expression to match a plain time or time range.
4830 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4831 groups carry important information:
4832 0 the full match
4833 1 the first time, range or not
4834 8 the second time, if it is a range.")
4836 (defconst org-plain-time-extension-regexp
4837 (concat
4838 "\\(\\<[012]?[0-9]"
4839 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4840 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4841 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
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 7 hours of duration
4846 9 minutes of duration")
4848 (defconst org-stamp-time-of-day-regexp
4849 (concat
4850 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4851 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4852 "\\(--?"
4853 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4854 "Regular expression to match a timestamp time or time range.
4855 After a match, the following groups carry important information:
4856 0 the full match
4857 1 date plus weekday, for back referencing to make sure both times are on the same day
4858 2 the first time, range or not
4859 4 the second time, if it is a range.")
4861 (defconst org-startup-options
4862 '(("fold" org-startup-folded t)
4863 ("overview" org-startup-folded t)
4864 ("nofold" org-startup-folded nil)
4865 ("showall" org-startup-folded nil)
4866 ("showeverything" org-startup-folded showeverything)
4867 ("content" org-startup-folded content)
4868 ("indent" org-startup-indented t)
4869 ("noindent" org-startup-indented nil)
4870 ("hidestars" org-hide-leading-stars t)
4871 ("showstars" org-hide-leading-stars nil)
4872 ("odd" org-odd-levels-only t)
4873 ("oddeven" org-odd-levels-only nil)
4874 ("align" org-startup-align-all-tables t)
4875 ("noalign" org-startup-align-all-tables nil)
4876 ("inlineimages" org-startup-with-inline-images t)
4877 ("noinlineimages" org-startup-with-inline-images nil)
4878 ("latexpreview" org-startup-with-latex-preview t)
4879 ("nolatexpreview" org-startup-with-latex-preview nil)
4880 ("customtime" org-display-custom-times t)
4881 ("logdone" org-log-done time)
4882 ("lognotedone" org-log-done note)
4883 ("nologdone" org-log-done nil)
4884 ("lognoteclock-out" org-log-note-clock-out t)
4885 ("nolognoteclock-out" org-log-note-clock-out nil)
4886 ("logrepeat" org-log-repeat state)
4887 ("lognoterepeat" org-log-repeat note)
4888 ("logdrawer" org-log-into-drawer t)
4889 ("nologdrawer" org-log-into-drawer nil)
4890 ("logstatesreversed" org-log-states-order-reversed t)
4891 ("nologstatesreversed" org-log-states-order-reversed nil)
4892 ("nologrepeat" org-log-repeat nil)
4893 ("logreschedule" org-log-reschedule time)
4894 ("lognotereschedule" org-log-reschedule note)
4895 ("nologreschedule" org-log-reschedule nil)
4896 ("logredeadline" org-log-redeadline time)
4897 ("lognoteredeadline" org-log-redeadline note)
4898 ("nologredeadline" org-log-redeadline nil)
4899 ("logrefile" org-log-refile time)
4900 ("lognoterefile" org-log-refile note)
4901 ("nologrefile" org-log-refile nil)
4902 ("fninline" org-footnote-define-inline t)
4903 ("nofninline" org-footnote-define-inline nil)
4904 ("fnlocal" org-footnote-section nil)
4905 ("fnauto" org-footnote-auto-label t)
4906 ("fnprompt" org-footnote-auto-label nil)
4907 ("fnconfirm" org-footnote-auto-label confirm)
4908 ("fnplain" org-footnote-auto-label plain)
4909 ("fnadjust" org-footnote-auto-adjust t)
4910 ("nofnadjust" org-footnote-auto-adjust nil)
4911 ("constcgs" constants-unit-system cgs)
4912 ("constSI" constants-unit-system SI)
4913 ("noptag" org-tag-persistent-alist nil)
4914 ("hideblocks" org-hide-block-startup t)
4915 ("nohideblocks" org-hide-block-startup nil)
4916 ("beamer" org-startup-with-beamer-mode t)
4917 ("entitiespretty" org-pretty-entities t)
4918 ("entitiesplain" org-pretty-entities nil))
4919 "Variable associated with STARTUP options for org-mode.
4920 Each element is a list of three items: the startup options (as written
4921 in the #+STARTUP line), the corresponding variable, and the value to set
4922 this variable to if the option is found. An optional forth element PUSH
4923 means to push this value onto the list in the variable.")
4925 (defcustom org-group-tags t
4926 "When non-nil (the default), use group tags.
4927 This can be turned on/off through `org-toggle-tags-groups'."
4928 :group 'org-tags
4929 :group 'org-startup
4930 :type 'boolean)
4932 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4934 (defun org-toggle-tags-groups ()
4935 "Toggle support for group tags.
4936 Support for group tags is controlled by the option
4937 `org-group-tags', which is non-nil by default."
4938 (interactive)
4939 (setq org-group-tags (not org-group-tags))
4940 (cond ((and (derived-mode-p 'org-agenda-mode)
4941 org-group-tags)
4942 (org-agenda-redo))
4943 ((derived-mode-p 'org-mode)
4944 (let ((org-inhibit-startup t)) (org-mode))))
4945 (message "Groups tags support has been turned %s"
4946 (if org-group-tags "on" "off")))
4948 (defun org-set-regexps-and-options (&optional tags-only)
4949 "Precompute regular expressions used in the current buffer.
4950 When optional argument TAGS-ONLY is non-nil, only compute tags
4951 related expressions."
4952 (when (derived-mode-p 'org-mode)
4953 (let ((alist (org--setup-collect-keywords
4954 (org-make-options-regexp
4955 (append '("FILETAGS" "TAGS" "SETUPFILE")
4956 (and (not tags-only)
4957 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4958 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4959 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4960 (org--setup-process-tags
4961 (cdr (assq 'tags alist)) (cdr (assq 'filetags alist)))
4962 (unless tags-only
4963 ;; File properties.
4964 (org-set-local 'org-file-properties (cdr (assq 'property alist)))
4965 ;; Archive location.
4966 (let ((archive (cdr (assq 'archive alist))))
4967 (when archive (org-set-local 'org-archive-location archive)))
4968 ;; Category.
4969 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4970 (when cat
4971 (org-set-local 'org-category (intern cat))
4972 (org-set-local 'org-file-properties
4973 (org--update-property-plist
4974 "CATEGORY" cat org-file-properties))))
4975 ;; Columns.
4976 (let ((column (cdr (assq 'columns alist))))
4977 (when column (org-set-local 'org-columns-default-format column)))
4978 ;; Constants.
4979 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4980 ;; Link abbreviations.
4981 (let ((links (cdr (assq 'link alist))))
4982 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4983 ;; Priorities.
4984 (let ((priorities (cdr (assq 'priorities alist))))
4985 (when priorities
4986 (org-set-local 'org-highest-priority (nth 0 priorities))
4987 (org-set-local 'org-lowest-priority (nth 1 priorities))
4988 (org-set-local 'org-default-priority (nth 2 priorities))))
4989 ;; Scripts.
4990 (let ((scripts (assq 'scripts alist)))
4991 (when scripts
4992 (org-set-local 'org-use-sub-superscripts (cdr scripts))))
4993 ;; Startup options.
4994 (let ((startup (cdr (assq 'startup alist))))
4995 (dolist (option startup)
4996 (let ((entry (assoc-string option org-startup-options t)))
4997 (when entry
4998 (let ((var (nth 1 entry))
4999 (val (nth 2 entry)))
5000 (if (not (nth 3 entry)) (org-set-local var val)
5001 (unless (listp (symbol-value var))
5002 (org-set-local var nil))
5003 (add-to-list var val)))))))
5004 ;; TODO keywords.
5005 (org-set-local 'org-todo-kwd-alist nil)
5006 (org-set-local 'org-todo-key-alist nil)
5007 (org-set-local 'org-todo-key-trigger nil)
5008 (org-set-local 'org-todo-keywords-1 nil)
5009 (org-set-local 'org-done-keywords nil)
5010 (org-set-local 'org-todo-heads nil)
5011 (org-set-local 'org-todo-sets nil)
5012 (org-set-local 'org-todo-log-states nil)
5013 (let ((todo-sequences
5014 (or (nreverse (cdr (assq 'todo alist)))
5015 (let ((d (default-value 'org-todo-keywords)))
5016 (if (not (stringp (car d))) d
5017 ;; XXX: Backward compatibility code.
5018 (list (cons org-todo-interpretation d)))))))
5019 (dolist (sequence todo-sequences)
5020 (let* ((sequence (or (run-hook-with-args-until-success
5021 'org-todo-setup-filter-hook sequence)
5022 sequence))
5023 (sequence-type (car sequence))
5024 (keywords (cdr sequence))
5025 (sep (member "|" keywords))
5026 names alist)
5027 (dolist (k (remove "|" keywords))
5028 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5030 (error "Invalid TODO keyword %s" k))
5031 (let ((name (match-string 1 k))
5032 (key (match-string 2 k))
5033 (log (org-extract-log-state-settings k)))
5034 (push name names)
5035 (push (cons name (and key (string-to-char key))) alist)
5036 (when log (push log org-todo-log-states))))
5037 (let* ((names (nreverse names))
5038 (done (if sep (org-remove-keyword-keys (cdr sep))
5039 (last names)))
5040 (head (car names))
5041 (tail (list sequence-type head (car done) (org-last done))))
5042 (add-to-list 'org-todo-heads head 'append)
5043 (push names org-todo-sets)
5044 (setq org-done-keywords (append org-done-keywords done nil))
5045 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5046 (setq org-todo-key-alist
5047 (append org-todo-key-alist
5048 (and alist
5049 (append '((:startgroup))
5050 (nreverse alist)
5051 '((:endgroup))))))
5052 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5053 (setq org-todo-sets (nreverse org-todo-sets)
5054 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5055 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5056 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5057 ;; Compute the regular expressions and other local variables.
5058 ;; Using `org-outline-regexp-bol' would complicate them much,
5059 ;; because of the fixed white space at the end of that string.
5060 (if (not org-done-keywords)
5061 (setq org-done-keywords
5062 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5063 (setq org-not-done-keywords
5064 (org-delete-all org-done-keywords
5065 (copy-sequence org-todo-keywords-1))
5066 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5067 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5068 org-not-done-heading-regexp
5069 (format org-heading-keyword-regexp-format org-not-done-regexp)
5070 org-todo-line-regexp
5071 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5072 org-complex-heading-regexp
5073 (concat "^\\(\\*+\\)"
5074 "\\(?: +" org-todo-regexp "\\)?"
5075 "\\(?: +\\(\\[#.\\]\\)\\)?"
5076 "\\(?: +\\(.*?\\)\\)??"
5077 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5078 "[ \t]*$")
5079 org-complex-heading-regexp-format
5080 (concat "^\\(\\*+\\)"
5081 "\\(?: +" org-todo-regexp "\\)?"
5082 "\\(?: +\\(\\[#.\\]\\)\\)?"
5083 "\\(?: +"
5084 ;; Stats cookies can be stuck to body.
5085 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5086 "\\(%s\\)"
5087 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5088 "\\)"
5089 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5090 "[ \t]*$")
5091 org-todo-line-tags-regexp
5092 (concat "^\\(\\*+\\)"
5093 "\\(?: +" org-todo-regexp "\\)?"
5094 "\\(?: +\\(.*?\\)\\)??"
5095 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5096 "[ \t]*$"))
5097 (org-compute-latex-and-related-regexp)))))
5099 (defun org--setup-collect-keywords (regexp &optional files alist)
5100 "Return setup keywords values as an alist.
5102 REGEXP matches a subset of setup keywords. FILES is a list of
5103 file names already visited. It is used to avoid circular setup
5104 files. ALIST, when non-nil, is the alist computed so far.
5106 Return value contains the following keys: `archive', `category',
5107 `columns', `constants', `filetags', `link', `priorities',
5108 `property', `scripts', `startup', `tags' and `todo'."
5109 (org-with-wide-buffer
5110 (goto-char (point-min))
5111 (let ((case-fold-search t))
5112 (while (re-search-forward regexp nil t)
5113 (let ((element (org-element-at-point)))
5114 (when (eq (org-element-type element) 'keyword)
5115 (let ((key (org-element-property :key element))
5116 (value (org-element-property :value element)))
5117 (cond
5118 ((equal key "ARCHIVE")
5119 (when (org-string-nw-p value)
5120 (push (cons 'archive value) alist)))
5121 ((equal key "CATEGORY") (push (cons 'category value) alist))
5122 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5123 ((equal key "CONSTANTS")
5124 (let* ((constants (assq 'constants alist))
5125 (store (cdr constants)))
5126 (dolist (pair (org-split-string value))
5127 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5128 pair)
5129 (let* ((name (match-string 1 pair))
5130 (value (match-string 2 pair))
5131 (old (assoc name store)))
5132 (if old (setcdr old value)
5133 (push (cons name value) store)))))
5134 (if constants (setcdr constants store)
5135 (push (cons 'constants store) alist))))
5136 ((equal key "FILETAGS")
5137 (when (org-string-nw-p value)
5138 (let ((old (assq 'filetags alist))
5139 (new (apply #'nconc
5140 (mapcar (lambda (x) (org-split-string x ":"))
5141 (org-split-string value)))))
5142 (if old (setcdr old (append new (cdr old)))
5143 (push (cons 'filetags new) alist)))))
5144 ((equal key "LINK")
5145 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5146 (let ((links (assq 'link alist))
5147 (pair (cons (org-match-string-no-properties 1 value)
5148 (org-match-string-no-properties 2 value))))
5149 (if links (push pair (cdr links))
5150 (push (list 'link pair) alist)))))
5151 ((equal key "OPTIONS")
5152 (when (and (org-string-nw-p value)
5153 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5154 (push (cons 'scripts (read (match-string 1 value))) alist)))
5155 ((equal key "PRIORITIES")
5156 (push (cons 'priorities
5157 (let ((prio (org-split-string value)))
5158 (if (< (length prio) 3) '(?A ?C ?B)
5159 (mapcar #'string-to-char prio))))
5160 alist))
5161 ((equal key "PROPERTY")
5162 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5163 (let* ((property (assq 'property alist))
5164 (value (org--update-property-plist
5165 (org-match-string-no-properties 1 value)
5166 (org-match-string-no-properties 2 value)
5167 (cdr property))))
5168 (if property (setcdr property value)
5169 (push (cons 'property value) alist)))))
5170 ((equal key "STARTUP")
5171 (let ((startup (assq 'startup alist)))
5172 (if startup
5173 (setcdr startup
5174 (append (cdr startup) (org-split-string value)))
5175 (push (cons 'startup (org-split-string value)) alist))))
5176 ((equal key "TAGS")
5177 (let ((tag-cell (assq 'tags alist)))
5178 (if tag-cell
5179 (setcdr tag-cell
5180 (append (cdr tag-cell)
5181 '("\\n")
5182 (org-split-string value)))
5183 (push (cons 'tags (org-split-string value)) alist))))
5184 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5185 (let ((todo (assq 'todo alist))
5186 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5187 (org-split-string value))))
5188 (if todo (push value (cdr todo))
5189 (push (list 'todo value) alist))))
5190 ((equal key "SETUPFILE")
5191 (unless buffer-read-only ; Do not check in Gnus messages.
5192 (let ((f (and (org-string-nw-p value)
5193 (expand-file-name
5194 (org-remove-double-quotes value)))))
5195 (when (and f (file-readable-p f) (not (member f files)))
5196 (with-temp-buffer
5197 (insert-file-contents f)
5198 (setq alist
5199 ;; Fake Org mode to benefit from cache
5200 ;; without recurring needlessly.
5201 (let ((major-mode 'org-mode))
5202 (org--setup-collect-keywords
5203 regexp (cons f files) alist)))))))))))))))
5204 alist)
5206 (defun org--setup-process-tags (tags filetags)
5207 "Precompute variables used for tags.
5208 TAGS is a list of tags and tag group symbols, as strings.
5209 FILETAGS is a list of tags, as strings."
5210 ;; Process the file tags.
5211 (org-set-local 'org-file-tags
5212 (mapcar #'org-add-prop-inherited filetags))
5213 ;; Provide default tags if no local tags are found.
5214 (when (and (not tags) org-tag-alist)
5215 (setq tags
5216 (mapcar (lambda (tag)
5217 (case (car tag)
5218 (:startgroup "{")
5219 (:endgroup "}")
5220 (:grouptags ":")
5221 (:newline "\\n")
5222 (otherwise (concat (car tag)
5223 (and (characterp (cdr tag))
5224 (format "(%c)" (cdr tag)))))))
5225 org-tag-alist)))
5226 ;; Process the tags.
5227 (org-set-local 'org-tag-groups-alist nil)
5228 (org-set-local 'org-tag-alist nil)
5229 (let (group-flag)
5230 (while tags
5231 (let ((e (car tags)))
5232 (setq tags (cdr tags))
5233 (cond
5234 ((equal e "{")
5235 (push '(:startgroup) org-tag-alist)
5236 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5237 ((equal e "}")
5238 (push '(:endgroup) org-tag-alist)
5239 (setq group-flag nil))
5240 ((equal e ":")
5241 (push '(:grouptags) org-tag-alist)
5242 (setq group-flag 'append))
5243 ((equal e "\\n") (push '(:newline) org-tag-alist))
5244 ((string-match
5245 (org-re "\\`\\([[:alnum:]_@#%]+\\)\\(?:(\\(.\\))\\)?\\'") e)
5246 (let ((tag (match-string 1 e))
5247 (key (and (match-beginning 2)
5248 (string-to-char (match-string 2 e)))))
5249 (cond ((eq group-flag 'append)
5250 (setcar org-tag-groups-alist
5251 (append (car org-tag-groups-alist) (list tag))))
5252 (group-flag (push (list tag) org-tag-groups-alist)))
5253 (unless (assoc tag org-tag-alist)
5254 (push (cons tag key) org-tag-alist))))))))
5255 (setq org-tag-alist (nreverse org-tag-alist)))
5257 (defun org-file-contents (file &optional noerror)
5258 "Return the contents of FILE, as a string."
5259 (if (and file (file-readable-p file))
5260 (with-temp-buffer
5261 (insert-file-contents file)
5262 (buffer-string))
5263 (funcall (if noerror 'message 'error)
5264 "Cannot read file \"%s\"%s"
5265 file
5266 (let ((from (buffer-file-name (buffer-base-buffer))))
5267 (if from (concat " (referenced in file \"" from "\")") "")))))
5269 (defun org-extract-log-state-settings (x)
5270 "Extract the log state setting from a TODO keyword string.
5271 This will extract info from a string like \"WAIT(w@/!)\"."
5272 (let (kw key log1 log2)
5273 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5274 (setq kw (match-string 1 x)
5275 key (and (match-end 2) (match-string 2 x))
5276 log1 (and (match-end 3) (match-string 3 x))
5277 log2 (and (match-end 4) (match-string 4 x)))
5278 (and (or log1 log2)
5279 (list kw
5280 (and log1 (if (equal log1 "!") 'time 'note))
5281 (and log2 (if (equal log2 "!") 'time 'note)))))))
5283 (defun org-remove-keyword-keys (list)
5284 "Remove a pair of parenthesis at the end of each string in LIST."
5285 (mapcar (lambda (x)
5286 (if (string-match "(.*)$" x)
5287 (substring x 0 (match-beginning 0))
5289 list))
5291 (defun org-assign-fast-keys (alist)
5292 "Assign fast keys to a keyword-key alist.
5293 Respect keys that are already there."
5294 (let (new e (alt ?0))
5295 (while (setq e (pop alist))
5296 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5297 (cdr e)) ;; Key already assigned.
5298 (push e new)
5299 (let ((clist (string-to-list (downcase (car e))))
5300 (used (append new alist)))
5301 (when (= (car clist) ?@)
5302 (pop clist))
5303 (while (and clist (rassoc (car clist) used))
5304 (pop clist))
5305 (unless clist
5306 (while (rassoc alt used)
5307 (incf alt)))
5308 (push (cons (car e) (or (car clist) alt)) new))))
5309 (nreverse new)))
5311 ;;; Some variables used in various places
5313 (defvar org-window-configuration nil
5314 "Used in various places to store a window configuration.")
5315 (defvar org-selected-window nil
5316 "Used in various places to store a window configuration.")
5317 (defvar org-finish-function nil
5318 "Function to be called when `C-c C-c' is used.
5319 This is for getting out of special buffers like capture.")
5322 ;; FIXME: Occasionally check by commenting these, to make sure
5323 ;; no other functions uses these, forgetting to let-bind them.
5324 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5325 (defvar org-last-state)
5326 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5328 ;; Defined somewhere in this file, but used before definition.
5329 (defvar org-entities) ;; defined in org-entities.el
5330 (defvar org-struct-menu)
5331 (defvar org-org-menu)
5332 (defvar org-tbl-menu)
5334 ;;;; Define the Org-mode
5336 ;; We use a before-change function to check if a table might need
5337 ;; an update.
5338 (defvar org-table-may-need-update t
5339 "Indicates that a table might need an update.
5340 This variable is set by `org-before-change-function'.
5341 `org-table-align' sets it back to nil.")
5342 (defun org-before-change-function (beg end)
5343 "Every change indicates that a table might need an update."
5344 (setq org-table-may-need-update t))
5345 (defvar org-mode-map)
5346 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5347 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5348 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5349 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5350 (defvar org-table-buffer-is-an nil)
5352 (defvar bidi-paragraph-direction)
5353 (defvar buffer-face-mode-face)
5355 (require 'outline)
5356 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5357 (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"))
5358 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5360 ;; Other stuff we need.
5361 (require 'time-date)
5362 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5363 (require 'easymenu)
5364 (require 'overlay)
5366 ;; (require 'org-macs) moved higher up in the file before it is first used
5367 (require 'org-entities)
5368 ;; (require 'org-compat) moved higher up in the file before it is first used
5369 (require 'org-faces)
5370 (require 'org-list)
5371 (require 'org-pcomplete)
5372 (require 'org-src)
5373 (require 'org-footnote)
5374 (require 'org-macro)
5376 ;; babel
5377 (require 'ob)
5379 ;;;###autoload
5380 (define-derived-mode org-mode outline-mode "Org"
5381 "Outline-based notes management and organizer, alias
5382 \"Carsten's outline-mode for keeping track of everything.\"
5384 Org-mode develops organizational tasks around a NOTES file which
5385 contains information about projects as plain text. Org-mode is
5386 implemented on top of outline-mode, which is ideal to keep the content
5387 of large files well structured. It supports ToDo items, deadlines and
5388 time stamps, which magically appear in the diary listing of the Emacs
5389 calendar. Tables are easily created with a built-in table editor.
5390 Plain text URL-like links connect to websites, emails (VM), Usenet
5391 messages (Gnus), BBDB entries, and any files related to the project.
5392 For printing and sharing of notes, an Org-mode file (or a part of it)
5393 can be exported as a structured ASCII or HTML file.
5395 The following commands are available:
5397 \\{org-mode-map}"
5399 ;; Get rid of Outline menus, they are not needed
5400 ;; Need to do this here because define-derived-mode sets up
5401 ;; the keymap so late. Still, it is a waste to call this each time
5402 ;; we switch another buffer into org-mode.
5403 (if (featurep 'xemacs)
5404 (when (boundp 'outline-mode-menu-heading)
5405 ;; Assume this is Greg's port, it uses easymenu
5406 (easy-menu-remove outline-mode-menu-heading)
5407 (easy-menu-remove outline-mode-menu-show)
5408 (easy-menu-remove outline-mode-menu-hide))
5409 (define-key org-mode-map [menu-bar headings] 'undefined)
5410 (define-key org-mode-map [menu-bar hide] 'undefined)
5411 (define-key org-mode-map [menu-bar show] 'undefined))
5413 (org-load-modules-maybe)
5414 (easy-menu-add org-org-menu)
5415 (easy-menu-add org-tbl-menu)
5416 (org-install-agenda-files-menu)
5417 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5418 (add-to-invisibility-spec '(org-cwidth))
5419 (add-to-invisibility-spec '(org-hide-block . t))
5420 (when (featurep 'xemacs)
5421 (org-set-local 'line-move-ignore-invisible t))
5422 (org-set-local 'outline-regexp org-outline-regexp)
5423 (org-set-local 'outline-level 'org-outline-level)
5424 (setq bidi-paragraph-direction 'left-to-right)
5425 (when (and org-ellipsis
5426 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5427 (fboundp 'make-glyph-code))
5428 (unless org-display-table
5429 (setq org-display-table (make-display-table)))
5430 (set-display-table-slot
5431 org-display-table 4
5432 (vconcat (mapcar
5433 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5434 org-ellipsis)))
5435 (if (stringp org-ellipsis) org-ellipsis "..."))))
5436 (setq buffer-display-table org-display-table))
5437 (org-set-regexps-and-options)
5438 (org-set-font-lock-defaults)
5439 (when (and org-tag-faces (not org-tags-special-faces-re))
5440 ;; tag faces set outside customize.... force initialization.
5441 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5442 ;; Calc embedded
5443 (org-set-local 'calc-embedded-open-mode "# ")
5444 ;; Modify a few syntax entries
5445 (modify-syntax-entry ?@ "w")
5446 (modify-syntax-entry ?\" "\"")
5447 (modify-syntax-entry ?\\ "_")
5448 (modify-syntax-entry ?~ "_")
5449 (if org-startup-truncated (setq truncate-lines t))
5450 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5451 (org-set-local 'font-lock-unfontify-region-function
5452 'org-unfontify-region)
5453 ;; Activate before-change-function
5454 (org-set-local 'org-table-may-need-update t)
5455 (org-add-hook 'before-change-functions 'org-before-change-function nil
5456 'local)
5457 ;; Check for running clock before killing a buffer
5458 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5459 ;; Initialize macros templates.
5460 (org-macro-initialize-templates)
5461 ;; Initialize radio targets.
5462 (org-update-radio-target-regexp)
5463 ;; Indentation.
5464 (org-set-local 'indent-line-function 'org-indent-line)
5465 (org-set-local 'indent-region-function 'org-indent-region)
5466 ;; Filling and auto-filling.
5467 (org-setup-filling)
5468 ;; Comments.
5469 (org-setup-comments-handling)
5470 ;; Initialize cache.
5471 (org-element-cache-reset)
5472 ;; Beginning/end of defun
5473 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5474 (org-set-local 'end-of-defun-function
5475 (lambda ()
5476 (if (not (org-at-heading-p))
5477 (org-forward-element)
5478 (org-forward-element)
5479 (forward-char -1))))
5480 ;; Next error for sparse trees
5481 (org-set-local 'next-error-function 'org-occur-next-match)
5482 ;; Make sure dependence stuff works reliably, even for users who set it
5483 ;; too late :-(
5484 (if org-enforce-todo-dependencies
5485 (add-hook 'org-blocker-hook
5486 'org-block-todo-from-children-or-siblings-or-parent)
5487 (remove-hook 'org-blocker-hook
5488 'org-block-todo-from-children-or-siblings-or-parent))
5489 (if org-enforce-todo-checkbox-dependencies
5490 (add-hook 'org-blocker-hook
5491 'org-block-todo-from-checkboxes)
5492 (remove-hook 'org-blocker-hook
5493 'org-block-todo-from-checkboxes))
5495 ;; Align options lines
5496 (org-set-local
5497 'align-mode-rules-list
5498 '((org-in-buffer-settings
5499 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5500 (modes . '(org-mode)))))
5502 ;; Imenu
5503 (org-set-local 'imenu-create-index-function
5504 'org-imenu-get-tree)
5506 ;; Make isearch reveal context
5507 (if (or (featurep 'xemacs)
5508 (not (boundp 'outline-isearch-open-invisible-function)))
5509 ;; Emacs 21 and XEmacs make use of the hook
5510 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5511 ;; Emacs 22 deals with this through a special variable
5512 (org-set-local 'outline-isearch-open-invisible-function
5513 (lambda (&rest ignore) (org-show-context 'isearch))))
5515 ;; Setup the pcomplete hooks
5516 (set (make-local-variable 'pcomplete-command-completion-function)
5517 'org-pcomplete-initial)
5518 (set (make-local-variable 'pcomplete-command-name-function)
5519 'org-command-at-point)
5520 (set (make-local-variable 'pcomplete-default-completion-function)
5521 'ignore)
5522 (set (make-local-variable 'pcomplete-parse-arguments-function)
5523 'org-parse-arguments)
5524 (set (make-local-variable 'pcomplete-termination-string) "")
5525 (when (>= emacs-major-version 23)
5526 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5528 ;; If empty file that did not turn on org-mode automatically, make it to.
5529 (if (and org-insert-mode-line-in-empty-file
5530 (org-called-interactively-p 'any)
5531 (= (point-min) (point-max)))
5532 (insert "# -*- mode: org -*-\n\n"))
5533 (unless org-inhibit-startup
5534 (org-unmodified
5535 (and org-startup-with-beamer-mode (org-beamer-mode))
5536 (when org-startup-align-all-tables
5537 (org-table-map-tables 'org-table-align 'quietly))
5538 (when org-startup-with-inline-images
5539 (org-display-inline-images))
5540 (when org-startup-with-latex-preview
5541 (org-toggle-latex-fragment))
5542 (unless org-inhibit-startup-visibility-stuff
5543 (org-set-startup-visibility))
5544 (org-refresh-effort-properties)))
5545 ;; Try to set org-hide correctly
5546 (let ((foreground (org-find-invisible-foreground)))
5547 (if foreground
5548 (set-face-foreground 'org-hide foreground))))
5550 ;; Update `customize-package-emacs-version-alist'
5551 (add-to-list 'customize-package-emacs-version-alist
5552 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5553 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5554 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5556 (defvar org-mode-transpose-word-syntax-table
5557 (let ((st (make-syntax-table text-mode-syntax-table)))
5558 (mapc (lambda(c) (modify-syntax-entry
5559 (string-to-char (car c)) "w p" st))
5560 org-emphasis-alist)
5561 st))
5563 (when (fboundp 'abbrev-table-put)
5564 (abbrev-table-put org-mode-abbrev-table
5565 :parents (list text-mode-abbrev-table)))
5567 (defun org-find-invisible-foreground ()
5568 (let ((candidates (remove
5569 "unspecified-bg"
5570 (nconc
5571 (list (face-background 'default)
5572 (face-background 'org-default))
5573 (mapcar
5574 (lambda (alist)
5575 (when (boundp alist)
5576 (cdr (assoc 'background-color (symbol-value alist)))))
5577 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5578 (list (face-foreground 'org-hide))))))
5579 (car (remove nil candidates))))
5581 (defun org-current-time (&optional rounding-minutes past)
5582 "Current time, possibly rounded to ROUNDING-MINUTES.
5583 When ROUNDING-MINUTES is not an integer, fall back on the car of
5584 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5585 the rounding returns a past time."
5586 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5587 (car org-time-stamp-rounding-minutes)))
5588 (time (decode-time)) res)
5589 (if (< r 1)
5590 (current-time)
5591 (setq res
5592 (apply 'encode-time
5593 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5594 (nthcdr 2 time))))
5595 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5596 (seconds-to-time (- (org-float-time res) (* r 60)))
5597 res))))
5599 (defun org-today ()
5600 "Return today date, considering `org-extend-today-until'."
5601 (time-to-days
5602 (time-subtract (current-time)
5603 (list 0 (* 3600 org-extend-today-until) 0))))
5605 ;;;; Font-Lock stuff, including the activators
5607 (defvar org-mouse-map (make-sparse-keymap))
5608 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5609 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5610 (when org-mouse-1-follows-link
5611 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5612 (when org-tab-follows-link
5613 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5614 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5616 (require 'font-lock)
5618 (defconst org-non-link-chars "]\t\n\r<>")
5619 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5620 "file+sys" "news" "shell" "elisp" "doi" "message"
5621 "help"))
5622 (defvar org-link-types-re nil
5623 "Matches a link that has a url-like prefix like \"http:\"")
5624 (defvar org-link-re-with-space nil
5625 "Matches a link with spaces, optional angular brackets around it.")
5626 (defvar org-link-re-with-space2 nil
5627 "Matches a link with spaces, optional angular brackets around it.")
5628 (defvar org-link-re-with-space3 nil
5629 "Matches a link with spaces, only for internal part in bracket links.")
5630 (defvar org-angle-link-re nil
5631 "Matches link with angular brackets, spaces are allowed.")
5632 (defvar org-plain-link-re nil
5633 "Matches plain link, without spaces.")
5634 (defvar org-bracket-link-regexp nil
5635 "Matches a link in double brackets.")
5636 (defvar org-bracket-link-analytic-regexp nil
5637 "Regular expression used to analyze links.
5638 Here is what the match groups contain after a match:
5639 1: http:
5640 2: http
5641 3: path
5642 4: [desc]
5643 5: desc")
5644 (defvar org-bracket-link-analytic-regexp++ nil
5645 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5646 (defvar org-any-link-re nil
5647 "Regular expression matching any link.")
5649 (defconst org-match-sexp-depth 3
5650 "Number of stacked braces for sub/superscript matching.")
5652 (defun org-create-multibrace-regexp (left right n)
5653 "Create a regular expression which will match a balanced sexp.
5654 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5655 as single character strings.
5656 The regexp returned will match the entire expression including the
5657 delimiters. It will also define a single group which contains the
5658 match except for the outermost delimiters. The maximum depth of
5659 stacked delimiters is N. Escaping delimiters is not possible."
5660 (let* ((nothing (concat "[^" left right "]*?"))
5661 (or "\\|")
5662 (re nothing)
5663 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5664 (while (> n 1)
5665 (setq n (1- n)
5666 re (concat re or next)
5667 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5668 (concat left "\\(" re "\\)" right)))
5670 (defconst org-match-substring-regexp
5671 (concat
5672 "\\(\\S-\\)\\([_^]\\)\\("
5673 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5674 "\\|"
5675 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5676 "\\|"
5677 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5678 "The regular expression matching a sub- or superscript.")
5680 (defconst org-match-substring-with-braces-regexp
5681 (concat
5682 "\\(\\S-\\)\\([_^]\\)"
5683 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5684 "The regular expression matching a sub- or superscript, forcing braces.")
5686 (defun org-make-link-regexps ()
5687 "Update the link regular expressions.
5688 This should be called after the variable `org-link-types' has changed."
5689 (let ((types-re (regexp-opt org-link-types t)))
5690 (setq org-link-types-re
5691 (concat "\\`" types-re ":")
5692 org-link-re-with-space
5693 (concat "<?" types-re ":"
5694 "\\([^" org-non-link-chars " ]"
5695 "[^" org-non-link-chars "]*"
5696 "[^" org-non-link-chars " ]\\)>?")
5697 org-link-re-with-space2
5698 (concat "<?" types-re ":"
5699 "\\([^" org-non-link-chars " ]"
5700 "[^\t\n\r]*"
5701 "[^" org-non-link-chars " ]\\)>?")
5702 org-link-re-with-space3
5703 (concat "<?" types-re ":"
5704 "\\([^" org-non-link-chars " ]"
5705 "[^\t\n\r]*\\)")
5706 org-angle-link-re
5707 (concat "<" types-re ":"
5708 "\\([^" org-non-link-chars " ]"
5709 "[^" org-non-link-chars "]*"
5710 "\\)>")
5711 org-plain-link-re
5712 (concat
5713 "\\<" types-re ":"
5714 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5715 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5716 org-bracket-link-regexp
5717 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5718 org-bracket-link-analytic-regexp
5719 (concat
5720 "\\[\\["
5721 "\\(" types-re ":\\)?"
5722 "\\([^]]+\\)"
5723 "\\]"
5724 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5725 "\\]")
5726 org-bracket-link-analytic-regexp++
5727 (concat
5728 "\\[\\["
5729 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5730 "\\([^]]+\\)"
5731 "\\]"
5732 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5733 "\\]")
5734 org-any-link-re
5735 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5736 org-angle-link-re "\\)\\|\\("
5737 org-plain-link-re "\\)"))))
5739 (org-make-link-regexps)
5741 (defvar org-emph-face nil)
5743 (defun org-do-emphasis-faces (limit)
5744 "Run through the buffer and emphasize strings."
5745 (let (rtn a)
5746 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5747 (let* ((border (char-after (match-beginning 3)))
5748 (bre (regexp-quote (char-to-string border))))
5749 (if (and (not (= border (char-after (match-beginning 4))))
5750 (not (save-match-data
5751 (string-match (concat bre ".*" bre)
5752 (replace-regexp-in-string
5753 "\n" " "
5754 (substring (match-string 2) 1 -1))))))
5755 (progn
5756 (setq rtn t)
5757 (setq a (assoc (match-string 3) org-emphasis-alist))
5758 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5759 'face
5760 (nth 1 a))
5761 (and (nth 2 a)
5762 (org-remove-flyspell-overlays-in
5763 (match-beginning 0) (match-end 0)))
5764 (add-text-properties (match-beginning 2) (match-end 2)
5765 '(font-lock-multiline t org-emphasis t))
5766 (when org-hide-emphasis-markers
5767 (add-text-properties (match-end 4) (match-beginning 5)
5768 '(invisible org-link))
5769 (add-text-properties (match-beginning 3) (match-end 3)
5770 '(invisible org-link))))))
5771 (goto-char (1+ (match-beginning 0))))
5772 rtn))
5774 (defun org-emphasize (&optional char)
5775 "Insert or change an emphasis, i.e. a font like bold or italic.
5776 If there is an active region, change that region to a new emphasis.
5777 If there is no region, just insert the marker characters and position
5778 the cursor between them.
5779 CHAR should be the marker character. If it is a space, it means to
5780 remove the emphasis of the selected region.
5781 If CHAR is not given (for example in an interactive call) it will be
5782 prompted for."
5783 (interactive)
5784 (let ((erc org-emphasis-regexp-components)
5785 (prompt "")
5786 (string "") beg end move c s)
5787 (if (org-region-active-p)
5788 (setq beg (region-beginning) end (region-end)
5789 string (buffer-substring beg end))
5790 (setq move t))
5792 (unless char
5793 (message "Emphasis marker or tag: [%s]"
5794 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5795 (setq char (read-char-exclusive)))
5796 (if (equal char ?\ )
5797 (setq s "" move nil)
5798 (unless (assoc (char-to-string char) org-emphasis-alist)
5799 (user-error "No such emphasis marker: \"%c\"" char))
5800 (setq s (char-to-string char)))
5801 (while (and (> (length string) 1)
5802 (equal (substring string 0 1) (substring string -1))
5803 (assoc (substring string 0 1) org-emphasis-alist))
5804 (setq string (substring string 1 -1)))
5805 (setq string (concat s string s))
5806 (if beg (delete-region beg end))
5807 (unless (or (bolp)
5808 (string-match (concat "[" (nth 0 erc) "\n]")
5809 (char-to-string (char-before (point)))))
5810 (insert " "))
5811 (unless (or (eobp)
5812 (string-match (concat "[" (nth 1 erc) "\n]")
5813 (char-to-string (char-after (point)))))
5814 (insert " ") (backward-char 1))
5815 (insert string)
5816 (and move (backward-char 1))))
5818 (defconst org-nonsticky-props
5819 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5821 (defsubst org-rear-nonsticky-at (pos)
5822 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5824 (defun org-activate-plain-links (limit)
5825 "Add link properties for plain links."
5826 (let (f hl)
5827 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5828 (not (member 'org-tag
5829 (get-text-property (1- (match-beginning 0)) 'face)))
5830 (not (org-in-src-block-p)))
5831 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5832 (setq f (get-text-property (match-beginning 0) 'face))
5833 (setq hl (org-match-string-no-properties 0))
5834 (if (or (eq f 'org-tag)
5835 (and (listp f) (memq 'org-tag f)))
5837 (add-text-properties (match-beginning 0) (match-end 0)
5838 (list 'mouse-face 'highlight
5839 'face 'org-link
5840 'htmlize-link `(:uri ,hl)
5841 'keymap org-mouse-map))
5842 (org-rear-nonsticky-at (match-end 0)))
5843 t)))
5845 (defun org-activate-code (limit)
5846 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5847 (progn
5848 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5849 (remove-text-properties (match-beginning 0) (match-end 0)
5850 '(display t invisible t intangible t))
5851 t)))
5853 (defcustom org-src-fontify-natively t
5854 "When non-nil, fontify code in code blocks."
5855 :type 'boolean
5856 :version "24.4"
5857 :package-version '(Org . "8.3")
5858 :group 'org-appearance
5859 :group 'org-babel)
5861 (defcustom org-allow-promoting-top-level-subtree nil
5862 "When non-nil, allow promoting a top level subtree.
5863 The leading star of the top level headline will be replaced
5864 by a #."
5865 :type 'boolean
5866 :version "24.1"
5867 :group 'org-appearance)
5869 (defun org-fontify-meta-lines-and-blocks (limit)
5870 (condition-case nil
5871 (org-fontify-meta-lines-and-blocks-1 limit)
5872 (error (message "org-mode fontification error"))))
5874 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5875 "Fontify #+ lines and blocks."
5876 (let ((case-fold-search t))
5877 (if (re-search-forward
5878 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5879 limit t)
5880 (let ((beg (match-beginning 0))
5881 (block-start (match-end 0))
5882 (block-end nil)
5883 (lang (match-string 7))
5884 (beg1 (line-beginning-position 2))
5885 (dc1 (downcase (match-string 2)))
5886 (dc3 (downcase (match-string 3)))
5887 end end1 quoting block-type ovl)
5888 (cond
5889 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5890 ;; a single line of backend-specific content
5891 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5892 (remove-text-properties (match-beginning 0) (match-end 0)
5893 '(display t invisible t intangible t))
5894 (add-text-properties (match-beginning 1) (match-end 3)
5895 '(font-lock-fontified t face org-meta-line))
5896 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5897 '(font-lock-fontified t face org-block))
5898 ; for backend-specific code
5900 ((and (match-end 4) (equal dc3 "+begin"))
5901 ;; Truly a block
5902 (setq block-type (downcase (match-string 5))
5903 quoting (member block-type org-protecting-blocks))
5904 (when (re-search-forward
5905 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5906 nil t) ;; on purpose, we look further than LIMIT
5907 (setq end (min (point-max) (match-end 0))
5908 end1 (min (point-max) (1- (match-beginning 0))))
5909 (setq block-end (match-beginning 0))
5910 (when quoting
5911 (org-remove-flyspell-overlays-in beg1 end1)
5912 (remove-text-properties beg end
5913 '(display t invisible t intangible t)))
5914 (add-text-properties
5915 beg end '(font-lock-fontified t font-lock-multiline t))
5916 (add-text-properties beg beg1 '(face org-meta-line))
5917 (org-remove-flyspell-overlays-in beg beg1)
5918 (add-text-properties ; For end_src
5919 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5920 (org-remove-flyspell-overlays-in end1 end)
5921 (cond
5922 ((and lang (not (string= lang "")) org-src-fontify-natively)
5923 (org-src-font-lock-fontify-block lang block-start block-end)
5924 (add-text-properties beg1 block-end '(src-block t)))
5925 (quoting
5926 (add-text-properties beg1 (min (point-max) (1+ end1))
5927 '(face org-block))) ; end of source block
5928 ((not org-fontify-quote-and-verse-blocks))
5929 ((string= block-type "quote")
5930 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5931 ((string= block-type "verse")
5932 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5933 (add-text-properties beg beg1 '(face org-block-begin-line))
5934 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5935 '(face org-block-end-line))
5937 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5938 (org-remove-flyspell-overlays-in
5939 (match-beginning 0)
5940 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5941 (add-text-properties
5942 beg (match-end 3)
5943 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5944 '(font-lock-fontified t invisible t)
5945 '(font-lock-fontified t face org-document-info-keyword)))
5946 (add-text-properties
5947 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5948 (if (string-equal dc1 "+title:")
5949 '(font-lock-fontified t face org-document-title)
5950 '(font-lock-fontified t face org-document-info))))
5951 ((or (equal dc1 "+results")
5952 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5953 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5954 "+call:" "+header:" "+headers:" "+name:"))
5955 (and (match-end 4) (equal dc3 "+attr")))
5956 (org-remove-flyspell-overlays-in
5957 (match-beginning 0)
5958 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5959 (add-text-properties
5960 beg (match-end 0)
5961 '(font-lock-fontified t face org-meta-line))
5963 ((member dc3 '(" " ""))
5964 (org-remove-flyspell-overlays-in beg (match-end 0))
5965 (add-text-properties
5966 beg (match-end 0)
5967 '(font-lock-fontified t face font-lock-comment-face)))
5968 (t ;; just any other in-buffer setting, but not indented
5969 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5970 (add-text-properties
5971 beg (match-end 0)
5972 '(font-lock-fontified t face org-meta-line))
5973 t))))))
5975 (defun org-fontify-drawers (limit)
5976 "Fontify drawers."
5977 (when (re-search-forward org-drawer-regexp limit t)
5978 (add-text-properties
5979 (match-beginning 0) (match-end 0)
5980 '(font-lock-fontified t face org-special-keyword))
5981 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5984 (defun org-fontify-macros (limit)
5985 "Fontify macros."
5986 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5987 (add-text-properties
5988 (match-beginning 0) (match-end 0)
5989 '(font-lock-fontified t face org-macro))
5990 (when org-hide-macro-markers
5991 (add-text-properties (match-end 2) (match-beginning 2)
5992 '(invisible t))
5993 (add-text-properties (match-beginning 1) (match-end 1)
5994 '(invisible t)))
5995 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5998 (defun org-activate-angle-links (limit)
5999 "Add text properties for angle links."
6000 (if (and (re-search-forward org-angle-link-re limit t)
6001 (not (org-in-src-block-p)))
6002 (progn
6003 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6004 (add-text-properties (match-beginning 0) (match-end 0)
6005 (list 'mouse-face 'highlight
6006 'keymap org-mouse-map))
6007 (org-rear-nonsticky-at (match-end 0))
6008 t)))
6010 (defun org-activate-footnote-links (limit)
6011 "Add text properties for footnotes."
6012 (let ((fn (org-footnote-next-reference-or-definition limit)))
6013 (when fn
6014 (let* ((beg (nth 1 fn))
6015 (end (nth 2 fn))
6016 (label (car fn))
6017 (referencep (/= (line-beginning-position) beg)))
6018 (when (and referencep (nth 3 fn))
6019 (save-excursion
6020 (goto-char beg)
6021 (search-forward (or label "fn:"))
6022 (org-remove-flyspell-overlays-in beg (match-end 0))))
6023 (add-text-properties beg end
6024 (list 'mouse-face 'highlight
6025 'keymap org-mouse-map
6026 'help-echo
6027 (if referencep "Footnote reference"
6028 "Footnote definition")
6029 'font-lock-fontified t
6030 'font-lock-multiline t
6031 'face 'org-footnote))))))
6033 (defun org-activate-bracket-links (limit)
6034 "Add text properties for bracketed links."
6035 (if (and (re-search-forward org-bracket-link-regexp limit t)
6036 (not (org-in-src-block-p)))
6037 (let* ((hl (org-match-string-no-properties 1))
6038 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6039 (ip (org-maybe-intangible
6040 (list 'invisible 'org-link
6041 'keymap org-mouse-map 'mouse-face 'highlight
6042 'font-lock-multiline t 'help-echo help
6043 'htmlize-link `(:uri ,hl))))
6044 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6045 'font-lock-multiline t 'help-echo help
6046 'htmlize-link `(:uri ,hl))))
6047 ;; We need to remove the invisible property here. Table narrowing
6048 ;; may have made some of this invisible.
6049 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6050 (remove-text-properties (match-beginning 0) (match-end 0)
6051 '(invisible nil))
6052 (if (match-end 3)
6053 (progn
6054 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6055 (org-rear-nonsticky-at (match-beginning 3))
6056 (add-text-properties (match-beginning 3) (match-end 3) vp)
6057 (org-rear-nonsticky-at (match-end 3))
6058 (add-text-properties (match-end 3) (match-end 0) ip)
6059 (org-rear-nonsticky-at (match-end 0)))
6060 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6061 (org-rear-nonsticky-at (match-beginning 1))
6062 (add-text-properties (match-beginning 1) (match-end 1) vp)
6063 (org-rear-nonsticky-at (match-end 1))
6064 (add-text-properties (match-end 1) (match-end 0) ip)
6065 (org-rear-nonsticky-at (match-end 0)))
6066 t)))
6068 (defun org-activate-dates (limit)
6069 "Add text properties for dates."
6070 (if (and (re-search-forward org-tsr-regexp-both limit t)
6071 (not (equal (char-before (match-beginning 0)) 91)))
6072 (progn
6073 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6074 (add-text-properties (match-beginning 0) (match-end 0)
6075 (list 'mouse-face 'highlight
6076 'keymap org-mouse-map))
6077 (org-rear-nonsticky-at (match-end 0))
6078 (when org-display-custom-times
6079 (if (match-end 3)
6080 (org-display-custom-time (match-beginning 3) (match-end 3)))
6081 (org-display-custom-time (match-beginning 1) (match-end 1)))
6082 t)))
6084 (defvar org-target-link-regexp nil
6085 "Regular expression matching radio targets in plain text.")
6086 (make-variable-buffer-local 'org-target-link-regexp)
6088 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6089 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6090 border border border))
6091 "Regular expression matching a link target.")
6093 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6094 "Regular expression matching a radio target.")
6096 (defconst org-any-target-regexp
6097 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6098 "Regular expression matching any target.")
6100 (defun org-activate-target-links (limit)
6101 "Add text properties for target matches."
6102 (when org-target-link-regexp
6103 (let ((case-fold-search t))
6104 (if (re-search-forward org-target-link-regexp limit t)
6105 (progn
6106 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6107 (add-text-properties (match-beginning 1) (match-end 1)
6108 (list 'mouse-face 'highlight
6109 'keymap org-mouse-map
6110 'help-echo "Radio target link"
6111 'org-linked-text t))
6112 (org-rear-nonsticky-at (match-end 1))
6113 t)))))
6115 (defun org-update-radio-target-regexp ()
6116 "Find all radio targets in this file and update the regular expression.
6117 Also refresh fontification if needed."
6118 (interactive)
6119 (let ((old-regexp org-target-link-regexp)
6120 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6121 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6122 (targets
6123 (org-with-wide-buffer
6124 (goto-char (point-min))
6125 (let (rtn)
6126 (while (re-search-forward org-radio-target-regexp nil t)
6127 ;; Make sure point is really within the object.
6128 (backward-char)
6129 (let ((obj (org-element-context)))
6130 (when (eq (org-element-type obj) 'radio-target)
6131 (add-to-list 'rtn (org-element-property :value obj)))))
6132 rtn))))
6133 (setq org-target-link-regexp
6134 (and targets
6135 (concat before-re
6136 (mapconcat
6137 (lambda (x)
6138 (replace-regexp-in-string
6139 " +" "\\s-+" (regexp-quote x) t t))
6140 targets
6141 "\\|")
6142 after-re)))
6143 (unless (equal old-regexp org-target-link-regexp)
6144 ;; Clean-up cache.
6145 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6146 ((not org-target-link-regexp) old-regexp)
6148 (concat before-re
6149 (mapconcat
6150 (lambda (re)
6151 (substring re (length before-re)
6152 (- (length after-re))))
6153 (list old-regexp org-target-link-regexp)
6154 "\\|")
6155 after-re)))))
6156 (org-with-wide-buffer
6157 (goto-char (point-min))
6158 (while (re-search-forward regexp nil t)
6159 (org-element-cache-refresh (match-beginning 1)))))
6160 ;; Re fontify buffer.
6161 (when (memq 'radio org-highlight-links)
6162 (org-restart-font-lock)))))
6164 (defun org-hide-wide-columns (limit)
6165 (let (s e)
6166 (setq s (text-property-any (point) (or limit (point-max))
6167 'org-cwidth t))
6168 (when s
6169 (setq e (next-single-property-change s 'org-cwidth))
6170 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6171 (goto-char e)
6172 t)))
6174 (defvar org-latex-and-related-regexp nil
6175 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6177 (defun org-compute-latex-and-related-regexp ()
6178 "Compute regular expression for LaTeX, entities and sub/superscript.
6179 Result depends on variable `org-highlight-latex-and-related'."
6180 (org-set-local
6181 'org-latex-and-related-regexp
6182 (let* ((re-sub
6183 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6184 ((eq org-use-sub-superscripts '{})
6185 (list org-match-substring-with-braces-regexp))
6186 (org-use-sub-superscripts (list org-match-substring-regexp))))
6187 (re-latex
6188 (when (memq 'latex org-highlight-latex-and-related)
6189 (let ((matchers (plist-get org-format-latex-options :matchers)))
6190 (delq nil
6191 (mapcar (lambda (x)
6192 (and (member (car x) matchers) (nth 1 x)))
6193 org-latex-regexps)))))
6194 (re-entities
6195 (when (memq 'entities org-highlight-latex-and-related)
6196 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6197 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6199 (defun org-do-latex-and-related (limit)
6200 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6201 LIMIT bounds the search for syntax to highlight. Stop at first
6202 highlighted object, if any. Return t if some highlighting was
6203 done, nil otherwise."
6204 (when (org-string-nw-p org-latex-and-related-regexp)
6205 (catch 'found
6206 (while (re-search-forward org-latex-and-related-regexp limit t)
6207 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6208 'face))
6209 '(org-code org-verbatim underline))
6210 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6211 '(?_ ?^))
6213 0)))
6214 (font-lock-prepend-text-property
6215 (+ offset (match-beginning 0)) (match-end 0)
6216 'face 'org-latex-and-related)
6217 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6218 '(font-lock-multiline t)))
6219 (throw 'found t)))
6220 nil)))
6222 (defun org-restart-font-lock ()
6223 "Restart `font-lock-mode', to force refontification."
6224 (when (and (boundp 'font-lock-mode) font-lock-mode)
6225 (font-lock-mode -1)
6226 (font-lock-mode 1)))
6228 (defun org-activate-tags (limit)
6229 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6230 (progn
6231 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6232 (add-text-properties (match-beginning 1) (match-end 1)
6233 (list 'mouse-face 'highlight
6234 'keymap org-mouse-map))
6235 (org-rear-nonsticky-at (match-end 1))
6236 t)))
6238 (defun org-outline-level ()
6239 "Compute the outline level of the heading at point.
6241 If this is called at a normal headline, the level is the number
6242 of stars. Use `org-reduced-level' to remove the effect of
6243 `org-odd-levels'. Unlike to `org-current-level', this function
6244 takes into consideration inlinetasks."
6245 (org-with-wide-buffer
6246 (end-of-line)
6247 (if (re-search-backward org-outline-regexp-bol nil t)
6248 (1- (- (match-end 0) (match-beginning 0)))
6249 0)))
6251 (defvar org-font-lock-keywords nil)
6253 (defsubst org-re-property (property &optional literal allow-null)
6254 "Return a regexp matching a PROPERTY line.
6256 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6257 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6258 non-nil, match properties even without a value.
6260 Match group 3 is set to the value when it exists. If there is no
6261 value and ALLOW-NULL is non-nil, it is set to the empty string."
6262 (concat
6263 "^\\(?4:[ \t]*\\)"
6264 (format "\\(?1::\\(?2:%s\\):\\)"
6265 (if literal property (regexp-quote property)))
6266 (if allow-null
6267 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$"
6268 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$")))
6270 (defconst org-property-re
6271 (org-re-property "\\S-+" 'literal t)
6272 "Regular expression matching a property line.
6273 There are four matching groups:
6274 1: :PROPKEY: including the leading and trailing colon,
6275 2: PROPKEY without the leading and trailing colon,
6276 3: PROPVAL without leading or trailing spaces,
6277 4: the indentation of the current line,
6278 5: trailing whitespace.")
6280 (defvar org-font-lock-hook nil
6281 "Functions to be called for special font lock stuff.")
6283 (defvar org-font-lock-set-keywords-hook nil
6284 "Functions that can manipulate `org-font-lock-extra-keywords'.
6285 This is called after `org-font-lock-extra-keywords' is defined, but before
6286 it is installed to be used by font lock. This can be useful if something
6287 needs to be inserted at a specific position in the font-lock sequence.")
6289 (defun org-font-lock-hook (limit)
6290 "Run `org-font-lock-hook' within LIMIT."
6291 (run-hook-with-args 'org-font-lock-hook limit))
6293 (defun org-set-font-lock-defaults ()
6294 "Set font lock defaults for the current buffer."
6295 (let* ((em org-fontify-emphasized-text)
6296 (lk org-highlight-links)
6297 (org-font-lock-extra-keywords
6298 (list
6299 ;; Call the hook
6300 '(org-font-lock-hook)
6301 ;; Headlines
6302 `(,(if org-fontify-whole-heading-line
6303 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6304 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6305 (1 (org-get-level-face 1))
6306 (2 (org-get-level-face 2))
6307 (3 (org-get-level-face 3)))
6308 ;; Table lines
6309 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6310 (1 'org-table t))
6311 ;; Table internals
6312 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6313 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6314 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6315 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6316 ;; Drawers
6317 '(org-fontify-drawers)
6318 ;; Properties
6319 (list org-property-re
6320 '(1 'org-special-keyword t)
6321 '(3 'org-property-value t))
6322 ;; Links
6323 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6324 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6325 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6326 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6327 (if (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6328 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6329 (if (memq 'footnote lk) '(org-activate-footnote-links))
6330 ;; Targets.
6331 (list org-any-target-regexp '(0 'org-target t))
6332 ;; Diary sexps.
6333 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6334 ;; Macro
6335 '(org-fontify-macros)
6336 '(org-hide-wide-columns (0 nil append))
6337 ;; TODO keyword
6338 (list (format org-heading-keyword-regexp-format
6339 org-todo-regexp)
6340 '(2 (org-get-todo-face 2) t))
6341 ;; DONE
6342 (if org-fontify-done-headline
6343 (list (format org-heading-keyword-regexp-format
6344 (concat
6345 "\\(?:"
6346 (mapconcat 'regexp-quote org-done-keywords "\\|")
6347 "\\)"))
6348 '(2 'org-headline-done t))
6349 nil)
6350 ;; Priorities
6351 '(org-font-lock-add-priority-faces)
6352 ;; Tags
6353 '(org-font-lock-add-tag-faces)
6354 ;; Tags groups
6355 (if (and org-group-tags org-tag-groups-alist)
6356 (list (concat org-outline-regexp-bol ".+\\(:"
6357 (regexp-opt (mapcar 'car org-tag-groups-alist))
6358 ":\\).*$")
6359 '(1 'org-tag-group prepend)))
6360 ;; Special keywords
6361 (list (concat "\\<" org-comment-string) '(0 'org-special-keyword t))
6362 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6363 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6364 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6365 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6366 ;; Emphasis
6367 (if em
6368 (if (featurep 'xemacs)
6369 '(org-do-emphasis-faces (0 nil append))
6370 '(org-do-emphasis-faces)))
6371 ;; Checkboxes
6372 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6373 1 'org-checkbox prepend)
6374 (if (cdr (assq 'checkbox org-list-automatic-rules))
6375 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6376 (0 (org-get-checkbox-statistics-face) t)))
6377 ;; Description list items
6378 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6379 1 'org-list-dt prepend)
6380 ;; ARCHIVEd headings
6381 (list (concat
6382 org-outline-regexp-bol
6383 "\\(.*:" org-archive-tag ":.*\\)")
6384 '(1 'org-archived prepend))
6385 ;; Specials
6386 '(org-do-latex-and-related)
6387 '(org-fontify-entities)
6388 '(org-raise-scripts)
6389 ;; Code
6390 '(org-activate-code (1 'org-code t))
6391 ;; COMMENT
6392 (list (format
6393 "^\\*\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6394 org-todo-regexp
6395 org-comment-string)
6396 '(9 'org-special-keyword t))
6397 ;; Blocks and meta lines
6398 '(org-fontify-meta-lines-and-blocks))))
6399 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6400 (run-hooks 'org-font-lock-set-keywords-hook)
6401 ;; Now set the full font-lock-keywords
6402 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6403 (org-set-local 'font-lock-defaults
6404 '(org-font-lock-keywords t nil nil backward-paragraph))
6405 (kill-local-variable 'font-lock-keywords) nil))
6407 (defun org-toggle-pretty-entities ()
6408 "Toggle the composition display of entities as UTF8 characters."
6409 (interactive)
6410 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6411 (org-restart-font-lock)
6412 (if org-pretty-entities
6413 (message "Entities are now displayed as UTF8 characters")
6414 (save-restriction
6415 (widen)
6416 (org-decompose-region (point-min) (point-max))
6417 (message "Entities are now displayed as plain text"))))
6419 (defvar org-custom-properties-overlays nil
6420 "List of overlays used for custom properties.")
6421 (make-variable-buffer-local 'org-custom-properties-overlays)
6423 (defun org-toggle-custom-properties-visibility ()
6424 "Display or hide properties in `org-custom-properties'."
6425 (interactive)
6426 (if org-custom-properties-overlays
6427 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6428 (setq org-custom-properties-overlays nil))
6429 (when org-custom-properties
6430 (org-with-wide-buffer
6431 (goto-char (point-min))
6432 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6433 (while (re-search-forward regexp nil t)
6434 (let ((end (cdr (save-match-data (org-get-property-block)))))
6435 (when (and end (< (point) end))
6436 ;; Hide first custom property in current drawer.
6437 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6438 (overlay-put o 'invisible t)
6439 (overlay-put o 'org-custom-property t)
6440 (push o org-custom-properties-overlays))
6441 ;; Hide additional custom properties in the same drawer.
6442 (while (re-search-forward regexp end t)
6443 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6444 (overlay-put o 'invisible t)
6445 (overlay-put o 'org-custom-property t)
6446 (push o org-custom-properties-overlays)))))
6447 ;; Each entry is limited to a single property drawer.
6448 (outline-next-heading)))))))
6450 (defun org-fontify-entities (limit)
6451 "Find an entity to fontify."
6452 (let (ee)
6453 (when org-pretty-entities
6454 (catch 'match
6455 (while (re-search-forward
6456 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6457 limit t)
6458 (if (and (not (org-at-comment-p))
6459 (setq ee (org-entity-get (match-string 1)))
6460 (= (length (nth 6 ee)) 1))
6461 (let*
6462 ((end (if (equal (match-string 2) "{}")
6463 (match-end 2)
6464 (match-end 1))))
6465 (add-text-properties
6466 (match-beginning 0) end
6467 (list 'font-lock-fontified t))
6468 (compose-region (match-beginning 0) end
6469 (nth 6 ee) nil)
6470 (backward-char 1)
6471 (throw 'match t))))
6472 nil))))
6474 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6475 "Fontify string S like in Org-mode."
6476 (with-temp-buffer
6477 (insert s)
6478 (let ((org-odd-levels-only odd-levels))
6479 (org-mode)
6480 (font-lock-ensure)
6481 (buffer-string))))
6483 (defvar org-m nil)
6484 (defvar org-l nil)
6485 (defvar org-f nil)
6486 (defun org-get-level-face (n)
6487 "Get the right face for match N in font-lock matching of headlines."
6488 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6489 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6490 (if org-cycle-level-faces
6491 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6492 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6493 (cond
6494 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6495 ((eq n 2) org-f)
6496 (t (if org-level-color-stars-only nil org-f))))
6499 (defun org-get-todo-face (kwd)
6500 "Get the right face for a TODO keyword KWD.
6501 If KWD is a number, get the corresponding match group."
6502 (if (numberp kwd) (setq kwd (match-string kwd)))
6503 (or (org-face-from-face-or-color
6504 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6505 (and (member kwd org-done-keywords) 'org-done)
6506 'org-todo))
6508 (defun org-face-from-face-or-color (context inherit face-or-color)
6509 "Create a face list that inherits INHERIT, but sets the foreground color.
6510 When FACE-OR-COLOR is not a string, just return it."
6511 (if (stringp face-or-color)
6512 (list :inherit inherit
6513 (cdr (assoc context org-faces-easy-properties))
6514 face-or-color)
6515 face-or-color))
6517 (defun org-font-lock-add-tag-faces (limit)
6518 "Add the special tag faces."
6519 (when (and org-tag-faces org-tags-special-faces-re)
6520 (while (re-search-forward org-tags-special-faces-re limit t)
6521 (add-text-properties (match-beginning 1) (match-end 1)
6522 (list 'face (org-get-tag-face 1)
6523 'font-lock-fontified t))
6524 (backward-char 1))))
6526 (defun org-font-lock-add-priority-faces (limit)
6527 "Add the special priority faces."
6528 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6529 (when (save-match-data (org-at-heading-p))
6530 (add-text-properties
6531 (match-beginning 0) (match-end 0)
6532 (list 'face (or (org-face-from-face-or-color
6533 'priority 'org-priority
6534 (cdr (assoc (char-after (match-beginning 1))
6535 org-priority-faces)))
6536 'org-priority)
6537 'font-lock-fontified t)))))
6539 (defun org-get-tag-face (kwd)
6540 "Get the right face for a TODO keyword KWD.
6541 If KWD is a number, get the corresponding match group."
6542 (if (numberp kwd) (setq kwd (match-string kwd)))
6543 (or (org-face-from-face-or-color
6544 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6545 'org-tag))
6547 (defun org-unfontify-region (beg end &optional maybe_loudly)
6548 "Remove fontification and activation overlays from links."
6549 (font-lock-default-unfontify-region beg end)
6550 (let* ((buffer-undo-list t)
6551 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6552 (inhibit-modification-hooks t)
6553 deactivate-mark buffer-file-name buffer-file-truename)
6554 (org-decompose-region beg end)
6555 (remove-text-properties beg end
6556 '(mouse-face t keymap t org-linked-text t
6557 invisible t intangible t
6558 org-emphasis t))
6559 (org-remove-font-lock-display-properties beg end)))
6561 (defconst org-script-display '(((raise -0.3) (height 0.7))
6562 ((raise 0.3) (height 0.7))
6563 ((raise -0.5))
6564 ((raise 0.5)))
6565 "Display properties for showing superscripts and subscripts.")
6567 (defun org-remove-font-lock-display-properties (beg end)
6568 "Remove specific display properties that have been added by font lock.
6569 The will remove the raise properties that are used to show superscripts
6570 and subscripts."
6571 (let (next prop)
6572 (while (< beg end)
6573 (setq next (next-single-property-change beg 'display nil end)
6574 prop (get-text-property beg 'display))
6575 (if (member prop org-script-display)
6576 (put-text-property beg next 'display nil))
6577 (setq beg next))))
6579 (defun org-raise-scripts (limit)
6580 "Add raise properties to sub/superscripts."
6581 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6582 (if (re-search-forward
6583 (if (eq org-use-sub-superscripts t)
6584 org-match-substring-regexp
6585 org-match-substring-with-braces-regexp)
6586 limit t)
6587 (let* ((pos (point)) table-p comment-p
6588 (mpos (match-beginning 3))
6589 (emph-p (get-text-property mpos 'org-emphasis))
6590 (link-p (get-text-property mpos 'mouse-face))
6591 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6592 (goto-char (point-at-bol))
6593 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6594 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6595 (goto-char pos)
6596 ;; Handle a_b^c
6597 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6598 (if (or comment-p emph-p link-p keyw-p)
6600 (put-text-property (match-beginning 3) (match-end 0)
6601 'display
6602 (if (equal (char-after (match-beginning 2)) ?^)
6603 (nth (if table-p 3 1) org-script-display)
6604 (nth (if table-p 2 0) org-script-display)))
6605 (add-text-properties (match-beginning 2) (match-end 2)
6606 (list 'invisible t
6607 'org-dwidth t 'org-dwidth-n 1))
6608 (if (and (eq (char-after (match-beginning 3)) ?{)
6609 (eq (char-before (match-end 3)) ?}))
6610 (progn
6611 (add-text-properties
6612 (match-beginning 3) (1+ (match-beginning 3))
6613 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6614 (add-text-properties
6615 (1- (match-end 3)) (match-end 3)
6616 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6617 t)))))
6619 ;;;; Visibility cycling, including org-goto and indirect buffer
6621 ;;; Cycling
6623 (defvar org-cycle-global-status nil)
6624 (make-variable-buffer-local 'org-cycle-global-status)
6625 (put 'org-cycle-global-status 'org-state t)
6626 (defvar org-cycle-subtree-status nil)
6627 (make-variable-buffer-local 'org-cycle-subtree-status)
6628 (put 'org-cycle-subtree-status 'org-state t)
6630 (defvar org-inlinetask-min-level)
6632 (defun org-unlogged-message (&rest args)
6633 "Display a message, but avoid logging it in the *Messages* buffer."
6634 (let ((message-log-max nil))
6635 (apply 'message args)))
6637 ;;;###autoload
6638 (defun org-cycle (&optional arg)
6639 "TAB-action and visibility cycling for Org-mode.
6641 This is the command invoked in Org-mode by the TAB key. Its main purpose
6642 is outline visibility cycling, but it also invokes other actions
6643 in special contexts.
6645 - When this function is called with a prefix argument, rotate the entire
6646 buffer through 3 states (global cycling)
6647 1. OVERVIEW: Show only top-level headlines.
6648 2. CONTENTS: Show all headlines of all levels, but no body text.
6649 3. SHOW ALL: Show everything.
6650 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6651 determined by the variable `org-startup-folded', and by any VISIBILITY
6652 properties in the buffer.
6653 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6654 including any drawers.
6656 - When inside a table, re-align the table and move to the next field.
6658 - When point is at the beginning of a headline, rotate the subtree started
6659 by this line through 3 different states (local cycling)
6660 1. FOLDED: Only the main headline is shown.
6661 2. CHILDREN: The main headline and the direct children are shown.
6662 From this state, you can move to one of the children
6663 and zoom in further.
6664 3. SUBTREE: Show the entire subtree, including body text.
6665 If there is no subtree, switch directly from CHILDREN to FOLDED.
6667 - When point is at the beginning of an empty headline and the variable
6668 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6669 of the headline by demoting and promoting it to likely levels. This
6670 speeds up creation document structure by pressing TAB once or several
6671 times right after creating a new headline.
6673 - When there is a numeric prefix, go up to a heading with level ARG, do
6674 a `show-subtree' and return to the previous cursor position. If ARG
6675 is negative, go up that many levels.
6677 - When point is not at the beginning of a headline, execute the global
6678 binding for TAB, which is re-indenting the line. See the option
6679 `org-cycle-emulate-tab' for details.
6681 - Special case: if point is at the beginning of the buffer and there is
6682 no headline in line 1, this function will act as if called with prefix arg
6683 (C-u TAB, same as S-TAB) also when called without prefix arg.
6684 But only if also the variable `org-cycle-global-at-bob' is t."
6685 (interactive "P")
6686 (org-load-modules-maybe)
6687 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6688 (and org-cycle-level-after-item/entry-creation
6689 (or (org-cycle-level)
6690 (org-cycle-item-indentation))))
6691 (let* ((limit-level
6692 (or org-cycle-max-level
6693 (and (boundp 'org-inlinetask-min-level)
6694 org-inlinetask-min-level
6695 (1- org-inlinetask-min-level))))
6696 (nstars (and limit-level
6697 (if org-odd-levels-only
6698 (and limit-level (1- (* limit-level 2)))
6699 limit-level)))
6700 (org-outline-regexp
6701 (if (not (derived-mode-p 'org-mode))
6702 outline-regexp
6703 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6704 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6705 (not (looking-at org-outline-regexp))))
6706 (org-cycle-hook
6707 (if bob-special
6708 (delq 'org-optimize-window-after-visibility-change
6709 (copy-sequence org-cycle-hook))
6710 org-cycle-hook))
6711 (pos (point)))
6713 (if (or bob-special (equal arg '(4)))
6714 ;; special case: use global cycling
6715 (setq arg t))
6717 (cond
6719 ((equal arg '(16))
6720 (setq last-command 'dummy)
6721 (org-set-startup-visibility)
6722 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6724 ((equal arg '(64))
6725 (show-all)
6726 (org-unlogged-message "Entire buffer visible, including drawers"))
6728 ;; Try cdlatex TAB completion
6729 ((org-try-cdlatex-tab))
6731 ;; Table: enter it or move to the next field.
6732 ((org-at-table-p 'any)
6733 (if (org-at-table.el-p)
6734 (message "Use C-c ' to edit table.el tables")
6735 (if arg (org-table-edit-field t)
6736 (org-table-justify-field-maybe)
6737 (call-interactively 'org-table-next-field))))
6739 ((run-hook-with-args-until-success
6740 'org-tab-after-check-for-table-hook))
6742 ;; Global cycling: delegate to `org-cycle-internal-global'.
6743 ((eq arg t) (org-cycle-internal-global))
6745 ;; Drawers: delegate to `org-flag-drawer'.
6746 ((save-excursion
6747 (beginning-of-line 1)
6748 (looking-at org-drawer-regexp))
6749 (org-flag-drawer ; toggle block visibility
6750 (not (get-char-property (match-end 0) 'invisible))))
6752 ;; Show-subtree, ARG levels up from here.
6753 ((integerp arg)
6754 (save-excursion
6755 (org-back-to-heading)
6756 (outline-up-heading (if (< arg 0) (- arg)
6757 (- (funcall outline-level) arg)))
6758 (org-show-subtree)))
6760 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6761 ((and (featurep 'org-inlinetask)
6762 (org-inlinetask-at-task-p)
6763 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6764 (org-inlinetask-toggle-visibility))
6766 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6767 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6768 (save-excursion (beginning-of-line 1)
6769 (looking-at org-outline-regexp)))
6770 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6771 (org-cycle-internal-local))
6773 ;; From there: TAB emulation and template completion.
6774 (buffer-read-only (org-back-to-heading))
6776 ((run-hook-with-args-until-success
6777 'org-tab-after-check-for-cycling-hook))
6779 ((org-try-structure-completion))
6781 ((run-hook-with-args-until-success
6782 'org-tab-before-tab-emulation-hook))
6784 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6785 (or (not (bolp))
6786 (not (looking-at org-outline-regexp))))
6787 (call-interactively (global-key-binding "\t")))
6789 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6790 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6791 (or (and (eq org-cycle-emulate-tab 'white)
6792 (= (match-end 0) (point-at-eol)))
6793 (and (eq org-cycle-emulate-tab 'whitestart)
6794 (>= (match-end 0) pos))))
6796 (eq org-cycle-emulate-tab t))
6797 (call-interactively (global-key-binding "\t")))
6799 (t (save-excursion
6800 (org-back-to-heading)
6801 (org-cycle)))))))
6803 (defun org-cycle-internal-global ()
6804 "Do the global cycling action."
6805 ;; Hack to avoid display of messages for .org attachments in Gnus
6806 (let ((ga (string-match "\\*fontification" (buffer-name))))
6807 (cond
6808 ((and (eq last-command this-command)
6809 (eq org-cycle-global-status 'overview))
6810 ;; We just created the overview - now do table of contents
6811 ;; This can be slow in very large buffers, so indicate action
6812 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6813 (unless ga (org-unlogged-message "CONTENTS..."))
6814 (org-content)
6815 (unless ga (org-unlogged-message "CONTENTS...done"))
6816 (setq org-cycle-global-status 'contents)
6817 (run-hook-with-args 'org-cycle-hook 'contents))
6819 ((and (eq last-command this-command)
6820 (eq org-cycle-global-status 'contents))
6821 ;; We just showed the table of contents - now show everything
6822 (run-hook-with-args 'org-pre-cycle-hook 'all)
6823 (show-all)
6824 (unless ga (org-unlogged-message "SHOW ALL"))
6825 (setq org-cycle-global-status 'all)
6826 (run-hook-with-args 'org-cycle-hook 'all))
6829 ;; Default action: go to overview
6830 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6831 (org-overview)
6832 (unless ga (org-unlogged-message "OVERVIEW"))
6833 (setq org-cycle-global-status 'overview)
6834 (run-hook-with-args 'org-cycle-hook 'overview)))))
6836 (defvar org-called-with-limited-levels nil
6837 "Non-nil when `org-with-limited-levels' is currently active.")
6839 (defun org-cycle-internal-local ()
6840 "Do the local cycling action."
6841 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6842 ;; First, determine end of headline (EOH), end of subtree or item
6843 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6844 (save-excursion
6845 (if (org-at-item-p)
6846 (progn
6847 (beginning-of-line)
6848 (setq struct (org-list-struct))
6849 (setq eoh (point-at-eol))
6850 (setq eos (org-list-get-item-end-before-blank (point) struct))
6851 (setq has-children (org-list-has-child-p (point) struct)))
6852 (org-back-to-heading)
6853 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6854 (setq eos (save-excursion (org-end-of-subtree t t)
6855 (when (bolp) (backward-char)) (point)))
6856 (setq has-children
6857 (or (save-excursion
6858 (let ((level (funcall outline-level)))
6859 (outline-next-heading)
6860 (and (org-at-heading-p t)
6861 (> (funcall outline-level) level))))
6862 (save-excursion
6863 (org-list-search-forward (org-item-beginning-re) eos t)))))
6864 ;; Determine end invisible part of buffer (EOL)
6865 (beginning-of-line 2)
6866 ;; XEmacs doesn't have `next-single-char-property-change'
6867 (if (featurep 'xemacs)
6868 (while (and (not (eobp)) ;; this is like `next-line'
6869 (get-char-property (1- (point)) 'invisible))
6870 (beginning-of-line 2))
6871 (while (and (not (eobp)) ;; this is like `next-line'
6872 (get-char-property (1- (point)) 'invisible))
6873 (goto-char (next-single-char-property-change (point) 'invisible))
6874 (and (eolp) (beginning-of-line 2))))
6875 (setq eol (point)))
6876 ;; Find out what to do next and set `this-command'
6877 (cond
6878 ((= eos eoh)
6879 ;; Nothing is hidden behind this heading
6880 (unless (org-before-first-heading-p)
6881 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6882 (org-unlogged-message "EMPTY ENTRY")
6883 (setq org-cycle-subtree-status nil)
6884 (save-excursion
6885 (goto-char eos)
6886 (outline-next-heading)
6887 (if (outline-invisible-p) (org-flag-heading nil))))
6888 ((and (or (>= eol eos)
6889 (not (string-match "\\S-" (buffer-substring eol eos))))
6890 (or has-children
6891 (not (setq children-skipped
6892 org-cycle-skip-children-state-if-no-children))))
6893 ;; Entire subtree is hidden in one line: children view
6894 (unless (org-before-first-heading-p)
6895 (run-hook-with-args 'org-pre-cycle-hook 'children))
6896 (if (org-at-item-p)
6897 (org-list-set-item-visibility (point-at-bol) struct 'children)
6898 (org-show-entry)
6899 (org-with-limited-levels (show-children))
6900 ;; FIXME: This slows down the func way too much.
6901 ;; How keep drawers hidden in subtree anyway?
6902 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6903 ;; (org-cycle-hide-drawers 'subtree))
6905 ;; Fold every list in subtree to top-level items.
6906 (when (eq org-cycle-include-plain-lists 'integrate)
6907 (save-excursion
6908 (org-back-to-heading)
6909 (while (org-list-search-forward (org-item-beginning-re) eos t)
6910 (beginning-of-line 1)
6911 (let* ((struct (org-list-struct))
6912 (prevs (org-list-prevs-alist struct))
6913 (end (org-list-get-bottom-point struct)))
6914 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6915 (org-list-get-all-items (point) struct prevs))
6916 (goto-char (if (< end eos) end eos)))))))
6917 (org-unlogged-message "CHILDREN")
6918 (save-excursion
6919 (goto-char eos)
6920 (outline-next-heading)
6921 (if (outline-invisible-p) (org-flag-heading nil)))
6922 (setq org-cycle-subtree-status 'children)
6923 (unless (org-before-first-heading-p)
6924 (run-hook-with-args 'org-cycle-hook 'children)))
6925 ((or children-skipped
6926 (and (eq last-command this-command)
6927 (eq org-cycle-subtree-status 'children)))
6928 ;; We just showed the children, or no children are there,
6929 ;; now show everything.
6930 (unless (org-before-first-heading-p)
6931 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6932 (outline-flag-region eoh eos nil)
6933 (org-unlogged-message
6934 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6935 (setq org-cycle-subtree-status 'subtree)
6936 (unless (org-before-first-heading-p)
6937 (run-hook-with-args 'org-cycle-hook 'subtree)))
6939 ;; Default action: hide the subtree.
6940 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6941 (outline-flag-region eoh eos t)
6942 (org-unlogged-message "FOLDED")
6943 (setq org-cycle-subtree-status 'folded)
6944 (unless (org-before-first-heading-p)
6945 (run-hook-with-args 'org-cycle-hook 'folded))))))
6947 ;;;###autoload
6948 (defun org-global-cycle (&optional arg)
6949 "Cycle the global visibility. For details see `org-cycle'.
6950 With \\[universal-argument] prefix arg, switch to startup visibility.
6951 With a numeric prefix, show all headlines up to that level."
6952 (interactive "P")
6953 (let ((org-cycle-include-plain-lists
6954 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6955 (cond
6956 ((integerp arg)
6957 (show-all)
6958 (hide-sublevels arg)
6959 (setq org-cycle-global-status 'contents))
6960 ((equal arg '(4))
6961 (org-set-startup-visibility)
6962 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6964 (org-cycle '(4))))))
6966 (defun org-set-startup-visibility ()
6967 "Set the visibility required by startup options and properties."
6968 (cond
6969 ((eq org-startup-folded t)
6970 (org-overview))
6971 ((eq org-startup-folded 'content)
6972 (org-content))
6973 ((or (eq org-startup-folded 'showeverything)
6974 (eq org-startup-folded nil))
6975 (show-all)))
6976 (unless (eq org-startup-folded 'showeverything)
6977 (if org-hide-block-startup (org-hide-block-all))
6978 (org-set-visibility-according-to-property 'no-cleanup)
6979 (org-cycle-hide-archived-subtrees 'all)
6980 (org-cycle-hide-drawers 'all)
6981 (org-cycle-show-empty-lines t)))
6983 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6984 "Switch subtree visibilities according to :VISIBILITY: property."
6985 (interactive)
6986 (let (org-show-entry-below)
6987 (org-with-wide-buffer
6988 (goto-char (point-min))
6989 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6990 (if (not (org-at-property-p)) (outline-next-heading)
6991 (let ((state (match-string 3)))
6992 (save-excursion
6993 (org-back-to-heading t)
6994 (hide-subtree)
6995 (org-reveal)
6996 (cond
6997 ((equal state "folded")
6998 (hide-subtree))
6999 ((equal state "children")
7000 (org-show-hidden-entry)
7001 (show-children))
7002 ((equal state "content")
7003 (save-excursion
7004 (save-restriction
7005 (org-narrow-to-subtree)
7006 (org-content))))
7007 ((member state '("all" "showall"))
7008 (show-subtree)))))))
7009 (unless no-cleanup
7010 (org-cycle-hide-archived-subtrees 'all)
7011 (org-cycle-hide-drawers 'all)
7012 (org-cycle-show-empty-lines 'all)))))
7014 ;; This function uses outline-regexp instead of the more fundamental
7015 ;; org-outline-regexp so that org-cycle-global works outside of Org
7016 ;; buffers, where outline-regexp is needed.
7017 (defun org-overview ()
7018 "Switch to overview mode, showing only top-level headlines.
7019 This shows all headlines with a level equal or greater than the level
7020 of the first headline in the buffer. This is important, because if the
7021 first headline is not level one, then (hide-sublevels 1) gives confusing
7022 results."
7023 (interactive)
7024 (save-excursion
7025 (let ((level
7026 (save-excursion
7027 (goto-char (point-min))
7028 (if (re-search-forward (concat "^" outline-regexp) nil t)
7029 (progn
7030 (goto-char (match-beginning 0))
7031 (funcall outline-level))))))
7032 (and level (hide-sublevels level)))))
7034 (defun org-content (&optional arg)
7035 "Show all headlines in the buffer, like a table of contents.
7036 With numerical argument N, show content up to level N."
7037 (interactive "P")
7038 (org-overview)
7039 (save-excursion
7040 ;; Visit all headings and show their offspring
7041 (and (integerp arg) (org-overview))
7042 (goto-char (point-max))
7043 (catch 'exit
7044 (while (and (progn (condition-case nil
7045 (outline-previous-visible-heading 1)
7046 (error (goto-char (point-min))))
7048 (looking-at org-outline-regexp))
7049 (if (integerp arg)
7050 (show-children (1- arg))
7051 (show-branches))
7052 (if (bobp) (throw 'exit nil))))))
7054 (defun org-optimize-window-after-visibility-change (state)
7055 "Adjust the window after a change in outline visibility.
7056 This function is the default value of the hook `org-cycle-hook'."
7057 (when (get-buffer-window (current-buffer))
7058 (cond
7059 ((eq state 'content) nil)
7060 ((eq state 'all) nil)
7061 ((eq state 'folded) nil)
7062 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7063 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7065 (defun org-remove-empty-overlays-at (pos)
7066 "Remove outline overlays that do not contain non-white stuff."
7067 (mapc
7068 (lambda (o)
7069 (and (eq 'outline (overlay-get o 'invisible))
7070 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7071 (overlay-end o))))
7072 (delete-overlay o)))
7073 (overlays-at pos)))
7075 (defun org-clean-visibility-after-subtree-move ()
7076 "Fix visibility issues after moving a subtree."
7077 ;; First, find a reasonable region to look at:
7078 ;; Start two siblings above, end three below
7079 (let* ((beg (save-excursion
7080 (and (org-get-last-sibling)
7081 (org-get-last-sibling))
7082 (point)))
7083 (end (save-excursion
7084 (and (org-get-next-sibling)
7085 (org-get-next-sibling)
7086 (org-get-next-sibling))
7087 (if (org-at-heading-p)
7088 (point-at-eol)
7089 (point))))
7090 (level (looking-at "\\*+"))
7091 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7092 (save-excursion
7093 (save-restriction
7094 (narrow-to-region beg end)
7095 (when re
7096 ;; Properly fold already folded siblings
7097 (goto-char (point-min))
7098 (while (re-search-forward re nil t)
7099 (if (and (not (outline-invisible-p))
7100 (save-excursion
7101 (goto-char (point-at-eol)) (outline-invisible-p)))
7102 (hide-entry))))
7103 (org-cycle-show-empty-lines 'overview)
7104 (org-cycle-hide-drawers 'overview)))))
7106 (defun org-cycle-show-empty-lines (state)
7107 "Show empty lines above all visible headlines.
7108 The region to be covered depends on STATE when called through
7109 `org-cycle-hook'. Lisp program can use t for STATE to get the
7110 entire buffer covered. Note that an empty line is only shown if there
7111 are at least `org-cycle-separator-lines' empty lines before the headline."
7112 (when (not (= org-cycle-separator-lines 0))
7113 (save-excursion
7114 (let* ((n (abs org-cycle-separator-lines))
7115 (re (cond
7116 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7117 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7118 (t (let ((ns (number-to-string (- n 2))))
7119 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7120 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7121 beg end b e)
7122 (cond
7123 ((memq state '(overview contents t))
7124 (setq beg (point-min) end (point-max)))
7125 ((memq state '(children folded))
7126 (setq beg (point) end (progn (org-end-of-subtree t t)
7127 (beginning-of-line 2)
7128 (point)))))
7129 (when beg
7130 (goto-char beg)
7131 (while (re-search-forward re end t)
7132 (unless (get-char-property (match-end 1) 'invisible)
7133 (setq e (match-end 1))
7134 (if (< org-cycle-separator-lines 0)
7135 (setq b (save-excursion
7136 (goto-char (match-beginning 0))
7137 (org-back-over-empty-lines)
7138 (if (save-excursion
7139 (goto-char (max (point-min) (1- (point))))
7140 (org-at-heading-p))
7141 (1- (point))
7142 (point))))
7143 (setq b (match-beginning 1)))
7144 (outline-flag-region b e nil)))))))
7145 ;; Never hide empty lines at the end of the file.
7146 (save-excursion
7147 (goto-char (point-max))
7148 (outline-previous-heading)
7149 (outline-end-of-heading)
7150 (if (and (looking-at "[ \t\n]+")
7151 (= (match-end 0) (point-max)))
7152 (outline-flag-region (point) (match-end 0) nil))))
7154 (defun org-show-empty-lines-in-parent ()
7155 "Move to the parent and re-show empty lines before visible headlines."
7156 (save-excursion
7157 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7158 (org-cycle-show-empty-lines context))))
7160 (defun org-files-list ()
7161 "Return `org-agenda-files' list, plus all open org-mode files.
7162 This is useful for operations that need to scan all of a user's
7163 open and agenda-wise Org files."
7164 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7165 (dolist (buf (buffer-list))
7166 (with-current-buffer buf
7167 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7168 (let ((file (expand-file-name (buffer-file-name))))
7169 (unless (member file files)
7170 (push file files))))))
7171 files))
7173 (defsubst org-entry-beginning-position ()
7174 "Return the beginning position of the current entry."
7175 (save-excursion (outline-back-to-heading t) (point)))
7177 (defsubst org-entry-end-position ()
7178 "Return the end position of the current entry."
7179 (save-excursion (outline-next-heading) (point)))
7181 (defun org-cycle-hide-drawers (state &optional exceptions)
7182 "Re-hide all drawers after a visibility state change.
7183 When non-nil, optional argument EXCEPTIONS is a list of strings
7184 specifying which drawers should not be hidden."
7185 (when (and (derived-mode-p 'org-mode)
7186 (not (memq state '(overview folded contents))))
7187 (save-excursion
7188 (let* ((globalp (memq state '(contents all)))
7189 (beg (if globalp (point-min) (point)))
7190 (end (if globalp (point-max)
7191 (if (eq state 'children)
7192 (save-excursion (outline-next-heading) (point))
7193 (org-end-of-subtree t)))))
7194 (goto-char beg)
7195 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7196 (unless (member-ignore-case (match-string 1) exceptions)
7197 (let ((drawer (org-element-at-point)))
7198 (when (memq (org-element-type drawer) '(drawer property-drawer))
7199 (org-flag-drawer t drawer)
7200 ;; Make sure to skip drawer entirely or we might flag
7201 ;; it another time when matching its ending line with
7202 ;; `org-drawer-regexp'.
7203 (goto-char (org-element-property :end drawer))))))))))
7205 (defun org-cycle-hide-inline-tasks (state)
7206 "Re-hide inline tasks when switching to 'contents or 'children
7207 visibility state."
7208 (case state
7209 (contents
7210 (when (org-bound-and-true-p org-inlinetask-min-level)
7211 (hide-sublevels (1- org-inlinetask-min-level))))
7212 (children
7213 (when (featurep 'org-inlinetask)
7214 (save-excursion
7215 (while (and (outline-next-heading)
7216 (org-inlinetask-at-task-p))
7217 (org-inlinetask-toggle-visibility)
7218 (org-inlinetask-goto-end)))))))
7220 (defun org-flag-drawer (flag &optional element)
7221 "When FLAG is non-nil, hide the drawer we are at.
7222 Otherwise make it visible. When optional argument ELEMENT is
7223 a parsed drawer, as returned by `org-element-at-point', hide or
7224 show that drawer instead."
7225 (when (save-excursion
7226 (beginning-of-line)
7227 (org-looking-at-p org-drawer-regexp))
7228 (let ((drawer (or element (org-element-at-point))))
7229 (when (memq (org-element-type drawer) '(drawer property-drawer))
7230 (let ((post (org-element-property :post-affiliated drawer)))
7231 (save-excursion
7232 (outline-flag-region
7233 (progn (goto-char post) (line-end-position))
7234 (progn (goto-char (org-element-property :end drawer))
7235 (skip-chars-backward " \r\t\n")
7236 (line-end-position))
7237 flag))
7238 ;; When the drawer is hidden away, make sure point lies in
7239 ;; a visible part of the buffer.
7240 (when (and flag (> (line-beginning-position) post))
7241 (goto-char post)))))))
7243 (defun org-subtree-end-visible-p ()
7244 "Is the end of the current subtree visible?"
7245 (pos-visible-in-window-p
7246 (save-excursion (org-end-of-subtree t) (point))))
7248 (defun org-first-headline-recenter ()
7249 "Move cursor to the first headline and recenter the headline."
7250 (goto-char (point-min))
7251 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7252 (set-window-start (selected-window) (point-at-bol))))
7254 ;;; Saving and restoring visibility
7256 (defun org-outline-overlay-data (&optional use-markers)
7257 "Return a list of the locations of all outline overlays.
7258 These are overlays with the `invisible' property value `outline'.
7259 The return value is a list of cons cells, with start and stop
7260 positions for each overlay.
7261 If USE-MARKERS is set, return the positions as markers."
7262 (let (beg end)
7263 (save-excursion
7264 (save-restriction
7265 (widen)
7266 (delq nil
7267 (mapcar (lambda (o)
7268 (when (eq (overlay-get o 'invisible) 'outline)
7269 (setq beg (overlay-start o)
7270 end (overlay-end o))
7271 (and beg end (> end beg)
7272 (if use-markers
7273 (cons (copy-marker beg)
7274 (copy-marker end t))
7275 (cons beg end)))))
7276 (overlays-in (point-min) (point-max))))))))
7278 (defun org-set-outline-overlay-data (data)
7279 "Create visibility overlays for all positions in DATA.
7280 DATA should have been made by `org-outline-overlay-data'."
7281 (let (o)
7282 (save-excursion
7283 (save-restriction
7284 (widen)
7285 (show-all)
7286 (mapc (lambda (c)
7287 (outline-flag-region (car c) (cdr c) t))
7288 data)))))
7290 ;;; Folding of blocks
7292 (defvar org-hide-block-overlays nil
7293 "Overlays hiding blocks.")
7294 (make-variable-buffer-local 'org-hide-block-overlays)
7296 (defun org-block-map (function &optional start end)
7297 "Call FUNCTION at the head of all source blocks in the current buffer.
7298 Optional arguments START and END can be used to limit the range."
7299 (let ((start (or start (point-min)))
7300 (end (or end (point-max))))
7301 (save-excursion
7302 (goto-char start)
7303 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7304 (save-excursion
7305 (save-match-data
7306 (goto-char (match-beginning 0))
7307 (funcall function)))))))
7309 (defun org-hide-block-toggle-all ()
7310 "Toggle the visibility of all blocks in the current buffer."
7311 (org-block-map 'org-hide-block-toggle))
7313 (defun org-hide-block-all ()
7314 "Fold all blocks in the current buffer."
7315 (interactive)
7316 (org-show-block-all)
7317 (org-block-map 'org-hide-block-toggle-maybe))
7319 (defun org-show-block-all ()
7320 "Unfold all blocks in the current buffer."
7321 (interactive)
7322 (mapc 'delete-overlay org-hide-block-overlays)
7323 (setq org-hide-block-overlays nil))
7325 (defun org-hide-block-toggle-maybe ()
7326 "Toggle visibility of block at point.
7327 Unlike to `org-hide-block-toggle', this function does not throw
7328 an error. Return a non-nil value when toggling is successful."
7329 (interactive)
7330 (ignore-errors (org-hide-block-toggle)))
7332 (defun org-hide-block-toggle (&optional force)
7333 "Toggle the visibility of the current block.
7334 When optional argument FORCE is `off', make block visible. If it
7335 is non-nil, hide it unconditionally. Throw an error when not at
7336 a block. Return a non-nil value when toggling is successful."
7337 (interactive)
7338 (let ((element (org-element-at-point)))
7339 (unless (memq (org-element-type element)
7340 '(center-block comment-block dynamic-block example-block
7341 export-block quote-block special-block
7342 src-block verse-block))
7343 (user-error "Not at a block"))
7344 (let* ((start (save-excursion
7345 (goto-char (org-element-property :post-affiliated element))
7346 (line-end-position)))
7347 (end (save-excursion
7348 (goto-char (org-element-property :end element))
7349 (skip-chars-backward " \r\t\n")
7350 (line-end-position)))
7351 (overlays (overlays-at start)))
7352 (cond
7353 ;; Do nothing when not before or at the block opening line or
7354 ;; at the block closing line.
7355 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7356 ((and (not (eq force 'off))
7357 (not (memq t (mapcar
7358 (lambda (o)
7359 (eq (overlay-get o 'invisible) 'org-hide-block))
7360 overlays))))
7361 (let ((ov (make-overlay start end)))
7362 (overlay-put ov 'invisible 'org-hide-block)
7363 ;; Make the block accessible to `isearch'.
7364 (overlay-put
7365 ov 'isearch-open-invisible
7366 (lambda (ov)
7367 (when (memq ov org-hide-block-overlays)
7368 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7369 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7370 (delete-overlay ov))))
7371 (push ov org-hide-block-overlays)
7372 ;; When the block is hidden away, make sure point is left in
7373 ;; a visible part of the buffer.
7374 (when (> (line-beginning-position) start)
7375 (goto-char start)
7376 (beginning-of-line))
7377 ;; Signal successful toggling.
7379 ((or (not force) (eq force 'off))
7380 (dolist (ov overlays t)
7381 (when (memq ov org-hide-block-overlays)
7382 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7383 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7384 (delete-overlay ov))))))))
7386 ;; org-tab-after-check-for-cycling-hook
7387 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7388 ;; Remove overlays when changing major mode
7389 (add-hook 'org-mode-hook
7390 (lambda () (org-add-hook 'change-major-mode-hook
7391 'org-show-block-all 'append 'local)))
7393 ;;; Org-goto
7395 (defvar org-goto-window-configuration nil)
7396 (defvar org-goto-marker nil)
7397 (defvar org-goto-map)
7398 (defun org-goto-map ()
7399 "Set the keymap `org-goto'."
7400 (setq org-goto-map
7401 (let ((map (make-sparse-keymap)))
7402 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7403 mouse-drag-region universal-argument org-occur))
7404 cmd)
7405 (while (setq cmd (pop cmds))
7406 (substitute-key-definition cmd cmd map global-map)))
7407 (suppress-keymap map)
7408 (org-defkey map "\C-m" 'org-goto-ret)
7409 (org-defkey map [(return)] 'org-goto-ret)
7410 (org-defkey map [(left)] 'org-goto-left)
7411 (org-defkey map [(right)] 'org-goto-right)
7412 (org-defkey map [(control ?g)] 'org-goto-quit)
7413 (org-defkey map "\C-i" 'org-cycle)
7414 (org-defkey map [(tab)] 'org-cycle)
7415 (org-defkey map [(down)] 'outline-next-visible-heading)
7416 (org-defkey map [(up)] 'outline-previous-visible-heading)
7417 (if org-goto-auto-isearch
7418 (if (fboundp 'define-key-after)
7419 (define-key-after map [t] 'org-goto-local-auto-isearch)
7420 nil)
7421 (org-defkey map "q" 'org-goto-quit)
7422 (org-defkey map "n" 'outline-next-visible-heading)
7423 (org-defkey map "p" 'outline-previous-visible-heading)
7424 (org-defkey map "f" 'outline-forward-same-level)
7425 (org-defkey map "b" 'outline-backward-same-level)
7426 (org-defkey map "u" 'outline-up-heading))
7427 (org-defkey map "/" 'org-occur)
7428 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7429 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7430 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7431 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7432 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7433 map)))
7435 (defconst org-goto-help
7436 "Browse buffer copy, to find location or copy text.%s
7437 RET=jump to location C-g=quit and return to previous location
7438 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7440 (defvar org-goto-start-pos) ; dynamically scoped parameter
7442 (defun org-goto (&optional alternative-interface)
7443 "Look up a different location in the current file, keeping current visibility.
7445 When you want look-up or go to a different location in a
7446 document, the fastest way is often to fold the entire buffer and
7447 then dive into the tree. This method has the disadvantage, that
7448 the previous location will be folded, which may not be what you
7449 want.
7451 This command works around this by showing a copy of the current
7452 buffer in an indirect buffer, in overview mode. You can dive
7453 into the tree in that copy, use org-occur and incremental search
7454 to find a location. When pressing RET or `Q', the command
7455 returns to the original buffer in which the visibility is still
7456 unchanged. After RET it will also jump to the location selected
7457 in the indirect buffer and expose the headline hierarchy above.
7459 With a prefix argument, use the alternative interface: e.g. if
7460 `org-goto-interface' is 'outline use 'outline-path-completion."
7461 (interactive "P")
7462 (org-goto-map)
7463 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7464 (org-refile-use-outline-path t)
7465 (org-refile-target-verify-function nil)
7466 (interface
7467 (if (not alternative-interface)
7468 org-goto-interface
7469 (if (eq org-goto-interface 'outline)
7470 'outline-path-completion
7471 'outline)))
7472 (org-goto-start-pos (point))
7473 (selected-point
7474 (if (eq interface 'outline)
7475 (car (org-get-location (current-buffer) org-goto-help))
7476 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7477 (org-refile-check-position pa)
7478 (nth 3 pa)))))
7479 (if selected-point
7480 (progn
7481 (org-mark-ring-push org-goto-start-pos)
7482 (goto-char selected-point)
7483 (if (or (outline-invisible-p) (org-invisible-p2))
7484 (org-show-context 'org-goto)))
7485 (message "Quit"))))
7487 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7488 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7489 (defvar org-goto-local-auto-isearch-map) ; defined below
7491 (defun org-get-location (buf help)
7492 "Let the user select a location in the Org-mode buffer BUF.
7493 This function uses a recursive edit. It returns the selected position
7494 or nil."
7495 (org-no-popups
7496 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7497 (isearch-hide-immediately nil)
7498 (isearch-search-fun-function
7499 (lambda () 'org-goto-local-search-headings))
7500 (org-goto-selected-point org-goto-exit-command))
7501 (save-excursion
7502 (save-window-excursion
7503 (delete-other-windows)
7504 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7505 (org-pop-to-buffer-same-window
7506 (condition-case nil
7507 (make-indirect-buffer (current-buffer) "*org-goto*")
7508 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7509 (with-output-to-temp-buffer "*Org Help*"
7510 (princ (format help (if org-goto-auto-isearch
7511 " Just type for auto-isearch."
7512 " n/p/f/b/u to navigate, q to quit."))))
7513 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7514 (setq buffer-read-only nil)
7515 (let ((org-startup-truncated t)
7516 (org-startup-folded nil)
7517 (org-startup-align-all-tables nil))
7518 (org-mode)
7519 (org-overview))
7520 (setq buffer-read-only t)
7521 (if (and (boundp 'org-goto-start-pos)
7522 (integer-or-marker-p org-goto-start-pos))
7523 (let ((org-show-hierarchy-above t)
7524 (org-show-siblings t)
7525 (org-show-following-heading t))
7526 (goto-char org-goto-start-pos)
7527 (and (outline-invisible-p) (org-show-context)))
7528 (goto-char (point-min)))
7529 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7530 (message "Select location and press RET")
7531 (use-local-map org-goto-map)
7532 (recursive-edit)))
7533 (kill-buffer "*org-goto*")
7534 (cons org-goto-selected-point org-goto-exit-command))))
7536 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7537 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7538 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7539 (if (fboundp 'isearch-other-control-char)
7540 (progn
7541 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7542 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7543 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7544 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7545 (define-key org-goto-local-auto-isearch-map [return] nil))
7547 (defun org-goto-local-search-headings (string bound noerror)
7548 "Search and make sure that any matches are in headlines."
7549 (catch 'return
7550 (while (if isearch-forward
7551 (search-forward string bound noerror)
7552 (search-backward string bound noerror))
7553 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7554 (and (member :headline context)
7555 (not (member :tags context))))
7556 (throw 'return (point))))))
7558 (defun org-goto-local-auto-isearch ()
7559 "Start isearch."
7560 (interactive)
7561 (goto-char (point-min))
7562 (let ((keys (this-command-keys)))
7563 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7564 (isearch-mode t)
7565 (isearch-process-search-char (string-to-char keys)))))
7567 (defun org-goto-ret (&optional arg)
7568 "Finish `org-goto' by going to the new location."
7569 (interactive "P")
7570 (setq org-goto-selected-point (point)
7571 org-goto-exit-command 'return)
7572 (throw 'exit nil))
7574 (defun org-goto-left ()
7575 "Finish `org-goto' by going to the new location."
7576 (interactive)
7577 (if (org-at-heading-p)
7578 (progn
7579 (beginning-of-line 1)
7580 (setq org-goto-selected-point (point)
7581 org-goto-exit-command 'left)
7582 (throw 'exit nil))
7583 (user-error "Not on a heading")))
7585 (defun org-goto-right ()
7586 "Finish `org-goto' by going to the new location."
7587 (interactive)
7588 (if (org-at-heading-p)
7589 (progn
7590 (setq org-goto-selected-point (point)
7591 org-goto-exit-command 'right)
7592 (throw 'exit nil))
7593 (user-error "Not on a heading")))
7595 (defun org-goto-quit ()
7596 "Finish `org-goto' without cursor motion."
7597 (interactive)
7598 (setq org-goto-selected-point nil)
7599 (setq org-goto-exit-command 'quit)
7600 (throw 'exit nil))
7602 ;;; Indirect buffer display of subtrees
7604 (defvar org-indirect-dedicated-frame nil
7605 "This is the frame being used for indirect tree display.")
7606 (defvar org-last-indirect-buffer nil)
7608 (defun org-tree-to-indirect-buffer (&optional arg)
7609 "Create indirect buffer and narrow it to current subtree.
7610 With a numerical prefix ARG, go up to this level and then take that tree.
7611 If ARG is negative, go up that many levels.
7613 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7614 indirect buffer previously made with this command, to avoid proliferation of
7615 indirect buffers. However, when you call the command with a \
7616 \\[universal-argument] prefix, or
7617 when `org-indirect-buffer-display' is `new-frame', the last buffer
7618 is kept so that you can work with several indirect buffers at the same time.
7619 If `org-indirect-buffer-display' is `dedicated-frame', the \
7620 \\[universal-argument] prefix also
7621 requests that a new frame be made for the new buffer, so that the dedicated
7622 frame is not changed."
7623 (interactive "P")
7624 (let ((cbuf (current-buffer))
7625 (cwin (selected-window))
7626 (pos (point))
7627 beg end level heading ibuf)
7628 (save-excursion
7629 (org-back-to-heading t)
7630 (when (numberp arg)
7631 (setq level (org-outline-level))
7632 (if (< arg 0) (setq arg (+ level arg)))
7633 (while (> (setq level (org-outline-level)) arg)
7634 (org-up-heading-safe)))
7635 (setq beg (point)
7636 heading (org-get-heading))
7637 (org-end-of-subtree t t)
7638 (if (org-at-heading-p) (backward-char 1))
7639 (setq end (point)))
7640 (if (and (buffer-live-p org-last-indirect-buffer)
7641 (not (eq org-indirect-buffer-display 'new-frame))
7642 (not arg))
7643 (kill-buffer org-last-indirect-buffer))
7644 (setq ibuf (org-get-indirect-buffer cbuf heading)
7645 org-last-indirect-buffer ibuf)
7646 (cond
7647 ((or (eq org-indirect-buffer-display 'new-frame)
7648 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7649 (select-frame (make-frame))
7650 (delete-other-windows)
7651 (org-pop-to-buffer-same-window ibuf)
7652 (org-set-frame-title heading))
7653 ((eq org-indirect-buffer-display 'dedicated-frame)
7654 (raise-frame
7655 (select-frame (or (and org-indirect-dedicated-frame
7656 (frame-live-p org-indirect-dedicated-frame)
7657 org-indirect-dedicated-frame)
7658 (setq org-indirect-dedicated-frame (make-frame)))))
7659 (delete-other-windows)
7660 (org-pop-to-buffer-same-window ibuf)
7661 (org-set-frame-title (concat "Indirect: " heading)))
7662 ((eq org-indirect-buffer-display 'current-window)
7663 (org-pop-to-buffer-same-window ibuf))
7664 ((eq org-indirect-buffer-display 'other-window)
7665 (pop-to-buffer ibuf))
7666 (t (error "Invalid value")))
7667 (if (featurep 'xemacs)
7668 (save-excursion (org-mode) (turn-on-font-lock)))
7669 (narrow-to-region beg end)
7670 (show-all)
7671 (goto-char pos)
7672 (run-hook-with-args 'org-cycle-hook 'all)
7673 (and (window-live-p cwin) (select-window cwin))))
7675 (defun org-get-indirect-buffer (&optional buffer heading)
7676 (setq buffer (or buffer (current-buffer)))
7677 (let ((n 1) (base (buffer-name buffer)) bname)
7678 (while (buffer-live-p
7679 (get-buffer
7680 (setq bname
7681 (concat base "-"
7682 (if heading (concat heading "-" (number-to-string n))
7683 (number-to-string n))))))
7684 (setq n (1+ n)))
7685 (condition-case nil
7686 (make-indirect-buffer buffer bname 'clone)
7687 (error (make-indirect-buffer buffer bname)))))
7689 (defun org-set-frame-title (title)
7690 "Set the title of the current frame to the string TITLE."
7691 ;; FIXME: how to name a single frame in XEmacs???
7692 (unless (featurep 'xemacs)
7693 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7695 ;;;; Structure editing
7697 ;;; Inserting headlines
7699 (defun org-previous-line-empty-p (&optional next)
7700 "Is the previous line a blank line?
7701 When NEXT is non-nil, check the next line instead."
7702 (save-excursion
7703 (and (not (bobp))
7704 (or (beginning-of-line (if next 2 0)) t)
7705 (save-match-data
7706 (looking-at "[ \t]*$")))))
7708 (defun org-insert-heading (&optional arg invisible-ok)
7709 "Insert a new heading or an item with the same depth at point.
7711 If point is at the beginning of a heading or a list item, insert
7712 a new heading or a new item above the current one. If point is
7713 at the beginning of a normal line, turn the line into a heading.
7715 If point is in the middle of a headline or a list item, split the
7716 headline or the item and create a new headline/item with the text
7717 in the current line after point \(see `org-M-RET-may-split-line'
7718 on how to modify this behavior).
7720 With one universal prefix argument, set the user option
7721 `org-insert-heading-respect-content' to t for the duration of
7722 the command. This modifies the behavior described above in this
7723 ways: on list items and at the beginning of normal lines, force
7724 the insertion of a heading after the current subtree.
7726 With two universal prefix arguments, insert the heading at the
7727 end of the grandparent subtree. For example, if point is within
7728 a 2nd-level heading, then it will insert a 2nd-level heading at
7729 the end of the 1st-level parent heading.
7731 If point is at the beginning of a headline, insert a sibling
7732 before the current headline. If point is not at the beginning,
7733 split the line and create a new headline with the text in the
7734 current line after point \(see `org-M-RET-may-split-line' on how
7735 to modify this behavior).
7737 If point is at the beginning of a normal line, turn this line
7738 into a heading.
7740 When INVISIBLE-OK is set, stop at invisible headlines when going
7741 back. This is important for non-interactive uses of the
7742 command."
7743 (interactive "P")
7744 (if (org-called-interactively-p 'any) (org-reveal))
7745 (let ((itemp (org-in-item-p))
7746 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7747 (respect-content (or org-insert-heading-respect-content
7748 (equal arg '(4))))
7749 (initial-content "")
7750 (adjust-empty-lines t))
7752 (cond
7754 ((or (= (buffer-size) 0)
7755 (and (not (save-excursion
7756 (and (ignore-errors (org-back-to-heading invisible-ok))
7757 (org-at-heading-p))))
7758 (or arg (not itemp))))
7759 ;; At beginning of buffer or so high up that only a heading
7760 ;; makes sense.
7761 (cond ((and (bolp) (not respect-content)) (insert "* "))
7762 ((not respect-content)
7763 (unless may-split (end-of-line))
7764 (insert "\n* "))
7765 ((re-search-forward org-outline-regexp-bol nil t)
7766 (beginning-of-line)
7767 (insert "* \n")
7768 (backward-char))
7769 (t (goto-char (point-max))
7770 (insert "\n* ")))
7771 (run-hooks 'org-insert-heading-hook))
7773 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7776 ;; Maybe move at the end of the subtree
7777 (when (equal arg '(16))
7778 (org-up-heading-safe)
7779 (org-end-of-subtree t))
7780 ;; Insert a heading
7781 (save-restriction
7782 (widen)
7783 (let* ((level nil)
7784 (on-heading (org-at-heading-p))
7785 (empty-line-p (if on-heading
7786 (org-previous-line-empty-p)
7787 ;; We will decide later
7788 nil))
7789 ;; Get a level string to fall back on
7790 (fix-level
7791 (if (org-before-first-heading-p) "*"
7792 (save-excursion
7793 (org-back-to-heading t)
7794 (if (org-previous-line-empty-p) (setq empty-line-p t))
7795 (looking-at org-outline-regexp)
7796 (make-string (1- (length (match-string 0))) ?*))))
7797 (stars
7798 (save-excursion
7799 (condition-case nil
7800 (progn
7801 (org-back-to-heading invisible-ok)
7802 (when (and (not on-heading)
7803 (featurep 'org-inlinetask)
7804 (integerp org-inlinetask-min-level)
7805 (>= (length (match-string 0))
7806 org-inlinetask-min-level))
7807 ;; Find a heading level before the inline task
7808 (while (and (setq level (org-up-heading-safe))
7809 (>= level org-inlinetask-min-level)))
7810 (if (org-at-heading-p)
7811 (org-back-to-heading invisible-ok)
7812 (error "This should not happen")))
7813 (unless (and (save-excursion
7814 (save-match-data
7815 (org-backward-heading-same-level
7816 1 invisible-ok))
7817 (= (point) (match-beginning 0)))
7818 (not (org-previous-line-empty-p t)))
7819 (setq empty-line-p (or empty-line-p
7820 (org-previous-line-empty-p))))
7821 (match-string 0))
7822 (error (or fix-level "* ")))))
7823 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7824 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7825 pos hide-previous previous-pos)
7827 ;; If we insert after content, move there and clean up whitespace
7828 (when (and respect-content
7829 (not (org-looking-at-p org-outline-regexp-bol)))
7830 (if (not (org-before-first-heading-p))
7831 (org-end-of-subtree nil t)
7832 (re-search-forward org-outline-regexp-bol)
7833 (beginning-of-line 0))
7834 (skip-chars-backward " \r\n")
7835 (and (not (looking-back "^\\*+"))
7836 (looking-at "[ \t]+") (replace-match ""))
7837 (unless (eobp) (forward-char 1))
7838 (when (looking-at "^\\*")
7839 (unless (bobp) (backward-char 1))
7840 (insert "\n")))
7842 ;; If we are splitting, grab the text that should be moved to the new headline
7843 (when may-split
7844 (if (org-on-heading-p)
7845 ;; This is a heading, we split intelligently (keeping tags)
7846 (let ((pos (point)))
7847 (goto-char (point-at-bol))
7848 (unless (looking-at org-complex-heading-regexp)
7849 (error "This should not happen"))
7850 (when (and (match-beginning 4)
7851 (> pos (match-beginning 4))
7852 (< pos (match-end 4)))
7853 (setq initial-content (buffer-substring pos (match-end 4)))
7854 (goto-char pos)
7855 (delete-region (point) (match-end 4))
7856 (if (looking-at "[ \t]*$")
7857 (replace-match "")
7858 (insert (make-string (length initial-content) ?\ )))
7859 (setq initial-content (org-trim initial-content)))
7860 (goto-char pos))
7861 ;; a normal line
7862 (setq initial-content
7863 (org-trim (buffer-substring (point) (point-at-eol))))
7864 (delete-region (point) (point-at-eol))))
7866 ;; If we are at the beginning of the line, insert before it. Else after
7867 (cond
7868 ((and (bolp) (looking-at "[ \t]*$")))
7869 ((and (bolp) (not (looking-at "[ \t]*$")))
7870 (open-line 1))
7872 (goto-char (point-at-eol))
7873 (insert "\n")))
7875 ;; Insert the new heading
7876 (insert stars)
7877 (just-one-space)
7878 (insert initial-content)
7879 (when adjust-empty-lines
7880 (if (or (not blank)
7881 (and blank (not (org-previous-line-empty-p))))
7882 (org-N-empty-lines-before-current (if blank 1 0))))
7883 (run-hooks 'org-insert-heading-hook)))))))
7885 (defun org-N-empty-lines-before-current (N)
7886 "Make the number of empty lines before current exactly N.
7887 So this will delete or add empty lines."
7888 (save-excursion
7889 (beginning-of-line)
7890 (let ((p (point)))
7891 (skip-chars-backward " \r\t\n")
7892 (unless (bolp) (forward-line))
7893 (delete-region (point) p))
7894 (when (> N 0) (insert (make-string N ?\n)))))
7896 (defun org-get-heading (&optional no-tags no-todo)
7897 "Return the heading of the current entry, without the stars.
7898 When NO-TAGS is non-nil, don't include tags.
7899 When NO-TODO is non-nil, don't include TODO keywords."
7900 (save-excursion
7901 (org-back-to-heading t)
7902 (cond
7903 ((and no-tags no-todo)
7904 (looking-at org-complex-heading-regexp)
7905 (match-string 4))
7906 (no-tags
7907 (looking-at (concat org-outline-regexp
7908 "\\(.*?\\)"
7909 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7910 (match-string 1))
7911 (no-todo
7912 (looking-at org-todo-line-regexp)
7913 (match-string 3))
7914 (t (looking-at org-heading-regexp)
7915 (match-string 2)))))
7917 (defvar orgstruct-mode) ; defined below
7919 (defun org-heading-components ()
7920 "Return the components of the current heading.
7921 This is a list with the following elements:
7922 - the level as an integer
7923 - the reduced level, different if `org-odd-levels-only' is set.
7924 - the TODO keyword, or nil
7925 - the priority character, like ?A, or nil if no priority is given
7926 - the headline text itself, or the tags string if no headline text
7927 - the tags string, or nil."
7928 (save-excursion
7929 (org-back-to-heading t)
7930 (if (let (case-fold-search)
7931 (looking-at
7932 (if orgstruct-mode
7933 org-heading-regexp
7934 org-complex-heading-regexp)))
7935 (if orgstruct-mode
7936 (list (length (match-string 1))
7937 (org-reduced-level (length (match-string 1)))
7940 (match-string 2)
7941 nil)
7942 (list (length (match-string 1))
7943 (org-reduced-level (length (match-string 1)))
7944 (org-match-string-no-properties 2)
7945 (and (match-end 3) (aref (match-string 3) 2))
7946 (org-match-string-no-properties 4)
7947 (org-match-string-no-properties 5))))))
7949 (defun org-get-entry ()
7950 "Get the entry text, after heading, entire subtree."
7951 (save-excursion
7952 (org-back-to-heading t)
7953 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7955 (defun org-insert-heading-after-current ()
7956 "Insert a new heading with same level as current, after current subtree."
7957 (interactive)
7958 (org-back-to-heading)
7959 (org-insert-heading)
7960 (org-move-subtree-down)
7961 (end-of-line 1))
7963 (defun org-insert-heading-respect-content (&optional invisible-ok)
7964 "Insert heading with `org-insert-heading-respect-content' set to t."
7965 (interactive)
7966 (org-insert-heading '(4) invisible-ok))
7968 (defun org-insert-todo-heading-respect-content (&optional force-state)
7969 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7970 (interactive)
7971 (org-insert-todo-heading force-state '(4)))
7973 (defun org-insert-todo-heading (arg &optional force-heading)
7974 "Insert a new heading with the same level and TODO state as current heading.
7975 If the heading has no TODO state, or if the state is DONE, use the first
7976 state (TODO by default). Also with one prefix arg, force first state. With
7977 two prefix args, force inserting at the end of the parent subtree."
7978 (interactive "P")
7979 (when (or force-heading (not (org-insert-item 'checkbox)))
7980 (org-insert-heading (or (and (equal arg '(16)) '(16))
7981 force-heading))
7982 (save-excursion
7983 (org-back-to-heading)
7984 (outline-previous-heading)
7985 (looking-at org-todo-line-regexp))
7986 (let*
7987 ((new-mark-x
7988 (if (or (equal arg '(4))
7989 (not (match-beginning 2))
7990 (member (match-string 2) org-done-keywords))
7991 (car org-todo-keywords-1)
7992 (match-string 2)))
7993 (new-mark
7995 (run-hook-with-args-until-success
7996 'org-todo-get-default-hook new-mark-x nil)
7997 new-mark-x)))
7998 (beginning-of-line 1)
7999 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8000 (if org-treat-insert-todo-heading-as-state-change
8001 (org-todo new-mark)
8002 (insert new-mark " "))))
8003 (when org-provide-todo-statistics
8004 (org-update-parent-todo-statistics))))
8006 (defun org-insert-subheading (arg)
8007 "Insert a new subheading and demote it.
8008 Works for outline headings and for plain lists alike."
8009 (interactive "P")
8010 (org-insert-heading arg)
8011 (cond
8012 ((org-at-heading-p) (org-do-demote))
8013 ((org-at-item-p) (org-indent-item))))
8015 (defun org-insert-todo-subheading (arg)
8016 "Insert a new subheading with TODO keyword or checkbox and demote it.
8017 Works for outline headings and for plain lists alike."
8018 (interactive "P")
8019 (org-insert-todo-heading arg)
8020 (cond
8021 ((org-at-heading-p) (org-do-demote))
8022 ((org-at-item-p) (org-indent-item))))
8024 ;;; Promotion and Demotion
8026 (defvar org-after-demote-entry-hook nil
8027 "Hook run after an entry has been demoted.
8028 The cursor will be at the beginning of the entry.
8029 When a subtree is being demoted, the hook will be called for each node.")
8031 (defvar org-after-promote-entry-hook nil
8032 "Hook run after an entry has been promoted.
8033 The cursor will be at the beginning of the entry.
8034 When a subtree is being promoted, the hook will be called for each node.")
8036 (defun org-promote-subtree ()
8037 "Promote the entire subtree.
8038 See also `org-promote'."
8039 (interactive)
8040 (save-excursion
8041 (org-with-limited-levels (org-map-tree 'org-promote)))
8042 (org-fix-position-after-promote))
8044 (defun org-demote-subtree ()
8045 "Demote the entire subtree. See `org-demote'.
8046 See also `org-promote'."
8047 (interactive)
8048 (save-excursion
8049 (org-with-limited-levels (org-map-tree 'org-demote)))
8050 (org-fix-position-after-promote))
8053 (defun org-do-promote ()
8054 "Promote the current heading higher up the tree.
8055 If the region is active in `transient-mark-mode', promote all headings
8056 in the region."
8057 (interactive)
8058 (save-excursion
8059 (if (org-region-active-p)
8060 (org-map-region 'org-promote (region-beginning) (region-end))
8061 (org-promote)))
8062 (org-fix-position-after-promote))
8064 (defun org-do-demote ()
8065 "Demote the current heading lower down the tree.
8066 If the region is active in `transient-mark-mode', demote all headings
8067 in the region."
8068 (interactive)
8069 (save-excursion
8070 (if (org-region-active-p)
8071 (org-map-region 'org-demote (region-beginning) (region-end))
8072 (org-demote)))
8073 (org-fix-position-after-promote))
8075 (defun org-fix-position-after-promote ()
8076 "Make sure that after pro/demotion cursor position is right."
8077 (let ((pos (point)))
8078 (when (save-excursion
8079 (beginning-of-line 1)
8080 (looking-at org-todo-line-regexp)
8081 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8082 (cond ((eobp) (insert " "))
8083 ((eolp) (insert " "))
8084 ((equal (char-after) ?\ ) (forward-char 1))))))
8086 (defun org-current-level ()
8087 "Return the level of the current entry, or nil if before the first headline.
8088 The level is the number of stars at the beginning of the
8089 headline. Use `org-reduced-level' to remove the effect of
8090 `org-odd-levels'. Unlike to `org-outline-level', this function
8091 ignores inlinetasks."
8092 (let ((level (org-with-limited-levels (org-outline-level))))
8093 (and (> level 0) level)))
8095 (defun org-get-previous-line-level ()
8096 "Return the outline depth of the last headline before the current line.
8097 Returns 0 for the first headline in the buffer, and nil if before the
8098 first headline."
8099 (and (org-current-level)
8100 (or (and (/= (line-beginning-position) (point-min))
8101 (save-excursion (beginning-of-line 0) (org-current-level)))
8102 0)))
8104 (defun org-reduced-level (l)
8105 "Compute the effective level of a heading.
8106 This takes into account the setting of `org-odd-levels-only'."
8107 (cond
8108 ((zerop l) 0)
8109 (org-odd-levels-only (1+ (floor (/ l 2))))
8110 (t l)))
8112 (defun org-level-increment ()
8113 "Return the number of stars that will be added or removed at a
8114 time to headlines when structure editing, based on the value of
8115 `org-odd-levels-only'."
8116 (if org-odd-levels-only 2 1))
8118 (defun org-get-valid-level (level &optional change)
8119 "Rectify a level change under the influence of `org-odd-levels-only'
8120 LEVEL is a current level, CHANGE is by how much the level should be
8121 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8122 even level numbers will become the next higher odd number."
8123 (if org-odd-levels-only
8124 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8125 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8126 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8127 (max 1 (+ level (or change 0)))))
8129 (if (boundp 'define-obsolete-function-alias)
8130 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8131 (define-obsolete-function-alias 'org-get-legal-level
8132 'org-get-valid-level)
8133 (define-obsolete-function-alias 'org-get-legal-level
8134 'org-get-valid-level "23.1")))
8136 (defun org-promote ()
8137 "Promote the current heading higher up the tree."
8138 (org-with-wide-buffer
8139 (org-back-to-heading t)
8140 (let* ((after-change-functions (remq 'flyspell-after-change-function
8141 after-change-functions))
8142 (level (save-match-data (funcall outline-level)))
8143 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8144 (diff (abs (- level (length up-head) -1))))
8145 (cond
8146 ((and (= level 1) org-allow-promoting-top-level-subtree)
8147 (replace-match "# " nil t))
8148 ((= level 1)
8149 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8150 (t (replace-match up-head nil t)))
8151 (unless (= level 1)
8152 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8153 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8154 (run-hooks 'org-after-promote-entry-hook))))
8156 (defun org-demote ()
8157 "Demote the current heading lower down the tree."
8158 (org-with-wide-buffer
8159 (org-back-to-heading t)
8160 (let* ((after-change-functions (remq 'flyspell-after-change-function
8161 after-change-functions))
8162 (level (save-match-data (funcall outline-level)))
8163 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8164 (diff (abs (- level (length down-head) -1))))
8165 (replace-match down-head nil t)
8166 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8167 (when org-adapt-indentation (org-fixup-indentation diff))
8168 (run-hooks 'org-after-demote-entry-hook))))
8170 (defun org-cycle-level ()
8171 "Cycle the level of an empty headline through possible states.
8172 This goes first to child, then to parent, level, then up the hierarchy.
8173 After top level, it switches back to sibling level."
8174 (interactive)
8175 (let ((org-adapt-indentation nil))
8176 (when (org-point-at-end-of-empty-headline)
8177 (setq this-command 'org-cycle-level) ; Only needed for caching
8178 (let ((cur-level (org-current-level))
8179 (prev-level (org-get-previous-line-level)))
8180 (cond
8181 ;; If first headline in file, promote to top-level.
8182 ((= prev-level 0)
8183 (loop repeat (/ (- cur-level 1) (org-level-increment))
8184 do (org-do-promote)))
8185 ;; If same level as prev, demote one.
8186 ((= prev-level cur-level)
8187 (org-do-demote))
8188 ;; If parent is top-level, promote to top level if not already.
8189 ((= prev-level 1)
8190 (loop repeat (/ (- cur-level 1) (org-level-increment))
8191 do (org-do-promote)))
8192 ;; If top-level, return to prev-level.
8193 ((= cur-level 1)
8194 (loop repeat (/ (- prev-level 1) (org-level-increment))
8195 do (org-do-demote)))
8196 ;; If less than prev-level, promote one.
8197 ((< cur-level prev-level)
8198 (org-do-promote))
8199 ;; If deeper than prev-level, promote until higher than
8200 ;; prev-level.
8201 ((> cur-level prev-level)
8202 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8203 do (org-do-promote))))
8204 t))))
8206 (defun org-map-tree (fun)
8207 "Call FUN for every heading underneath the current one."
8208 (org-back-to-heading)
8209 (let ((level (funcall outline-level)))
8210 (save-excursion
8211 (funcall fun)
8212 (while (and (progn
8213 (outline-next-heading)
8214 (> (funcall outline-level) level))
8215 (not (eobp)))
8216 (funcall fun)))))
8218 (defun org-map-region (fun beg end)
8219 "Call FUN for every heading between BEG and END."
8220 (let ((org-ignore-region t))
8221 (save-excursion
8222 (setq end (copy-marker end))
8223 (goto-char beg)
8224 (if (and (re-search-forward org-outline-regexp-bol nil t)
8225 (< (point) end))
8226 (funcall fun))
8227 (while (and (progn
8228 (outline-next-heading)
8229 (< (point) end))
8230 (not (eobp)))
8231 (funcall fun)))))
8233 (defun org-fixup-indentation (diff)
8234 "Change the indentation in the current entry by DIFF.
8236 DIFF is an integer. Indentation is done according to the
8237 following rules:
8239 - Planning information and property drawers are always indented
8240 according to the new level of the headline;
8242 - Footnote definitions and their contents are ignored;
8244 - Inlinetasks' boundaries are not shifted;
8246 - Empty lines are ignored;
8248 - Other lines' indentation are shifted by DIFF columns, unless
8249 it would introduce a structural change in the document, in
8250 which case no shifting is done at all.
8252 Assume point is at a heading or an inlinetask beginning."
8253 (org-with-wide-buffer
8254 (narrow-to-region (line-beginning-position)
8255 (save-excursion
8256 (if (org-with-limited-levels (org-at-heading-p))
8257 (org-with-limited-levels (outline-next-heading))
8258 (org-inlinetask-goto-end))
8259 (point)))
8260 (forward-line)
8261 ;; Indent properly planning info and property drawer.
8262 (when (org-looking-at-p org-planning-line-re)
8263 (org-indent-line)
8264 (forward-line))
8265 (when (looking-at org-property-drawer-re)
8266 (goto-char (match-end 0))
8267 (forward-line)
8268 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8269 (catch 'no-shift
8270 (when (zerop diff) (throw 'no-shift nil))
8271 ;; If DIFF is negative, first check if a shift is possible at all
8272 ;; (e.g., it doesn't break structure). This can only happen if
8273 ;; some contents are not properly indented.
8274 (let ((case-fold-search t))
8275 (when (< diff 0)
8276 (let ((diff (- diff))
8277 (forbidden-re (concat org-outline-regexp
8278 "\\|"
8279 (substring org-footnote-definition-re 1))))
8280 (save-excursion
8281 (while (not (eobp))
8282 (cond
8283 ((org-looking-at-p "[ \t]*$") (forward-line))
8284 ((and (org-looking-at-p org-footnote-definition-re)
8285 (let ((e (org-element-at-point)))
8286 (and (eq (org-element-type e) 'footnote-definition)
8287 (goto-char (org-element-property :end e))))))
8288 ((org-looking-at-p org-outline-regexp) (forward-line))
8289 ;; Give up if shifting would move before column 0 or
8290 ;; if it would introduce a headline or a footnote
8291 ;; definition.
8293 (skip-chars-forward " \t")
8294 (let ((ind (current-column)))
8295 (when (or (< ind diff)
8296 (and (= ind diff) (org-looking-at-p forbidden-re)))
8297 (throw 'no-shift nil)))
8298 ;; Ignore contents of example blocks and source
8299 ;; blocks if their indentation is meant to be
8300 ;; preserved. Jump to block's closing line.
8301 (beginning-of-line)
8302 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8303 (let ((e (org-element-at-point)))
8304 (and (memq (org-element-type e)
8305 '(example-block src-block))
8306 (or org-src-preserve-indentation
8307 (org-element-property :preserve-indent e))
8308 (goto-char (org-element-property :end e))
8309 (progn (skip-chars-backward " \r\t\n")
8310 (beginning-of-line)
8311 t))))
8312 (forward-line))))))))
8313 ;; Shift lines but footnote definitions, inlinetasks boundaries
8314 ;; by DIFF. Also skip contents of source or example blocks
8315 ;; when indentation is meant to be preserved.
8316 (while (not (eobp))
8317 (cond
8318 ((and (org-looking-at-p org-footnote-definition-re)
8319 (let ((e (org-element-at-point)))
8320 (and (eq (org-element-type e) 'footnote-definition)
8321 (goto-char (org-element-property :end e))))))
8322 ((org-looking-at-p org-outline-regexp) (forward-line))
8323 ((org-looking-at-p "[ \t]*$") (forward-line))
8325 (org-indent-line-to (+ (org-get-indentation) diff))
8326 (beginning-of-line)
8327 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8328 (let ((e (org-element-at-point)))
8329 (and (memq (org-element-type e)
8330 '(example-block src-block))
8331 (or org-src-preserve-indentation
8332 (org-element-property :preserve-indent e))
8333 (goto-char (org-element-property :end e))
8334 (progn (skip-chars-backward " \r\t\n")
8335 (beginning-of-line)
8336 t))))
8337 (forward-line)))))))))
8339 (defun org-convert-to-odd-levels ()
8340 "Convert an org-mode file with all levels allowed to one with odd levels.
8341 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8342 level 5 etc."
8343 (interactive)
8344 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8345 (let ((outline-level 'org-outline-level)
8346 (org-odd-levels-only nil) n)
8347 (save-excursion
8348 (goto-char (point-min))
8349 (while (re-search-forward "^\\*\\*+ " nil t)
8350 (setq n (- (length (match-string 0)) 2))
8351 (while (>= (setq n (1- n)) 0)
8352 (org-demote))
8353 (end-of-line 1))))))
8355 (defun org-convert-to-oddeven-levels ()
8356 "Convert an org-mode file with only odd levels to one with odd/even levels.
8357 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8358 file contains a section with an even level, conversion would
8359 destroy the structure of the file. An error is signaled in this
8360 case."
8361 (interactive)
8362 (goto-char (point-min))
8363 ;; First check if there are no even levels
8364 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8365 (org-show-context t)
8366 (error "Not all levels are odd in this file. Conversion not possible"))
8367 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8368 (let ((outline-regexp org-outline-regexp)
8369 (outline-level 'org-outline-level)
8370 (org-odd-levels-only nil) n)
8371 (save-excursion
8372 (goto-char (point-min))
8373 (while (re-search-forward "^\\*\\*+ " nil t)
8374 (setq n (/ (1- (length (match-string 0))) 2))
8375 (while (>= (setq n (1- n)) 0)
8376 (org-promote))
8377 (end-of-line 1))))))
8379 (defun org-tr-level (n)
8380 "Make N odd if required."
8381 (if org-odd-levels-only (1+ (/ n 2)) n))
8383 ;;; Vertical tree motion, cutting and pasting of subtrees
8385 (defun org-move-subtree-up (&optional arg)
8386 "Move the current subtree up past ARG headlines of the same level."
8387 (interactive "p")
8388 (org-move-subtree-down (- (prefix-numeric-value arg))))
8390 (defun org-move-subtree-down (&optional arg)
8391 "Move the current subtree down past ARG headlines of the same level."
8392 (interactive "p")
8393 (setq arg (prefix-numeric-value arg))
8394 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8395 'org-get-last-sibling))
8396 (ins-point (make-marker))
8397 (cnt (abs arg))
8398 (col (current-column))
8399 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8400 ;; Select the tree
8401 (org-back-to-heading)
8402 (setq beg0 (point))
8403 (save-excursion
8404 (setq ne-beg (org-back-over-empty-lines))
8405 (setq beg (point)))
8406 (save-match-data
8407 (save-excursion (outline-end-of-heading)
8408 (setq folded (outline-invisible-p)))
8409 (progn (org-end-of-subtree nil t)
8410 (unless (eobp) (backward-char))))
8411 (outline-next-heading)
8412 (setq ne-end (org-back-over-empty-lines))
8413 (setq end (point))
8414 (goto-char beg0)
8415 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8416 ;; include less whitespace
8417 (save-excursion
8418 (goto-char beg)
8419 (forward-line (- ne-beg ne-end))
8420 (setq beg (point))))
8421 ;; Find insertion point, with error handling
8422 (while (> cnt 0)
8423 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8424 (progn (goto-char beg0)
8425 (user-error "Cannot move past superior level or buffer limit")))
8426 (setq cnt (1- cnt)))
8427 (if (> arg 0)
8428 ;; Moving forward - still need to move over subtree
8429 (progn (org-end-of-subtree t t)
8430 (save-excursion
8431 (org-back-over-empty-lines)
8432 (or (bolp) (newline)))))
8433 (setq ne-ins (org-back-over-empty-lines))
8434 (move-marker ins-point (point))
8435 (setq txt (buffer-substring beg end))
8436 (org-save-markers-in-region beg end)
8437 (delete-region beg end)
8438 (org-remove-empty-overlays-at beg)
8439 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8440 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8441 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8442 (let ((bbb (point)))
8443 (insert-before-markers txt)
8444 (org-reinstall-markers-in-region bbb)
8445 (move-marker ins-point bbb))
8446 (or (bolp) (insert "\n"))
8447 (setq ins-end (point))
8448 (goto-char ins-point)
8449 (org-skip-whitespace)
8450 (when (and (< arg 0)
8451 (org-first-sibling-p)
8452 (> ne-ins ne-beg))
8453 ;; Move whitespace back to beginning
8454 (save-excursion
8455 (goto-char ins-end)
8456 (let ((kill-whole-line t))
8457 (kill-line (- ne-ins ne-beg)) (point)))
8458 (insert (make-string (- ne-ins ne-beg) ?\n)))
8459 (move-marker ins-point nil)
8460 (if folded
8461 (hide-subtree)
8462 (org-show-entry)
8463 (show-children)
8464 (org-cycle-hide-drawers 'children))
8465 (org-clean-visibility-after-subtree-move)
8466 ;; move back to the initial column we were at
8467 (move-to-column col)))
8469 (defvar org-subtree-clip ""
8470 "Clipboard for cut and paste of subtrees.
8471 This is actually only a copy of the kill, because we use the normal kill
8472 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8474 (defvar org-subtree-clip-folded nil
8475 "Was the last copied subtree folded?
8476 This is used to fold the tree back after pasting.")
8478 (defun org-cut-subtree (&optional n)
8479 "Cut the current subtree into the clipboard.
8480 With prefix arg N, cut this many sequential subtrees.
8481 This is a short-hand for marking the subtree and then cutting it."
8482 (interactive "p")
8483 (org-copy-subtree n 'cut))
8485 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8486 "Copy the current subtree it in the clipboard.
8487 With prefix arg N, copy this many sequential subtrees.
8488 This is a short-hand for marking the subtree and then copying it.
8489 If CUT is non-nil, actually cut the subtree.
8490 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8491 of some markers in the region, even if CUT is non-nil. This is
8492 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8493 (interactive "p")
8494 (let (beg end folded (beg0 (point)))
8495 (if (org-called-interactively-p 'any)
8496 (org-back-to-heading nil) ; take what looks like a subtree
8497 (org-back-to-heading t)) ; take what is really there
8498 (setq beg (point))
8499 (skip-chars-forward " \t\r\n")
8500 (save-match-data
8501 (if nosubtrees
8502 (outline-next-heading)
8503 (save-excursion (outline-end-of-heading)
8504 (setq folded (outline-invisible-p)))
8505 (ignore-errors (org-forward-heading-same-level (1- n) t))
8506 (org-end-of-subtree t t)))
8507 (setq end (point))
8508 (goto-char beg0)
8509 (when (> end beg)
8510 (setq org-subtree-clip-folded folded)
8511 (when (or cut force-store-markers)
8512 (org-save-markers-in-region beg end))
8513 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8514 (setq org-subtree-clip (current-kill 0))
8515 (message "%s: Subtree(s) with %d characters"
8516 (if cut "Cut" "Copied")
8517 (length org-subtree-clip)))))
8519 (defun org-paste-subtree (&optional level tree for-yank remove)
8520 "Paste the clipboard as a subtree, with modification of headline level.
8521 The entire subtree is promoted or demoted in order to match a new headline
8522 level.
8524 If the cursor is at the beginning of a headline, the same level as
8525 that headline is used to paste the tree.
8527 If not, the new level is derived from the *visible* headings
8528 before and after the insertion point, and taken to be the inferior headline
8529 level of the two. So if the previous visible heading is level 3 and the
8530 next is level 4 (or vice versa), level 4 will be used for insertion.
8531 This makes sure that the subtree remains an independent subtree and does
8532 not swallow low level entries.
8534 You can also force a different level, either by using a numeric prefix
8535 argument, or by inserting the heading marker by hand. For example, if the
8536 cursor is after \"*****\", then the tree will be shifted to level 5.
8538 If optional TREE is given, use this text instead of the kill ring.
8540 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8541 move back over whitespace before inserting, and move point to the end of
8542 the inserted text when done.
8544 When REMOVE is non-nil, remove the subtree from the clipboard."
8545 (interactive "P")
8546 (setq tree (or tree (and kill-ring (current-kill 0))))
8547 (unless (org-kill-is-subtree-p tree)
8548 (user-error "%s"
8549 (substitute-command-keys
8550 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8551 (org-with-limited-levels
8552 (let* ((visp (not (outline-invisible-p)))
8553 (txt tree)
8554 (^re_ "\\(\\*+\\)[ \t]*")
8555 (old-level (if (string-match org-outline-regexp-bol txt)
8556 (- (match-end 0) (match-beginning 0) 1)
8557 -1))
8558 (force-level (cond (level (prefix-numeric-value level))
8559 ((and (looking-at "[ \t]*$")
8560 (string-match
8561 "^\\*+$" (buffer-substring
8562 (point-at-bol) (point))))
8563 (- (match-end 0) (match-beginning 0)))
8564 ((and (bolp)
8565 (looking-at org-outline-regexp))
8566 (- (match-end 0) (point) 1))))
8567 (previous-level (save-excursion
8568 (condition-case nil
8569 (progn
8570 (outline-previous-visible-heading 1)
8571 (if (looking-at ^re_)
8572 (- (match-end 0) (match-beginning 0) 1)
8574 (error 1))))
8575 (next-level (save-excursion
8576 (condition-case nil
8577 (progn
8578 (or (looking-at org-outline-regexp)
8579 (outline-next-visible-heading 1))
8580 (if (looking-at ^re_)
8581 (- (match-end 0) (match-beginning 0) 1)
8583 (error 1))))
8584 (new-level (or force-level (max previous-level next-level)))
8585 (shift (if (or (= old-level -1)
8586 (= new-level -1)
8587 (= old-level new-level))
8589 (- new-level old-level)))
8590 (delta (if (> shift 0) -1 1))
8591 (func (if (> shift 0) 'org-demote 'org-promote))
8592 (org-odd-levels-only nil)
8593 beg end newend)
8594 ;; Remove the forced level indicator
8595 (if force-level
8596 (delete-region (point-at-bol) (point)))
8597 ;; Paste
8598 (beginning-of-line (if (bolp) 1 2))
8599 (setq beg (point))
8600 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8601 (insert-before-markers txt)
8602 (unless (string-match "\n\\'" txt) (insert "\n"))
8603 (setq newend (point))
8604 (org-reinstall-markers-in-region beg)
8605 (setq end (point))
8606 (goto-char beg)
8607 (skip-chars-forward " \t\n\r")
8608 (setq beg (point))
8609 (if (and (outline-invisible-p) visp)
8610 (save-excursion (outline-show-heading)))
8611 ;; Shift if necessary
8612 (unless (= shift 0)
8613 (save-restriction
8614 (narrow-to-region beg end)
8615 (while (not (= shift 0))
8616 (org-map-region func (point-min) (point-max))
8617 (setq shift (+ delta shift)))
8618 (goto-char (point-min))
8619 (setq newend (point-max))))
8620 (when (or (org-called-interactively-p 'interactive) for-yank)
8621 (message "Clipboard pasted as level %d subtree" new-level))
8622 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8623 kill-ring
8624 (eq org-subtree-clip (current-kill 0))
8625 org-subtree-clip-folded)
8626 ;; The tree was folded before it was killed/copied
8627 (hide-subtree))
8628 (and for-yank (goto-char newend))
8629 (and remove (setq kill-ring (cdr kill-ring))))))
8631 (defun org-kill-is-subtree-p (&optional txt)
8632 "Check if the current kill is an outline subtree, or a set of trees.
8633 Returns nil if kill does not start with a headline, or if the first
8634 headline level is not the largest headline level in the tree.
8635 So this will actually accept several entries of equal levels as well,
8636 which is OK for `org-paste-subtree'.
8637 If optional TXT is given, check this string instead of the current kill."
8638 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8639 (re (org-get-limited-outline-regexp))
8640 (^re (concat "^" re))
8641 (start-level (and kill
8642 (string-match
8643 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8644 kill)
8645 (- (match-end 2) (match-beginning 2) 1)))
8646 (start (1+ (or (match-beginning 2) -1))))
8647 (if (not start-level)
8648 (progn
8649 nil) ;; does not even start with a heading
8650 (catch 'exit
8651 (while (setq start (string-match ^re kill (1+ start)))
8652 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8653 (throw 'exit nil)))
8654 t))))
8656 (defvar org-markers-to-move nil
8657 "Markers that should be moved with a cut-and-paste operation.
8658 Those markers are stored together with their positions relative to
8659 the start of the region.")
8661 (defun org-save-markers-in-region (beg end)
8662 "Check markers in region.
8663 If these markers are between BEG and END, record their position relative
8664 to BEG, so that after moving the block of text, we can put the markers back
8665 into place.
8666 This function gets called just before an entry or tree gets cut from the
8667 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8668 called immediately, to move the markers with the entries."
8669 (setq org-markers-to-move nil)
8670 (when (featurep 'org-clock)
8671 (org-clock-save-markers-for-cut-and-paste beg end))
8672 (when (featurep 'org-agenda)
8673 (org-agenda-save-markers-for-cut-and-paste beg end)))
8675 (defun org-check-and-save-marker (marker beg end)
8676 "Check if MARKER is between BEG and END.
8677 If yes, remember the marker and the distance to BEG."
8678 (when (and (marker-buffer marker)
8679 (equal (marker-buffer marker) (current-buffer)))
8680 (if (and (>= marker beg) (< marker end))
8681 (push (cons marker (- marker beg)) org-markers-to-move))))
8683 (defun org-reinstall-markers-in-region (beg)
8684 "Move all remembered markers to their position relative to BEG."
8685 (mapc (lambda (x)
8686 (move-marker (car x) (+ beg (cdr x))))
8687 org-markers-to-move)
8688 (setq org-markers-to-move nil))
8690 (defun org-narrow-to-subtree ()
8691 "Narrow buffer to the current subtree."
8692 (interactive)
8693 (save-excursion
8694 (save-match-data
8695 (org-with-limited-levels
8696 (narrow-to-region
8697 (progn (org-back-to-heading t) (point))
8698 (progn (org-end-of-subtree t t)
8699 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8700 (point)))))))
8702 (defun org-narrow-to-block ()
8703 "Narrow buffer to the current block."
8704 (interactive)
8705 (let* ((case-fold-search t)
8706 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8707 "^[ \t]*#\\+end_.*")))
8708 (if blockp
8709 (narrow-to-region (car blockp) (cdr blockp))
8710 (user-error "Not in a block"))))
8712 (defun org-clone-subtree-with-time-shift (n &optional shift)
8713 "Clone the task (subtree) at point N times.
8714 The clones will be inserted as siblings.
8716 In interactive use, the user will be prompted for the number of
8717 clones to be produced. If the entry has a timestamp, the user
8718 will also be prompted for a time shift, which may be a repeater
8719 as used in time stamps, for example `+3d'. To disable this,
8720 you can call the function with a universal prefix argument.
8722 When a valid repeater is given and the entry contains any time
8723 stamps, the clones will become a sequence in time, with time
8724 stamps in the subtree shifted for each clone produced. If SHIFT
8725 is nil or the empty string, time stamps will be left alone. The
8726 ID property of the original subtree is removed.
8728 If the original subtree did contain time stamps with a repeater,
8729 the following will happen:
8730 - the repeater will be removed in each clone
8731 - an additional clone will be produced, with the current, unshifted
8732 date(s) in the entry.
8733 - the original entry will be placed *after* all the clones, with
8734 repeater intact.
8735 - the start days in the repeater in the original entry will be shifted
8736 to past the last clone.
8737 In this way you can spell out a number of instances of a repeating task,
8738 and still retain the repeater to cover future instances of the task."
8739 (interactive "nNumber of clones to produce: ")
8740 (let ((shift
8741 (or shift
8742 (if (and (not (equal current-prefix-arg '(4)))
8743 (save-excursion
8744 (re-search-forward org-ts-regexp-both
8745 (save-excursion
8746 (org-end-of-subtree t)
8747 (point)) t)))
8748 (read-from-minibuffer
8749 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8750 ""))) ;; No time shift
8751 (n-no-remove -1)
8752 (drawer-re org-drawer-regexp)
8753 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8754 beg end template task idprop
8755 shift-n shift-what doshift nmin nmax)
8756 (if (not (and (integerp n) (> n 0)))
8757 (user-error "Invalid number of replications %s" n))
8758 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8759 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8760 shift)))
8761 (user-error "Invalid shift specification %s" shift))
8762 (when doshift
8763 (setq shift-n (string-to-number (match-string 1 shift))
8764 shift-what (cdr (assoc (match-string 2 shift)
8765 '(("d" . day) ("w" . week)
8766 ("m" . month) ("y" . year))))))
8767 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8768 (setq nmin 1 nmax n)
8769 (org-back-to-heading t)
8770 (setq beg (point))
8771 (setq idprop (org-entry-get nil "ID"))
8772 (org-end-of-subtree t t)
8773 (or (bolp) (insert "\n"))
8774 (setq end (point))
8775 (setq template (buffer-substring beg end))
8776 (when (and doshift
8777 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8778 (delete-region beg end)
8779 (setq end beg)
8780 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8781 (goto-char end)
8782 (loop for n from nmin to nmax do
8783 ;; prepare clone
8784 (with-temp-buffer
8785 (insert template)
8786 (org-mode)
8787 (goto-char (point-min))
8788 (org-show-subtree)
8789 (and idprop (if org-clone-delete-id
8790 (org-entry-delete nil "ID")
8791 (org-id-get-create t)))
8792 (unless (= n 0)
8793 (while (re-search-forward org-clock-re nil t)
8794 (kill-whole-line))
8795 (goto-char (point-min))
8796 (while (re-search-forward drawer-re nil t)
8797 (org-remove-empty-drawer-at (point))))
8798 (goto-char (point-min))
8799 (when doshift
8800 (while (re-search-forward org-ts-regexp-both nil t)
8801 (org-timestamp-change (* n shift-n) shift-what))
8802 (unless (= n n-no-remove)
8803 (goto-char (point-min))
8804 (while (re-search-forward org-ts-regexp nil t)
8805 (save-excursion
8806 (goto-char (match-beginning 0))
8807 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8808 (delete-region (match-beginning 1) (match-end 1)))))))
8809 (setq task (buffer-string)))
8810 (insert task))
8811 (goto-char beg)))
8813 ;;; Outline Sorting
8815 (defun org-sort (with-case)
8816 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8817 Optional argument WITH-CASE means sort case-sensitively."
8818 (interactive "P")
8819 (cond
8820 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8821 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8823 (org-call-with-arg 'org-sort-entries with-case))))
8825 (defun org-sort-remove-invisible (s)
8826 "Remove invisible links from string S."
8827 (remove-text-properties 0 (length s) org-rm-props s)
8828 (while (string-match org-bracket-link-regexp s)
8829 (setq s (replace-match (if (match-end 2)
8830 (match-string 3 s)
8831 (match-string 1 s)) t t s)))
8832 (let ((st (format " %s " s)))
8833 (while (string-match org-emph-re st)
8834 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8835 (setq s (substring st 1 -1)))
8838 (defvar org-priority-regexp) ; defined later in the file
8840 (defvar org-after-sorting-entries-or-items-hook nil
8841 "Hook that is run after a bunch of entries or items have been sorted.
8842 When children are sorted, the cursor is in the parent line when this
8843 hook gets called. When a region or a plain list is sorted, the cursor
8844 will be in the first entry of the sorted region/list.")
8846 (defun org-sort-entries
8847 (&optional with-case sorting-type getkey-func compare-func property)
8848 "Sort entries on a certain level of an outline tree.
8849 If there is an active region, the entries in the region are sorted.
8850 Else, if the cursor is before the first entry, sort the top-level items.
8851 Else, the children of the entry at point are sorted.
8853 Sorting can be alphabetically, numerically, by date/time as given by
8854 a time stamp, by a property, by priority order, or by a custom function.
8856 The command prompts for the sorting type unless it has been given to the
8857 function through the SORTING-TYPE argument, which needs to be a character,
8858 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8859 the precise meaning of each character:
8861 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8862 c By creation time, which is assumed to be the first inactive time stamp
8863 at the beginning of a line.
8864 d By deadline date/time.
8865 k By clocking time.
8866 n Numerically, by converting the beginning of the entry/item to a number.
8867 o By order of TODO keywords.
8868 p By priority according to the cookie.
8869 r By the value of a property.
8870 s By scheduled date/time.
8871 t By date/time, either the first active time stamp in the entry, or, if
8872 none exist, by the first inactive one.
8874 Capital letters will reverse the sort order.
8876 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8877 called with point at the beginning of the record. It must return either
8878 a string or a number that should serve as the sorting key for that record.
8880 Comparing entries ignores case by default. However, with an optional argument
8881 WITH-CASE, the sorting considers case as well.
8883 Sorting is done against the visible part of the headlines, it ignores hidden
8884 links.
8886 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8887 (interactive "P")
8888 (let ((case-func (if with-case 'identity 'downcase))
8889 (cmstr
8890 ;; The clock marker is lost when using `sort-subr', let's
8891 ;; store the clocking string.
8892 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8893 (save-excursion
8894 (goto-char org-clock-marker)
8895 (looking-back "^.*") (match-string-no-properties 0))))
8896 start beg end stars re re2
8897 txt what tmp)
8898 ;; Find beginning and end of region to sort
8899 (cond
8900 ((org-region-active-p)
8901 ;; we will sort the region
8902 (setq end (region-end)
8903 what "region")
8904 (goto-char (region-beginning))
8905 (if (not (org-at-heading-p)) (outline-next-heading))
8906 (setq start (point)))
8907 ((or (org-at-heading-p)
8908 (ignore-errors (progn (org-back-to-heading) t)))
8909 ;; we will sort the children of the current headline
8910 (org-back-to-heading)
8911 (setq start (point)
8912 end (progn (org-end-of-subtree t t)
8913 (or (bolp) (insert "\n"))
8914 (when (>= (org-back-over-empty-lines) 1)
8915 (forward-line 1))
8916 (point))
8917 what "children")
8918 (goto-char start)
8919 (show-subtree)
8920 (outline-next-heading))
8922 ;; we will sort the top-level entries in this file
8923 (goto-char (point-min))
8924 (or (org-at-heading-p) (outline-next-heading))
8925 (setq start (point))
8926 (goto-char (point-max))
8927 (beginning-of-line 1)
8928 (when (looking-at ".*?\\S-")
8929 ;; File ends in a non-white line
8930 (end-of-line 1)
8931 (insert "\n"))
8932 (setq end (point-max))
8933 (setq what "top-level")
8934 (goto-char start)
8935 (show-all)))
8937 (setq beg (point))
8938 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8940 (looking-at "\\(\\*+\\)")
8941 (setq stars (match-string 1)
8942 re (concat "^" (regexp-quote stars) " +")
8943 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8944 txt (buffer-substring beg end))
8945 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8946 (if (and (not (equal stars "*")) (string-match re2 txt))
8947 (user-error "Region to sort contains a level above the first entry"))
8949 (unless sorting-type
8950 (message
8951 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8952 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8953 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8954 what)
8955 (setq sorting-type (read-char-exclusive))
8957 (unless getkey-func
8958 (and (= (downcase sorting-type) ?f)
8959 (setq getkey-func
8960 (org-icompleting-read "Sort using function: "
8961 obarray 'fboundp t nil nil))
8962 (setq getkey-func (intern getkey-func))))
8964 (and (= (downcase sorting-type) ?r)
8965 (not property)
8966 (setq property
8967 (org-icompleting-read "Property: "
8968 (mapcar 'list (org-buffer-property-keys t))
8969 nil t))))
8971 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8972 (message "Sorting entries...")
8974 (save-restriction
8975 (narrow-to-region start end)
8976 (let ((dcst (downcase sorting-type))
8977 (case-fold-search nil)
8978 (now (current-time)))
8979 (sort-subr
8980 (/= dcst sorting-type)
8981 ;; This function moves to the beginning character of the "record" to
8982 ;; be sorted.
8983 (lambda nil
8984 (if (re-search-forward re nil t)
8985 (goto-char (match-beginning 0))
8986 (goto-char (point-max))))
8987 ;; This function moves to the last character of the "record" being
8988 ;; sorted.
8989 (lambda nil
8990 (save-match-data
8991 (condition-case nil
8992 (outline-forward-same-level 1)
8993 (error
8994 (goto-char (point-max))))))
8995 ;; This function returns the value that gets sorted against.
8996 (lambda nil
8997 (cond
8998 ((= dcst ?n)
8999 (if (looking-at org-complex-heading-regexp)
9000 (string-to-number (org-sort-remove-invisible (match-string 4)))
9001 nil))
9002 ((= dcst ?a)
9003 (if (looking-at org-complex-heading-regexp)
9004 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9005 nil))
9006 ((= dcst ?k)
9007 (or (get-text-property (point) :org-clock-minutes) 0))
9008 ((= dcst ?t)
9009 (let ((end (save-excursion (outline-next-heading) (point))))
9010 (if (or (re-search-forward org-ts-regexp end t)
9011 (re-search-forward org-ts-regexp-both end t))
9012 (org-time-string-to-seconds (match-string 0))
9013 (org-float-time now))))
9014 ((= dcst ?c)
9015 (let ((end (save-excursion (outline-next-heading) (point))))
9016 (if (re-search-forward
9017 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9018 end t)
9019 (org-time-string-to-seconds (match-string 0))
9020 (org-float-time now))))
9021 ((= dcst ?s)
9022 (let ((end (save-excursion (outline-next-heading) (point))))
9023 (if (re-search-forward org-scheduled-time-regexp end t)
9024 (org-time-string-to-seconds (match-string 1))
9025 (org-float-time now))))
9026 ((= dcst ?d)
9027 (let ((end (save-excursion (outline-next-heading) (point))))
9028 (if (re-search-forward org-deadline-time-regexp end t)
9029 (org-time-string-to-seconds (match-string 1))
9030 (org-float-time now))))
9031 ((= dcst ?p)
9032 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9033 (string-to-char (match-string 2))
9034 org-default-priority))
9035 ((= dcst ?r)
9036 (or (org-entry-get nil property) ""))
9037 ((= dcst ?o)
9038 (if (looking-at org-complex-heading-regexp)
9039 (let* ((m (match-string 2))
9040 (s (if (member m org-done-keywords) '- '+)))
9041 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9042 ((= dcst ?f)
9043 (if getkey-func
9044 (progn
9045 (setq tmp (funcall getkey-func))
9046 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
9047 tmp)
9048 (error "Invalid key function `%s'" getkey-func)))
9049 (t (error "Invalid sorting type `%c'" sorting-type))))
9051 (cond
9052 ((= dcst ?a) 'string<)
9053 ((= dcst ?f) compare-func)
9054 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9055 (run-hooks 'org-after-sorting-entries-or-items-hook)
9056 ;; Reset the clock marker if needed
9057 (when cmstr
9058 (save-excursion
9059 (goto-char start)
9060 (search-forward cmstr nil t)
9061 (move-marker org-clock-marker (point))))
9062 (message "Sorting entries...done")))
9064 ;;; The orgstruct minor mode
9066 ;; Define a minor mode which can be used in other modes in order to
9067 ;; integrate the org-mode structure editing commands.
9069 ;; This is really a hack, because the org-mode structure commands use
9070 ;; keys which normally belong to the major mode. Here is how it
9071 ;; works: The minor mode defines all the keys necessary to operate the
9072 ;; structure commands, but wraps the commands into a function which
9073 ;; tests if the cursor is currently at a headline or a plain list
9074 ;; item. If that is the case, the structure command is used,
9075 ;; temporarily setting many Org-mode variables like regular
9076 ;; expressions for filling etc. However, when any of those keys is
9077 ;; used at a different location, function uses `key-binding' to look
9078 ;; up if the key has an associated command in another currently active
9079 ;; keymap (minor modes, major mode, global), and executes that
9080 ;; command. There might be problems if any of the keys is otherwise
9081 ;; used as a prefix key.
9083 (defcustom orgstruct-heading-prefix-regexp ""
9084 "Regexp that matches the custom prefix of Org headlines in
9085 orgstruct(++)-mode."
9086 :group 'org
9087 :version "24.4"
9088 :package-version '(Org . "8.3")
9089 :type 'regexp)
9090 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9092 (defcustom orgstruct-setup-hook nil
9093 "Hook run after orgstruct-mode-map is filled."
9094 :group 'org
9095 :version "24.4"
9096 :package-version '(Org . "8.0")
9097 :type 'hook)
9099 (defvar orgstruct-initialized nil)
9101 (defvar org-local-vars nil
9102 "List of local variables, for use by `orgstruct-mode'.")
9104 ;;;###autoload
9105 (define-minor-mode orgstruct-mode
9106 "Toggle the minor mode `orgstruct-mode'.
9107 This mode is for using Org-mode structure commands in other
9108 modes. The following keys behave as if Org-mode were active, if
9109 the cursor is on a headline, or on a plain list item (both as
9110 defined by Org-mode)."
9111 nil " OrgStruct" (make-sparse-keymap)
9112 (funcall (if orgstruct-mode
9113 'add-to-invisibility-spec
9114 'remove-from-invisibility-spec)
9115 '(outline . t))
9116 (when orgstruct-mode
9117 (org-load-modules-maybe)
9118 (unless orgstruct-initialized
9119 (orgstruct-setup)
9120 (setq orgstruct-initialized t))))
9122 ;;;###autoload
9123 (defun turn-on-orgstruct ()
9124 "Unconditionally turn on `orgstruct-mode'."
9125 (orgstruct-mode 1))
9127 (defvar org-fb-vars nil)
9128 (make-variable-buffer-local 'org-fb-vars)
9129 (defun orgstruct++-mode (&optional arg)
9130 "Toggle `orgstruct-mode', the enhanced version of it.
9131 In addition to setting orgstruct-mode, this also exports all
9132 indentation and autofilling variables from org-mode into the
9133 buffer. It will also recognize item context in multiline items."
9134 (interactive "P")
9135 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9136 (if (< arg 1)
9137 (progn (orgstruct-mode -1)
9138 (mapc (lambda(v)
9139 (org-set-local (car v)
9140 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9141 org-fb-vars))
9142 (orgstruct-mode 1)
9143 (setq org-fb-vars nil)
9144 (unless org-local-vars
9145 (setq org-local-vars (org-get-local-variables)))
9146 (let (var val)
9147 (mapc
9148 (lambda (x)
9149 (when (string-match
9150 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9151 (symbol-name (car x)))
9152 (setq var (car x) val (nth 1 x))
9153 (push (list var `(quote ,(eval var))) org-fb-vars)
9154 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9155 org-local-vars)
9156 (org-set-local 'orgstruct-is-++ t))))
9158 (defvar orgstruct-is-++ nil
9159 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9160 (make-variable-buffer-local 'orgstruct-is-++)
9162 ;;;###autoload
9163 (defun turn-on-orgstruct++ ()
9164 "Unconditionally turn on `orgstruct++-mode'."
9165 (orgstruct++-mode 1))
9167 (defun orgstruct-error ()
9168 "Error when there is no default binding for a structure key."
9169 (interactive)
9170 (funcall (if (fboundp 'user-error)
9171 'user-error
9172 'error)
9173 "This key has no function outside structure elements"))
9175 (defun orgstruct-setup ()
9176 "Setup orgstruct keymap."
9177 (dolist (cell '((org-demote . t)
9178 (org-metaleft . t)
9179 (org-metaright . t)
9180 (org-promote . t)
9181 (org-shiftmetaleft . t)
9182 (org-shiftmetaright . t)
9183 org-backward-element
9184 org-backward-heading-same-level
9185 org-ctrl-c-ret
9186 org-ctrl-c-minus
9187 org-ctrl-c-star
9188 org-cycle
9189 org-forward-heading-same-level
9190 org-insert-heading
9191 org-insert-heading-respect-content
9192 org-kill-note-or-show-branches
9193 org-mark-subtree
9194 org-meta-return
9195 org-metadown
9196 org-metaup
9197 org-narrow-to-subtree
9198 org-promote-subtree
9199 org-reveal
9200 org-shiftdown
9201 org-shiftleft
9202 org-shiftmetadown
9203 org-shiftmetaup
9204 org-shiftright
9205 org-shifttab
9206 org-shifttab
9207 org-shiftup
9208 org-show-subtree
9209 org-sort
9210 org-up-element
9211 outline-demote
9212 outline-next-visible-heading
9213 outline-previous-visible-heading
9214 outline-promote
9215 outline-up-heading
9216 show-children))
9217 (let ((f (or (car-safe cell) cell))
9218 (disable-when-heading-prefix (cdr-safe cell)))
9219 (when (fboundp f)
9220 (let ((new-bindings))
9221 (dolist (binding (nconc (where-is-internal f org-mode-map)
9222 (where-is-internal f outline-mode-map)))
9223 (push binding new-bindings)
9224 ;; TODO use local-function-key-map
9225 (dolist (rep '(("<tab>" . "TAB")
9226 ("<return>" . "RET")
9227 ("<escape>" . "ESC")
9228 ("<delete>" . "DEL")))
9229 (setq binding (read-kbd-macro
9230 (let ((case-fold-search))
9231 (replace-regexp-in-string
9232 (regexp-quote (cdr rep))
9233 (car rep)
9234 (key-description binding)))))
9235 (pushnew binding new-bindings :test 'equal)))
9236 (dolist (binding new-bindings)
9237 (let ((key (lookup-key orgstruct-mode-map binding)))
9238 (when (or (not key) (numberp key))
9239 (ignore-errors
9240 (org-defkey orgstruct-mode-map
9241 binding
9242 (orgstruct-make-binding
9243 f binding disable-when-heading-prefix))))))))))
9244 (run-hooks 'orgstruct-setup-hook))
9246 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9247 "Create a function for binding in the structure minor mode.
9248 FUN is the command to call inside a table. KEY is the key that
9249 should be checked in for a command to execute outside of tables.
9250 Non-nil `disable-when-heading-prefix' means to disable the command
9251 if `orgstruct-heading-prefix-regexp' is not empty."
9252 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9253 (let ((nname name)
9254 (i 0))
9255 (while (fboundp (intern nname))
9256 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9257 (setq name (intern nname)))
9258 (eval
9259 (let ((bindings '((org-heading-regexp
9260 (concat "^"
9261 orgstruct-heading-prefix-regexp
9262 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9263 (org-outline-regexp
9264 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9265 (org-outline-regexp-bol
9266 (concat "^" org-outline-regexp))
9267 (outline-regexp org-outline-regexp)
9268 (outline-heading-end-regexp "\n")
9269 (outline-level 'org-outline-level)
9270 (outline-heading-alist))))
9271 `(defun ,name (arg)
9272 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9273 "Outside of structure, run the binding of `"
9274 (key-description key) "'."
9275 (when disable-when-heading-prefix
9276 (concat
9277 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9278 "back to the default binding due to limitations of Org's implementation of\n"
9279 "`" (symbol-name fun) "'.")))
9280 (interactive "p")
9281 (let* ((disable
9282 ,(and disable-when-heading-prefix
9283 '(not (string= orgstruct-heading-prefix-regexp ""))))
9284 (fallback
9285 (or disable
9286 (not
9287 (let* ,bindings
9288 (org-context-p 'headline 'item
9289 ,(when (memq fun
9290 '(org-insert-heading
9291 org-insert-heading-respect-content
9292 org-meta-return))
9293 '(when orgstruct-is-++
9294 'item-body))))))))
9295 (if fallback
9296 (let* ((orgstruct-mode)
9297 (binding
9298 (let ((key ,key))
9299 (catch 'exit
9300 (dolist
9301 (rep
9302 '(nil
9303 ("<\\([^>]*\\)tab>" . "\\1TAB")
9304 ("<\\([^>]*\\)return>" . "\\1RET")
9305 ("<\\([^>]*\\)escape>" . "\\1ESC")
9306 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9307 nil)
9308 (when rep
9309 (setq key (read-kbd-macro
9310 (let ((case-fold-search))
9311 (replace-regexp-in-string
9312 (car rep)
9313 (cdr rep)
9314 (key-description key))))))
9315 (when (key-binding key)
9316 (throw 'exit (key-binding key))))))))
9317 (if (keymapp binding)
9318 (org-set-transient-map binding)
9319 (let ((func (or binding
9320 (unless disable
9321 'orgstruct-error))))
9322 (when func
9323 (call-interactively func)))))
9324 (org-run-like-in-org-mode
9325 (lambda ()
9326 (interactive)
9327 (let* ,bindings
9328 (call-interactively ',fun)))))))))
9329 name))
9331 (defun org-contextualize-keys (alist contexts)
9332 "Return valid elements in ALIST depending on CONTEXTS.
9334 `org-agenda-custom-commands' or `org-capture-templates' are the
9335 values used for ALIST, and `org-agenda-custom-commands-contexts'
9336 or `org-capture-templates-contexts' are the associated contexts
9337 definitions."
9338 (let ((contexts
9339 ;; normalize contexts
9340 (mapcar
9341 (lambda(c) (cond ((listp (cadr c))
9342 (list (car c) (car c) (cadr c)))
9343 ((string= "" (cadr c))
9344 (list (car c) (car c) (caddr c)))
9345 (t c))) contexts))
9346 (a alist) c r s)
9347 ;; loop over all commands or templates
9348 (while (setq c (pop a))
9349 (let (vrules repl)
9350 (cond
9351 ((not (assoc (car c) contexts))
9352 (push c r))
9353 ((and (assoc (car c) contexts)
9354 (setq vrules (org-contextualize-validate-key
9355 (car c) contexts)))
9356 (mapc (lambda (vr)
9357 (when (not (equal (car vr) (cadr vr)))
9358 (setq repl vr))) vrules)
9359 (if (not repl) (push c r)
9360 (push (cadr repl) s)
9361 (push
9362 (cons (car c)
9363 (cdr (or (assoc (cadr repl) alist)
9364 (error "Undefined key `%s' as contextual replacement for `%s'"
9365 (cadr repl) (car c)))))
9366 r))))))
9367 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9368 (delq
9370 (delete-dups
9371 (mapcar (lambda (x)
9372 (let ((tpl (car x)))
9373 (when (not (delq
9375 (mapcar (lambda(y)
9376 (equal y tpl)) s))) x)))
9377 (reverse r))))))
9379 (defun org-contextualize-validate-key (key contexts)
9380 "Check CONTEXTS for agenda or capture KEY."
9381 (let (r rr res)
9382 (while (setq r (pop contexts))
9383 (mapc
9384 (lambda (rr)
9385 (when
9386 (and (equal key (car r))
9387 (if (functionp rr) (funcall rr)
9388 (or (and (eq (car rr) 'in-file)
9389 (buffer-file-name)
9390 (string-match (cdr rr) (buffer-file-name)))
9391 (and (eq (car rr) 'in-mode)
9392 (string-match (cdr rr) (symbol-name major-mode)))
9393 (and (eq (car rr) 'in-buffer)
9394 (string-match (cdr rr) (buffer-name)))
9395 (when (and (eq (car rr) 'not-in-file)
9396 (buffer-file-name))
9397 (not (string-match (cdr rr) (buffer-file-name))))
9398 (when (eq (car rr) 'not-in-mode)
9399 (not (string-match (cdr rr) (symbol-name major-mode))))
9400 (when (eq (car rr) 'not-in-buffer)
9401 (not (string-match (cdr rr) (buffer-name)))))))
9402 (push r res)))
9403 (car (last r))))
9404 (delete-dups (delq nil res))))
9406 (defun org-context-p (&rest contexts)
9407 "Check if local context is any of CONTEXTS.
9408 Possible values in the list of contexts are `table', `headline', and `item'."
9409 (let ((pos (point)))
9410 (goto-char (point-at-bol))
9411 (prog1 (or (and (memq 'table contexts)
9412 (looking-at "[ \t]*|"))
9413 (and (memq 'headline contexts)
9414 (looking-at org-outline-regexp))
9415 (and (memq 'item contexts)
9416 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9417 (and (memq 'item-body contexts)
9418 (org-in-item-p)))
9419 (goto-char pos))))
9421 (defun org-get-local-variables ()
9422 "Return a list of all local variables in an Org mode buffer."
9423 (let (varlist)
9424 (with-current-buffer (get-buffer-create "*Org tmp*")
9425 (erase-buffer)
9426 (org-mode)
9427 (setq varlist (buffer-local-variables)))
9428 (kill-buffer "*Org tmp*")
9429 (delq nil
9430 (mapcar
9431 (lambda (x)
9432 (setq x
9433 (if (symbolp x)
9434 (list x)
9435 (list (car x) (cdr x))))
9436 (if (and (not (get (car x) 'org-state))
9437 (string-match
9438 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9439 (symbol-name (car x))))
9440 x nil))
9441 varlist))))
9443 (defun org-clone-local-variables (from-buffer &optional regexp)
9444 "Clone local variables from FROM-BUFFER.
9445 Optional argument REGEXP selects variables to clone."
9446 (mapc
9447 (lambda (pair)
9448 (and (symbolp (car pair))
9449 (or (null regexp)
9450 (string-match regexp (symbol-name (car pair))))
9451 (set (make-local-variable (car pair))
9452 (cdr pair))))
9453 (buffer-local-variables from-buffer)))
9455 ;;;###autoload
9456 (defun org-run-like-in-org-mode (cmd)
9457 "Run a command, pretending that the current buffer is in Org-mode.
9458 This will temporarily bind local variables that are typically bound in
9459 Org-mode to the values they have in Org-mode, and then interactively
9460 call CMD."
9461 (org-load-modules-maybe)
9462 (unless org-local-vars
9463 (setq org-local-vars (org-get-local-variables)))
9464 (let (binds)
9465 (dolist (var org-local-vars)
9466 (when (or (not (boundp (car var)))
9467 (eq (symbol-value (car var))
9468 (default-value (car var))))
9469 (push (list (car var) `(quote ,(cadr var))) binds)))
9470 (eval `(let ,binds
9471 (call-interactively (quote ,cmd))))))
9473 (defun org-get-category (&optional pos force-refresh)
9474 "Get the category applying to position POS."
9475 (save-match-data
9476 (if force-refresh (org-refresh-category-properties))
9477 (let ((pos (or pos (point))))
9478 (or (get-text-property pos 'org-category)
9479 (progn (org-refresh-category-properties)
9480 (get-text-property pos 'org-category))))))
9482 ;;; Refresh properties
9484 (defun org-refresh-properties (dprop tprop)
9485 "Refresh buffer text properties.
9486 DPROP is the drawer property and TPROP is either the
9487 corresponding text property to set, or an alist with each element
9488 being a text property (as a symbol) and a function to apply to
9489 the value of the drawer property."
9490 (let ((case-fold-search t)
9491 (inhibit-read-only t))
9492 (org-with-silent-modifications
9493 (save-excursion
9494 (save-restriction
9495 (widen)
9496 (goto-char (point-min))
9497 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9498 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9500 (defun org-refresh-property (tprop p)
9501 "Refresh the buffer text property TPROP from the drawer property P.
9502 The refresh happens only for the current tree (not subtree)."
9503 (save-excursion
9504 (org-back-to-heading t)
9505 ;; tprop is a text property symbol
9506 (if (symbolp tprop)
9507 (put-text-property
9508 (point) (or (outline-next-heading) (point-max)) tprop p)
9509 ;; tprop is an alist with (properties . function) elements
9510 (mapc (lambda(al)
9511 (save-excursion
9512 (put-text-property
9513 (point-at-bol) (or (outline-next-heading) (point-max))
9514 (car al)
9515 (funcall (cdr al) p))))
9516 tprop))))
9518 (defun org-refresh-category-properties ()
9519 "Refresh category text properties in the buffer."
9520 (let ((case-fold-search t)
9521 (inhibit-read-only t)
9522 (def-cat (cond
9523 ((null org-category)
9524 (if buffer-file-name
9525 (file-name-sans-extension
9526 (file-name-nondirectory buffer-file-name))
9527 "???"))
9528 ((symbolp org-category) (symbol-name org-category))
9529 (t org-category)))
9530 beg end cat pos optionp)
9531 (org-with-silent-modifications
9532 (save-excursion
9533 (save-restriction
9534 (widen)
9535 (goto-char (point-min))
9536 (put-text-property (point) (point-max) 'org-category def-cat)
9537 (while (re-search-forward
9538 "^[ \t]*\\(\\(?:#\\+\\|:\\)CATEGORY:\\)\\(.*\\)" nil t)
9539 (setq pos (match-end 0)
9540 optionp (equal (char-after (match-beginning 0)) ?#)
9541 cat (org-trim (match-string 2)))
9542 (if optionp
9543 (setq beg (point-at-bol) end (point-max))
9544 (org-back-to-heading t)
9545 (setq beg (point) end (org-end-of-subtree t t)))
9546 (put-text-property beg end 'org-category cat)
9547 (goto-char pos)))))))
9549 (defun org-refresh-stats-properties ()
9550 "Refresh stats text properties in the buffer."
9551 (let (stats)
9552 (org-with-silent-modifications
9553 (save-excursion
9554 (save-restriction
9555 (widen)
9556 (goto-char (point-min))
9557 (while (re-search-forward
9558 (concat org-outline-regexp-bol ".*"
9559 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9560 nil t)
9561 (setq stats (cond ((equal (match-string 3) "0") 0)
9562 ((match-string 2)
9563 (/ (* (string-to-number (match-string 2)) 100)
9564 (string-to-number (match-string 3))))
9565 (t (string-to-number (match-string 1)))))
9566 (org-back-to-heading t)
9567 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9568 'org-stats stats)))))))
9570 (defun org-refresh-effort-properties ()
9571 "Refresh effort properties"
9572 (org-refresh-properties
9573 org-effort-property
9574 '((effort . identity)
9575 (effort-minutes . org-duration-string-to-minutes))))
9577 ;;;; Link Stuff
9579 ;;; Link abbreviations
9581 (defun org-link-expand-abbrev (link)
9582 "Apply replacements as defined in `org-link-abbrev-alist'."
9583 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9584 (let* ((key (match-string 1 link))
9585 (as (or (assoc key org-link-abbrev-alist-local)
9586 (assoc key org-link-abbrev-alist)))
9587 (tag (and (match-end 2) (match-string 3 link)))
9588 rpl)
9589 (if (not as)
9590 link
9591 (setq rpl (cdr as))
9592 (cond
9593 ((symbolp rpl) (funcall rpl tag))
9594 ((string-match "%(\\([^)]+\\))" rpl)
9595 (replace-match
9596 (save-match-data
9597 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9598 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9599 ((string-match "%h" rpl)
9600 (replace-match (url-hexify-string (or tag "")) t t rpl))
9601 (t (concat rpl tag)))))
9602 link))
9604 ;;; Storing and inserting links
9606 (defvar org-insert-link-history nil
9607 "Minibuffer history for links inserted with `org-insert-link'.")
9609 (defvar org-stored-links nil
9610 "Contains the links stored with `org-store-link'.")
9612 (defvar org-store-link-plist nil
9613 "Plist with info about the most recently link created with `org-store-link'.")
9615 (defvar org-link-protocols nil
9616 "Link protocols added to Org-mode using `org-add-link-type'.")
9618 (defvar org-store-link-functions nil
9619 "List of functions that are called to create and store a link.
9620 Each function will be called in turn until one returns a non-nil
9621 value. Each function should check if it is responsible for creating
9622 this link (for example by looking at the major mode).
9623 If not, it must exit and return nil.
9624 If yes, it should return a non-nil value after a calling
9625 `org-store-link-props' with a list of properties and values.
9626 Special properties are:
9628 :type The link prefix, like \"http\". This must be given.
9629 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9630 This is obligatory as well.
9631 :description Optional default description for the second pair
9632 of brackets in an Org-mode link. The user can still change
9633 this when inserting this link into an Org-mode buffer.
9635 In addition to these, any additional properties can be specified
9636 and then used in capture templates.")
9638 (defun org-add-link-type (type &optional follow export)
9639 "Add TYPE to the list of `org-link-types'.
9640 Re-compute all regular expressions depending on `org-link-types'
9642 FOLLOW and EXPORT are two functions.
9644 FOLLOW should take the link path as the single argument and do whatever
9645 is necessary to follow the link, for example find a file or display
9646 a mail message.
9648 EXPORT should format the link path for export to one of the export formats.
9649 It should be a function accepting three arguments:
9651 path the path of the link, the text after the prefix (like \"http:\")
9652 desc the description of the link, if any
9653 format the export format, a symbol like `html' or `latex' or `ascii'.
9655 The function may use the FORMAT information to return different values
9656 depending on the format. The return value will be put literally into
9657 the exported file. If the return value is nil, this means Org should
9658 do what it normally does with links which do not have EXPORT defined.
9660 Org mode has a built-in default for exporting links. If you are happy with
9661 this default, there is no need to define an export function for the link
9662 type. For a simple example of an export function, see `org-bbdb.el'."
9663 (add-to-list 'org-link-types type t)
9664 (org-make-link-regexps)
9665 (org-element-update-syntax)
9666 (if (assoc type org-link-protocols)
9667 (setcdr (assoc type org-link-protocols) (list follow export))
9668 (push (list type follow export) org-link-protocols)))
9670 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9671 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9673 ;;;###autoload
9674 (defun org-store-link (arg)
9675 "\\<org-mode-map>Store an org-link to the current location.
9676 This link is added to `org-stored-links' and can later be inserted
9677 into an org-buffer with \\[org-insert-link].
9679 For some link types, a prefix arg is interpreted.
9680 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9681 For file links, arg negates `org-context-in-file-links'.
9683 A double prefix arg force skipping storing functions that are not
9684 part of Org's core.
9686 A triple prefix arg force storing a link for each line in the
9687 active region."
9688 (interactive "P")
9689 (org-load-modules-maybe)
9690 (if (and (equal arg '(64)) (org-region-active-p))
9691 (save-excursion
9692 (let ((end (region-end)))
9693 (goto-char (region-beginning))
9694 (set-mark (point))
9695 (while (< (point-at-eol) end)
9696 (move-end-of-line 1) (activate-mark)
9697 (let (current-prefix-arg)
9698 (call-interactively 'org-store-link))
9699 (move-beginning-of-line 2)
9700 (set-mark (point)))))
9701 (org-with-limited-levels
9702 (setq org-store-link-plist nil)
9703 (let (link cpltxt desc description search
9704 txt custom-id agenda-link sfuns sfunsn)
9705 (cond
9707 ;; Store a link using an external link type
9708 ((and (not (equal arg '(16)))
9709 (setq sfuns
9710 (delq
9711 nil (mapcar (lambda (f)
9712 (let (fs) (if (funcall f) (push f fs))))
9713 org-store-link-functions))
9714 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9715 (or (and (cdr sfuns)
9716 (funcall (intern
9717 (completing-read
9718 "Which function for creating the link? "
9719 sfunsn nil t (car sfunsn)))))
9720 (funcall (caar sfuns)))
9721 (setq link (plist-get org-store-link-plist :link)
9722 desc (or (plist-get org-store-link-plist
9723 :description) link))))
9725 ;; Store a link from a source code buffer
9726 ((org-src-edit-buffer-p)
9727 (let (label gc)
9728 (while (or (not label)
9729 (save-excursion
9730 (save-restriction
9731 (widen)
9732 (goto-char (point-min))
9733 (re-search-forward
9734 (regexp-quote (format org-coderef-label-format label))
9735 nil t))))
9736 (when label (message "Label exists already") (sit-for 2))
9737 (setq label (read-string "Code line label: " label)))
9738 (end-of-line 1)
9739 (setq link (format org-coderef-label-format label))
9740 (setq gc (- 79 (length link)))
9741 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9742 (insert link)
9743 (setq link (concat "(" label ")") desc nil)))
9745 ;; We are in the agenda, link to referenced location
9746 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9747 (let ((m (or (get-text-property (point) 'org-hd-marker)
9748 (get-text-property (point) 'org-marker))))
9749 (when m
9750 (org-with-point-at m
9751 (setq agenda-link
9752 (if (org-called-interactively-p 'any)
9753 (call-interactively 'org-store-link)
9754 (org-store-link nil)))))))
9756 ((eq major-mode 'calendar-mode)
9757 (let ((cd (calendar-cursor-to-date)))
9758 (setq link
9759 (format-time-string
9760 (car org-time-stamp-formats)
9761 (apply 'encode-time
9762 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9763 nil nil nil))))
9764 (org-store-link-props :type "calendar" :date cd)))
9766 ((eq major-mode 'help-mode)
9767 (setq link (concat "help:" (save-excursion
9768 (goto-char (point-min))
9769 (looking-at "^[^ ]+")
9770 (match-string 0))))
9771 (org-store-link-props :type "help"))
9773 ((eq major-mode 'w3-mode)
9774 (setq cpltxt (if (and (buffer-name)
9775 (not (string-match "Untitled" (buffer-name))))
9776 (buffer-name)
9777 (url-view-url t))
9778 link (url-view-url t))
9779 (org-store-link-props :type "w3" :url (url-view-url t)))
9781 ((eq major-mode 'image-mode)
9782 (setq cpltxt (concat "file:"
9783 (abbreviate-file-name buffer-file-name))
9784 link cpltxt)
9785 (org-store-link-props :type "image" :file buffer-file-name))
9787 ;; In dired, store a link to the file of the current line
9788 ((derived-mode-p 'dired-mode)
9789 (let ((file (dired-get-filename nil t)))
9790 (setq file (if file
9791 (abbreviate-file-name
9792 (expand-file-name (dired-get-filename nil t)))
9793 ;; otherwise, no file so use current directory.
9794 default-directory))
9795 (setq cpltxt (concat "file:" file)
9796 link cpltxt)))
9798 ((setq search (run-hook-with-args-until-success
9799 'org-create-file-search-functions))
9800 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9801 "::" search))
9802 (setq cpltxt (or description link)))
9804 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9805 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9806 (cond
9807 ;; Store a link using the target at point
9808 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9809 (setq cpltxt
9810 (concat "file:"
9811 (abbreviate-file-name
9812 (buffer-file-name (buffer-base-buffer)))
9813 "::" (match-string 1))
9814 link cpltxt))
9815 ((and (featurep 'org-id)
9816 (or (eq org-id-link-to-org-use-id t)
9817 (and (org-called-interactively-p 'any)
9818 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9819 (and (eq org-id-link-to-org-use-id
9820 'create-if-interactive-and-no-custom-id)
9821 (not custom-id))))
9822 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9823 ;; Store a link using the ID at point
9824 (setq link (condition-case nil
9825 (prog1 (org-id-store-link)
9826 (setq desc (or (plist-get org-store-link-plist
9827 :description)
9828 "")))
9829 (error
9830 ;; Probably before first headline, link only to file
9831 (concat "file:"
9832 (abbreviate-file-name
9833 (buffer-file-name (buffer-base-buffer))))))))
9835 ;; Just link to current headline
9836 (setq cpltxt (concat "file:"
9837 (abbreviate-file-name
9838 (buffer-file-name (buffer-base-buffer)))))
9839 ;; Add a context search string
9840 (when (org-xor org-context-in-file-links arg)
9841 (let* ((ee (org-element-at-point))
9842 (et (org-element-type ee))
9843 (ev (plist-get (cadr ee) :value))
9844 (ek (plist-get (cadr ee) :key))
9845 (eok (and (stringp ek) (string-match "name" ek))))
9846 (setq txt (cond
9847 ((org-at-heading-p) nil)
9848 ((and (eq et 'keyword) eok) ev)
9849 ((org-region-active-p)
9850 (buffer-substring (region-beginning) (region-end)))))
9851 (when (or (null txt) (string-match "\\S-" txt))
9852 (setq cpltxt
9853 (concat cpltxt "::"
9854 (condition-case nil
9855 (org-make-org-heading-search-string txt)
9856 (error "")))
9857 desc (or (and (eq et 'keyword) eok ev)
9858 (nth 4 (ignore-errors (org-heading-components)))
9859 "NONE")))))
9860 (if (string-match "::\\'" cpltxt)
9861 (setq cpltxt (substring cpltxt 0 -2)))
9862 (setq link cpltxt))))
9864 ((buffer-file-name (buffer-base-buffer))
9865 ;; Just link to this file here.
9866 (setq cpltxt (concat "file:"
9867 (abbreviate-file-name
9868 (buffer-file-name (buffer-base-buffer)))))
9869 ;; Add a context string.
9870 (when (org-xor org-context-in-file-links arg)
9871 (setq txt (if (org-region-active-p)
9872 (buffer-substring (region-beginning) (region-end))
9873 (buffer-substring (point-at-bol) (point-at-eol))))
9874 ;; Only use search option if there is some text.
9875 (when (string-match "\\S-" txt)
9876 (setq cpltxt
9877 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9878 desc "NONE")))
9879 (setq link cpltxt))
9881 ((org-called-interactively-p 'interactive)
9882 (user-error "No method for storing a link from this buffer"))
9884 (t (setq link nil)))
9886 ;; We're done setting link and desc, clean up
9887 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9888 (setq link (or link cpltxt)
9889 desc (or desc cpltxt))
9890 (cond ((equal desc "NONE") (setq desc nil))
9891 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9892 (let ((d0 (match-string 3 desc))
9893 (p0 (match-string 5 desc)))
9894 (setq desc
9895 (replace-regexp-in-string
9896 org-bracket-link-regexp
9897 (concat (or p0 d0)
9898 (if (equal (length (match-string 0 desc))
9899 (length desc)) "*" "")) desc)))))
9901 ;; Return the link
9902 (if (not (and (or (org-called-interactively-p 'any)
9903 executing-kbd-macro) link))
9904 (or agenda-link (and link (org-make-link-string link desc)))
9905 (push (list link desc) org-stored-links)
9906 (message "Stored: %s" (or desc link))
9907 (when custom-id
9908 (setq link (concat "file:" (abbreviate-file-name
9909 (buffer-file-name)) "::#" custom-id))
9910 (push (list link desc) org-stored-links))
9911 (car org-stored-links))))))
9913 (defun org-store-link-props (&rest plist)
9914 "Store link properties, extract names and addresses."
9915 (let (x adr)
9916 (when (setq x (plist-get plist :from))
9917 (setq adr (mail-extract-address-components x))
9918 (setq plist (plist-put plist :fromname (car adr)))
9919 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9920 (when (setq x (plist-get plist :to))
9921 (setq adr (mail-extract-address-components x))
9922 (setq plist (plist-put plist :toname (car adr)))
9923 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9924 (let ((from (plist-get plist :from))
9925 (to (plist-get plist :to)))
9926 (when (and from to org-from-is-user-regexp)
9927 (setq plist
9928 (plist-put plist :fromto
9929 (if (string-match org-from-is-user-regexp from)
9930 (concat "to %t")
9931 (concat "from %f"))))))
9932 (setq org-store-link-plist plist))
9934 (defun org-add-link-props (&rest plist)
9935 "Add these properties to the link property list."
9936 (let (key value)
9937 (while plist
9938 (setq key (pop plist) value (pop plist))
9939 (setq org-store-link-plist
9940 (plist-put org-store-link-plist key value)))))
9942 (defun org-email-link-description (&optional fmt)
9943 "Return the description part of an email link.
9944 This takes information from `org-store-link-plist' and formats it
9945 according to FMT (default from `org-email-link-description-format')."
9946 (setq fmt (or fmt org-email-link-description-format))
9947 (let* ((p org-store-link-plist)
9948 (to (plist-get p :toaddress))
9949 (from (plist-get p :fromaddress))
9950 (table
9951 (list
9952 (cons "%c" (plist-get p :fromto))
9953 (cons "%F" (plist-get p :from))
9954 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9955 (cons "%T" (plist-get p :to))
9956 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9957 (cons "%s" (plist-get p :subject))
9958 (cons "%d" (plist-get p :date))
9959 (cons "%m" (plist-get p :message-id)))))
9960 (when (string-match "%c" fmt)
9961 ;; Check if the user wrote this message
9962 (if (and org-from-is-user-regexp from to
9963 (save-match-data (string-match org-from-is-user-regexp from)))
9964 (setq fmt (replace-match "to %t" t t fmt))
9965 (setq fmt (replace-match "from %f" t t fmt))))
9966 (org-replace-escapes fmt table)))
9968 (defun org-make-org-heading-search-string (&optional string)
9969 "Make search string for the current headline or STRING."
9970 (let ((s (or string
9971 (and (derived-mode-p 'org-mode)
9972 (save-excursion
9973 (org-back-to-heading t)
9974 (org-element-property :raw-value (org-element-at-point))))))
9975 (lines org-context-in-file-links))
9976 (or string (setq s (concat "*" s))) ; Add * for headlines
9977 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9978 (when (and string (integerp lines) (> lines 0))
9979 (let ((slines (org-split-string s "\n")))
9980 (when (< lines (length slines))
9981 (setq s (mapconcat
9982 'identity
9983 (reverse (nthcdr (- (length slines) lines)
9984 (reverse slines))) "\n")))))
9985 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9987 (defun org-make-link-string (link &optional description)
9988 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9989 (unless (string-match "\\S-" link)
9990 (error "Empty link"))
9991 (when (and description
9992 (stringp description)
9993 (not (string-match "\\S-" description)))
9994 (setq description nil))
9995 (when (stringp description)
9996 ;; Remove brackets from the description, they are fatal.
9997 (while (string-match "\\[" description)
9998 (setq description (replace-match "{" t t description)))
9999 (while (string-match "\\]" description)
10000 (setq description (replace-match "}" t t description))))
10001 (when (equal link description)
10002 ;; No description needed, it is identical
10003 (setq description nil))
10004 (when (and (not description)
10005 (not (string-match (org-image-file-name-regexp) link))
10006 (not (equal link (org-link-escape link))))
10007 (setq description (org-extract-attributes link)))
10008 (setq link
10009 (cond ((string-match (org-image-file-name-regexp) link) link)
10010 ((string-match org-link-types-re link)
10011 (concat (match-string 1 link)
10012 (org-link-escape (substring link (match-end 1)))))
10013 (t (org-link-escape link))))
10014 (concat "[[" link "]"
10015 (if description (concat "[" description "]") "")
10016 "]"))
10018 (defconst org-link-escape-chars
10019 ;;%20 %5B %5D
10020 '(?\ ?\[ ?\])
10021 "List of characters that should be escaped in a link when stored to Org.
10022 This is the list that is used for internal purposes.")
10024 (defconst org-link-escape-chars-browser
10025 ;;%20 %22
10026 '(?\ ?\")
10027 "List of characters to be escaped before handing over to the browser.
10028 If you consider using this constant then you probably want to use
10029 the function `org-link-escape-browser' instead. See there why
10030 this constant is a candidate to be removed once Org drops support
10031 for Emacs 24.1 and 24.2.")
10033 (defun org-link-escape (text &optional table merge)
10034 "Return percent escaped representation of TEXT.
10035 TEXT is a string with the text to escape.
10036 Optional argument TABLE is a list with characters that should be
10037 escaped. When nil, `org-link-escape-chars' is used.
10038 If optional argument MERGE is set, merge TABLE into
10039 `org-link-escape-chars'."
10040 ;; Don't escape chars in internal links
10041 (if (string-match "^\\*[[:alnum:]]+" text)
10042 text
10043 (cond
10044 ((and table merge)
10045 (mapc (lambda (defchr)
10046 (unless (member defchr table)
10047 (setq table (cons defchr table))))
10048 org-link-escape-chars))
10049 ((null table)
10050 (setq table org-link-escape-chars)))
10051 (mapconcat
10052 (lambda (char)
10053 (if (or (member char table)
10054 (and (or (< char 32) (= char ?\%) (> char 126))
10055 org-url-hexify-p))
10056 (mapconcat (lambda (sequence-element)
10057 (format "%%%.2X" sequence-element))
10058 (or (encode-coding-char char 'utf-8)
10059 (error "Unable to percent escape character: %s"
10060 (char-to-string char))) "")
10061 (char-to-string char))) text "")))
10063 (defun org-link-escape-browser (text)
10064 "Escape some characters before handing over to the browser.
10065 This function is a candidate to be removed together with the
10066 constant `org-link-escape-chars-browser' once Org drops support
10067 for Emacs 24.1 and 24.2. All calls to this function will have to
10068 be replaced with `url-encode-url' which is available since Emacs
10069 24.3.1."
10070 ;; Example with the Org link
10071 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10072 ;; to open the browser with +subject:"Release 8.2" filled into the
10073 ;; query field: In this case the variable TEXT contains the
10074 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10075 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10076 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10077 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10078 (if (fboundp 'url-encode-url)
10079 (url-encode-url text)
10080 (if (org-string-match-p
10081 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10082 text)
10083 (org-link-escape text org-link-escape-chars-browser)
10084 text)))
10086 (defun org-link-unescape (str)
10087 "Unhex hexified Unicode strings as returned from the JavaScript function
10088 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
10089 (unless (and (null str) (string= "" str))
10090 (let ((pos 0) (case-fold-search t) unhexed)
10091 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
10092 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
10093 (setq str (replace-match unhexed t t str))
10094 (setq pos (+ pos (length unhexed))))))
10095 str)
10097 (defun org-link-unescape-compound (hex)
10098 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10099 Note: this function also decodes single byte encodings like
10100 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10101 (save-match-data
10102 (let* ((bytes (cdr (split-string hex "%")))
10103 (ret "")
10104 (eat 0)
10105 (sum 0))
10106 (while bytes
10107 (let* ((val (string-to-number (pop bytes) 16))
10108 (shift-xor
10109 (if (= 0 eat)
10110 (cond
10111 ((>= val 252) (cons 6 252))
10112 ((>= val 248) (cons 5 248))
10113 ((>= val 240) (cons 4 240))
10114 ((>= val 224) (cons 3 224))
10115 ((>= val 192) (cons 2 192))
10116 (t (cons 0 0)))
10117 (cons 6 128))))
10118 (if (>= val 192) (setq eat (car shift-xor)))
10119 (setq val (logxor val (cdr shift-xor)))
10120 (setq sum (+ (lsh sum (car shift-xor)) val))
10121 (if (> eat 0) (setq eat (- eat 1)))
10122 (cond
10123 ((= 0 eat) ;multi byte
10124 (setq ret (concat ret (org-char-to-string sum)))
10125 (setq sum 0))
10126 ((not bytes) ; single byte(s)
10127 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10128 ret)))
10130 (defun org-link-unescape-single-byte-sequence (hex)
10131 "Unhexify hex-encoded single byte character sequences."
10132 (mapconcat (lambda (byte)
10133 (char-to-string (string-to-number byte 16)))
10134 (cdr (split-string hex "%")) ""))
10136 (defun org-xor (a b)
10137 "Exclusive or."
10138 (if a (not b) b))
10140 (defun org-fixup-message-id-for-http (s)
10141 "Replace special characters in a message id, so it can be used in an http query."
10142 (when (string-match "%" s)
10143 (setq s (mapconcat (lambda (c)
10144 (if (eq c ?%)
10145 "%25"
10146 (char-to-string c)))
10147 s "")))
10148 (while (string-match "<" s)
10149 (setq s (replace-match "%3C" t t s)))
10150 (while (string-match ">" s)
10151 (setq s (replace-match "%3E" t t s)))
10152 (while (string-match "@" s)
10153 (setq s (replace-match "%40" t t s)))
10156 (defun org-link-prettify (link)
10157 "Return a human-readable representation of LINK.
10158 The car of LINK must be a raw link.
10159 The cdr of LINK must be either a link description or nil."
10160 (let ((desc (or (cadr link) "<no description>")))
10161 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10162 "<" (car link) ">")))
10164 ;;;###autoload
10165 (defun org-insert-link-global ()
10166 "Insert a link like Org-mode does.
10167 This command can be called in any mode to insert a link in Org-mode syntax."
10168 (interactive)
10169 (org-load-modules-maybe)
10170 (org-run-like-in-org-mode 'org-insert-link))
10172 (defun org-insert-all-links (arg &optional pre post)
10173 "Insert all links in `org-stored-links'.
10174 When a universal prefix, do not delete the links from `org-stored-links'.
10175 When `ARG' is a number, insert the last N link(s).
10176 `PRE' and `POST' are optional arguments to define a string to
10177 prepend or to append."
10178 (interactive "P")
10179 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10180 (links (copy-seq org-stored-links))
10181 (pr (or pre "- "))
10182 (po (or post "\n"))
10183 (cnt 1) l)
10184 (if (null org-stored-links)
10185 (message "No link to insert")
10186 (while (and (or (listp arg) (>= arg cnt))
10187 (setq l (if (listp arg)
10188 (pop links)
10189 (pop org-stored-links))))
10190 (setq cnt (1+ cnt))
10191 (insert pr)
10192 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10193 (insert po)))))
10195 (defun org-insert-last-stored-link (arg)
10196 "Insert the last link stored in `org-stored-links'."
10197 (interactive "p")
10198 (org-insert-all-links arg "" "\n"))
10200 (defun org-link-fontify-links-to-this-file ()
10201 "Fontify links to the current file in `org-stored-links'."
10202 (let ((f (buffer-file-name)) a b)
10203 (setq a (mapcar (lambda(l)
10204 (let ((ll (car l)))
10205 (when (and (string-match "^file:\\(.+\\)::" ll)
10206 (equal f (expand-file-name (match-string 1 ll))))
10207 ll)))
10208 org-stored-links))
10209 (when (featurep 'org-id)
10210 (setq b (mapcar (lambda(l)
10211 (let ((ll (car l)))
10212 (when (and (string-match "^id:\\(.+\\)$" ll)
10213 (equal f (expand-file-name
10214 (or (org-id-find-id-file
10215 (match-string 1 ll)) ""))))
10216 ll)))
10217 org-stored-links)))
10218 (mapcar (lambda(l)
10219 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10220 (delq nil (append a b)))))
10222 (defvar org-link-links-in-this-file nil)
10223 (defun org-insert-link (&optional complete-file link-location default-description)
10224 "Insert a link. At the prompt, enter the link.
10226 Completion can be used to insert any of the link protocol prefixes like
10227 http or ftp in use.
10229 The history can be used to select a link previously stored with
10230 `org-store-link'. When the empty string is entered (i.e. if you just
10231 press RET at the prompt), the link defaults to the most recently
10232 stored link. As SPC triggers completion in the minibuffer, you need to
10233 use M-SPC or C-q SPC to force the insertion of a space character.
10235 You will also be prompted for a description, and if one is given, it will
10236 be displayed in the buffer instead of the link.
10238 If there is already a link at point, this command will allow you to edit link
10239 and description parts.
10241 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10242 be selected using completion. The path to the file will be relative to the
10243 current directory if the file is in the current directory or a subdirectory.
10244 Otherwise, the link will be the absolute path as completed in the minibuffer
10245 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10246 option `org-link-file-path-type'.
10248 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10249 the current directory or below.
10251 With three \\[universal-argument] prefixes, negate the meaning of
10252 `org-keep-stored-link-after-insertion'.
10254 If `org-make-link-description-function' is non-nil, this function will be
10255 called with the link target, and the result will be the default
10256 link description.
10258 If the LINK-LOCATION parameter is non-nil, this value will be
10259 used as the link location instead of reading one interactively.
10261 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10262 be used as the default description."
10263 (interactive "P")
10264 (let* ((wcf (current-window-configuration))
10265 (origbuf (current-buffer))
10266 (region (if (org-region-active-p)
10267 (buffer-substring (region-beginning) (region-end))))
10268 (remove (and region (list (region-beginning) (region-end))))
10269 (desc region)
10270 tmphist ; byte-compile incorrectly complains about this
10271 (link link-location)
10272 (abbrevs org-link-abbrev-alist-local)
10273 entry file all-prefixes auto-desc)
10274 (cond
10275 (link-location) ; specified by arg, just use it.
10276 ((org-in-regexp org-bracket-link-regexp 1)
10277 ;; We do have a link at point, and we are going to edit it.
10278 (setq remove (list (match-beginning 0) (match-end 0)))
10279 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10280 (setq link (read-string "Link: "
10281 (org-link-unescape
10282 (org-match-string-no-properties 1)))))
10283 ((or (org-in-regexp org-angle-link-re)
10284 (org-in-regexp org-plain-link-re))
10285 ;; Convert to bracket link
10286 (setq remove (list (match-beginning 0) (match-end 0))
10287 link (read-string "Link: "
10288 (org-remove-angle-brackets (match-string 0)))))
10289 ((member complete-file '((4) (16)))
10290 ;; Completing read for file names.
10291 (setq link (org-file-complete-link complete-file)))
10293 ;; Read link, with completion for stored links.
10294 (org-link-fontify-links-to-this-file)
10295 (org-switch-to-buffer-other-window "*Org Links*")
10296 (with-current-buffer "*Org Links*"
10297 (erase-buffer)
10298 (insert "Insert a link.
10299 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10300 (when org-stored-links
10301 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10302 (insert (mapconcat 'org-link-prettify
10303 (reverse org-stored-links) "\n")))
10304 (goto-char (point-min)))
10305 (let ((cw (selected-window)))
10306 (select-window (get-buffer-window "*Org Links*" 'visible))
10307 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10308 (unless (pos-visible-in-window-p (point-max))
10309 (org-fit-window-to-buffer))
10310 (and (window-live-p cw) (select-window cw)))
10311 ;; Fake a link history, containing the stored links.
10312 (setq tmphist (append (mapcar 'car org-stored-links)
10313 org-insert-link-history))
10314 (setq all-prefixes (append (mapcar 'car abbrevs)
10315 (mapcar 'car org-link-abbrev-alist)
10316 org-link-types))
10317 (unwind-protect
10318 (progn
10319 (setq link
10320 (org-completing-read
10321 "Link: "
10322 (append
10323 (mapcar (lambda (x) (concat x ":"))
10324 all-prefixes)
10325 (mapcar 'car org-stored-links))
10326 nil nil nil
10327 'tmphist
10328 (caar org-stored-links)))
10329 (if (not (string-match "\\S-" link))
10330 (user-error "No link selected"))
10331 (mapc (lambda(l)
10332 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10333 org-stored-links)
10334 (if (or (member link all-prefixes)
10335 (and (equal ":" (substring link -1))
10336 (member (substring link 0 -1) all-prefixes)
10337 (setq link (substring link 0 -1))))
10338 (setq link (with-current-buffer origbuf
10339 (org-link-try-special-completion link)))))
10340 (set-window-configuration wcf)
10341 (kill-buffer "*Org Links*"))
10342 (setq entry (assoc link org-stored-links))
10343 (or entry (push link org-insert-link-history))
10344 (setq desc (or desc (nth 1 entry)))))
10346 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10347 (not org-keep-stored-link-after-insertion))
10348 (setq org-stored-links (delq (assoc link org-stored-links)
10349 org-stored-links)))
10351 (if (and (string-match org-plain-link-re link)
10352 (not (string-match org-ts-regexp link)))
10353 ;; URL-like link, normalize the use of angular brackets.
10354 (setq link (org-remove-angle-brackets link)))
10356 ;; Check if we are linking to the current file with a search
10357 ;; option If yes, simplify the link by using only the search
10358 ;; option.
10359 (when (and buffer-file-name
10360 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10361 (let* ((path (match-string 1 link))
10362 (case-fold-search nil)
10363 (search (match-string 2 link)))
10364 (save-match-data
10365 (if (equal (file-truename buffer-file-name) (file-truename path))
10366 ;; We are linking to this same file, with a search option
10367 (setq link search)))))
10369 ;; Check if we can/should use a relative path. If yes, simplify the link
10370 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10371 (let* ((type (match-string 1 link))
10372 (path (match-string 2 link))
10373 (origpath path)
10374 (case-fold-search nil))
10375 (cond
10376 ((or (eq org-link-file-path-type 'absolute)
10377 (equal complete-file '(16)))
10378 (setq path (abbreviate-file-name (expand-file-name path))))
10379 ((eq org-link-file-path-type 'noabbrev)
10380 (setq path (expand-file-name path)))
10381 ((eq org-link-file-path-type 'relative)
10382 (setq path (file-relative-name path)))
10384 (save-match-data
10385 (if (string-match (concat "^" (regexp-quote
10386 (expand-file-name
10387 (file-name-as-directory
10388 default-directory))))
10389 (expand-file-name path))
10390 ;; We are linking a file with relative path name.
10391 (setq path (substring (expand-file-name path)
10392 (match-end 0)))
10393 (setq path (abbreviate-file-name (expand-file-name path)))))))
10394 (setq link (concat type path))
10395 (if (equal desc origpath)
10396 (setq desc path))))
10398 (if org-make-link-description-function
10399 (setq desc
10400 (or (condition-case nil
10401 (funcall org-make-link-description-function link desc)
10402 (error (progn (message "Can't get link description from `%s'"
10403 (symbol-name org-make-link-description-function))
10404 (sit-for 2) nil)))
10405 (read-string "Description: " default-description)))
10406 (if default-description (setq desc default-description)
10407 (setq desc (or (and auto-desc desc)
10408 (read-string "Description: " desc)))))
10410 (unless (string-match "\\S-" desc) (setq desc nil))
10411 (if remove (apply 'delete-region remove))
10412 (insert (org-make-link-string link desc))))
10414 (defun org-link-try-special-completion (type)
10415 "If there is completion support for link type TYPE, offer it."
10416 (let ((fun (intern (concat "org-" type "-complete-link"))))
10417 (if (functionp fun)
10418 (funcall fun)
10419 (read-string "Link (no completion support): " (concat type ":")))))
10421 (defun org-file-complete-link (&optional arg)
10422 "Create a file link using completion."
10423 (let (file link)
10424 (setq file (org-iread-file-name "File: "))
10425 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10426 (pwd1 (file-name-as-directory (abbreviate-file-name
10427 (expand-file-name ".")))))
10428 (cond
10429 ((equal arg '(16))
10430 (setq link (concat
10431 "file:"
10432 (abbreviate-file-name (expand-file-name file)))))
10433 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10434 (setq link (concat "file:" (match-string 1 file))))
10435 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10436 (expand-file-name file))
10437 (setq link (concat
10438 "file:" (match-string 1 (expand-file-name file)))))
10439 (t (setq link (concat "file:" file)))))
10440 link))
10442 (defun org-iread-file-name (&rest args)
10443 "Read-file-name using `ido-mode' speedup if available.
10444 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10445 See `read-file-name' for a description of parameters."
10446 (org-without-partial-completion
10447 (if (and org-completion-use-ido
10448 (fboundp 'ido-read-file-name)
10449 (boundp 'ido-mode) ido-mode
10450 (listp (second args)))
10451 (let ((ido-enter-matching-directory nil))
10452 (apply 'ido-read-file-name args))
10453 (apply 'read-file-name args))))
10455 (defun org-completing-read (&rest args)
10456 "Completing-read with SPACE being a normal character."
10457 (let ((enable-recursive-minibuffers t)
10458 (minibuffer-local-completion-map
10459 (copy-keymap minibuffer-local-completion-map)))
10460 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10461 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10462 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10463 (apply 'org-icompleting-read args)))
10465 (defun org-completing-read-no-i (&rest args)
10466 (let (org-completion-use-ido org-completion-use-iswitchb)
10467 (apply 'org-completing-read args)))
10469 (defun org-iswitchb-completing-read (prompt choices &rest args)
10470 "Use iswitch as a completing-read replacement to choose from choices.
10471 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10472 from."
10473 (let* ((iswitchb-use-virtual-buffers nil)
10474 (iswitchb-make-buflist-hook
10475 (lambda ()
10476 (setq iswitchb-temp-buflist choices))))
10477 (iswitchb-read-buffer prompt)))
10479 (defun org-icompleting-read (&rest args)
10480 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10481 (org-without-partial-completion
10482 (if (and org-completion-use-ido
10483 (fboundp 'ido-completing-read)
10484 (boundp 'ido-mode) ido-mode
10485 (listp (second args)))
10486 (let ((ido-enter-matching-directory nil))
10487 (apply 'ido-completing-read (concat (car args))
10488 (if (consp (car (nth 1 args)))
10489 (mapcar 'car (nth 1 args))
10490 (nth 1 args))
10491 (cddr args)))
10492 (if (and org-completion-use-iswitchb
10493 (boundp 'iswitchb-mode) iswitchb-mode
10494 (listp (second args)))
10495 (apply 'org-iswitchb-completing-read (concat (car args))
10496 (if (consp (car (nth 1 args)))
10497 (mapcar 'car (nth 1 args))
10498 (nth 1 args))
10499 (cddr args))
10500 (apply 'completing-read args)))))
10502 (defun org-extract-attributes (s)
10503 "Extract the attributes cookie from a string and set as text property."
10504 (let (a attr (start 0) key value)
10505 (save-match-data
10506 (when (string-match "{{\\([^}]+\\)}}$" s)
10507 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10508 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10509 (setq key (match-string 1 a) value (match-string 2 a)
10510 start (match-end 0)
10511 attr (plist-put attr (intern key) value))))
10512 (org-add-props s nil 'org-attr attr))
10515 ;;; Opening/following a link
10517 (defvar org-link-search-failed nil)
10519 (defvar org-open-link-functions nil
10520 "Hook for functions finding a plain text link.
10521 These functions must take a single argument, the link content.
10522 They will be called for links that look like [[link text][description]]
10523 when LINK TEXT does not have a protocol like \"http:\" and does not look
10524 like a filename (e.g. \"./blue.png\").
10526 These functions will be called *before* Org attempts to resolve the
10527 link by doing text searches in the current buffer - so if you want a
10528 link \"[[target]]\" to still find \"<<target>>\", your function should
10529 handle this as a special case.
10531 When the function does handle the link, it must return a non-nil value.
10532 If it decides that it is not responsible for this link, it must return
10533 nil to indicate that that Org-mode can continue with other options
10534 like exact and fuzzy text search.")
10536 (defun org-next-link (&optional search-backward)
10537 "Move forward to the next link.
10538 If the link is in hidden text, expose it."
10539 (interactive "P")
10540 (when (and org-link-search-failed (eq this-command last-command))
10541 (goto-char (point-min))
10542 (message "Link search wrapped back to beginning of buffer"))
10543 (setq org-link-search-failed nil)
10544 (let* ((pos (point))
10545 (ct (org-context))
10546 (a (assoc :link ct))
10547 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10548 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10549 ((looking-at org-any-link-re)
10550 ;; Don't stay stuck at link without an org-link face
10551 (forward-char (if search-backward -1 1))))
10552 (if (funcall srch-fun org-any-link-re nil t)
10553 (progn
10554 (goto-char (match-beginning 0))
10555 (if (outline-invisible-p) (org-show-context)))
10556 (goto-char pos)
10557 (setq org-link-search-failed t)
10558 (message "No further link found"))))
10560 (defun org-previous-link ()
10561 "Move backward to the previous link.
10562 If the link is in hidden text, expose it."
10563 (interactive)
10564 (funcall 'org-next-link t))
10566 (defun org-translate-link (s)
10567 "Translate a link string if a translation function has been defined."
10568 (if (and org-link-translation-function
10569 (fboundp org-link-translation-function)
10570 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10571 (progn
10572 (setq s (funcall org-link-translation-function
10573 (match-string 1 s) (match-string 2 s)))
10574 (concat (car s) ":" (cdr s)))
10577 (defun org-translate-link-from-planner (type path)
10578 "Translate a link from Emacs Planner syntax so that Org can follow it.
10579 This is still an experimental function, your mileage may vary."
10580 (cond
10581 ((member type '("http" "https" "news" "ftp"))
10582 ;; standard Internet links are the same.
10583 nil)
10584 ((and (equal type "irc") (string-match "^//" path))
10585 ;; Planner has two / at the beginning of an irc link, we have 1.
10586 ;; We should have zero, actually....
10587 (setq path (substring path 1)))
10588 ((and (equal type "lisp") (string-match "^/" path))
10589 ;; Planner has a slash, we do not.
10590 (setq type "elisp" path (substring path 1)))
10591 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10592 ;; A typical message link. Planner has the id after the final slash,
10593 ;; we separate it with a hash mark
10594 (setq path (concat (match-string 1 path) "#"
10595 (org-remove-angle-brackets (match-string 2 path))))))
10596 (cons type path))
10598 (defun org-find-file-at-mouse (ev)
10599 "Open file link or URL at mouse."
10600 (interactive "e")
10601 (mouse-set-point ev)
10602 (org-open-at-point 'in-emacs))
10604 (defun org-open-at-mouse (ev)
10605 "Open file link or URL at mouse.
10606 See the docstring of `org-open-file' for details."
10607 (interactive "e")
10608 (mouse-set-point ev)
10609 (if (eq major-mode 'org-agenda-mode)
10610 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10611 (org-open-at-point))
10613 (defvar org-window-config-before-follow-link nil
10614 "The window configuration before following a link.
10615 This is saved in case the need arises to restore it.")
10617 (defvar org-open-link-marker (make-marker)
10618 "Marker pointing to the location where `org-open-at-point' was called.")
10620 ;;;###autoload
10621 (defun org-open-at-point-global ()
10622 "Follow a link like Org-mode does.
10623 This command can be called in any mode to follow a link that has
10624 Org-mode syntax."
10625 (interactive)
10626 (org-run-like-in-org-mode 'org-open-at-point))
10628 ;;;###autoload
10629 (defun org-open-link-from-string (s &optional arg reference-buffer)
10630 "Open a link in the string S, as if it was in Org-mode."
10631 (interactive "sLink: \nP")
10632 (let ((reference-buffer (or reference-buffer (current-buffer))))
10633 (with-temp-buffer
10634 (let ((org-inhibit-startup (not reference-buffer)))
10635 (org-mode)
10636 (insert s)
10637 (goto-char (point-min))
10638 (when reference-buffer
10639 (setq org-link-abbrev-alist-local
10640 (with-current-buffer reference-buffer
10641 org-link-abbrev-alist-local)))
10642 (org-open-at-point arg reference-buffer)))))
10644 (defvar org-open-at-point-functions nil
10645 "Hook that is run when following a link at point.
10647 Functions in this hook must return t if they identify and follow
10648 a link at point. If they don't find anything interesting at point,
10649 they must return nil.")
10651 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10652 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10653 (defun org-open-at-point (&optional arg reference-buffer)
10654 "Open link, timestamp, footnote or tags at point.
10656 When point is on a link, follow it. Normally, files will be
10657 opened by an appropriate application. If the optional prefix
10658 argument ARG is non-nil, Emacs will visit the file. With
10659 a double prefix argument, try to open outside of Emacs, in the
10660 application the system uses for this file type.
10662 When point is on a timestamp, open the agenda at the day
10663 specified.
10665 When point is a footnote definition, move to the first reference
10666 found. If it is on a reference, move to the associated
10667 definition.
10669 When point is on a headline, display a list of every link in the
10670 entry, so it is possible to pick one, or all, of them. If point
10671 is on a tag, call `org-tags-view' instead.
10673 When optional argument REFERENCE-BUFFER is non-nil, it should
10674 specify a buffer from where the link search should happen. This
10675 is used internally by `org-open-link-from-string'.
10677 On top of syntactically correct links, this function will open
10678 the link at point in comments or comment blocks and the first
10679 link in a property drawer line."
10680 (interactive "P")
10681 ;; On a code block, open block's results.
10682 (unless (call-interactively 'org-babel-open-src-block-result)
10683 (org-load-modules-maybe)
10684 (move-marker org-open-link-marker (point))
10685 (setq org-window-config-before-follow-link (current-window-configuration))
10686 (org-remove-occur-highlights nil nil t)
10687 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10688 (let* ((context
10689 ;; Only consider supported types, even if they are not
10690 ;; the closest one.
10691 (org-element-lineage
10692 (org-element-context)
10693 '(comment comment-block footnote-definition footnote-reference
10694 headline inlinetask link node-property timestamp)
10696 (type (org-element-type context))
10697 (value (org-element-property :value context)))
10698 (cond
10699 ((not context) (user-error "No link found"))
10700 ;; Exception: open timestamps and links in properties drawers
10701 ;; and comments.
10702 ((memq type '(comment comment-block node-property))
10703 (cond ((org-in-regexp org-any-link-re)
10704 (org-open-link-from-string (match-string-no-properties 0)))
10705 ((or (org-at-timestamp-p t) (org-at-date-range-p t))
10706 (org-follow-timestamp-link))
10707 (t (user-error "No link found"))))
10708 ;; On a headline or an inlinetask, but not on a timestamp,
10709 ;; a link, a footnote reference or on tags.
10710 ((and (memq type '(headline inlinetask))
10711 ;; Not on tags.
10712 (progn (save-excursion (beginning-of-line)
10713 (looking-at org-complex-heading-regexp))
10714 (or (not (match-beginning 5))
10715 (< (point) (match-beginning 5)))))
10716 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10717 (links (car data))
10718 (links-end (cdr data)))
10719 (if links
10720 (dolist (link (if (stringp links) (list links) links))
10721 (search-forward link nil links-end)
10722 (goto-char (match-beginning 0))
10723 (org-open-at-point))
10724 (require 'org-attach)
10725 (org-attach-reveal 'if-exists))))
10726 ;; Do nothing on white spaces after an object, unless point
10727 ;; is right after it.
10728 ((> (point)
10729 (save-excursion
10730 (goto-char (org-element-property :end context))
10731 (skip-chars-backward " \t")
10732 (point)))
10733 (user-error "No link found"))
10734 ((eq type 'timestamp) (org-follow-timestamp-link))
10735 ;; On tags within a headline or an inlinetask.
10736 ((and (memq type '(headline inlinetask))
10737 (progn (save-excursion (beginning-of-line)
10738 (looking-at org-complex-heading-regexp))
10739 (and (match-beginning 5)
10740 (>= (point) (match-beginning 5)))))
10741 (org-tags-view arg (substring (match-string 5) 0 -1)))
10742 ((eq type 'link)
10743 ;; When link is located within the description of another
10744 ;; link (e.g., an inline image), always open the parent
10745 ;; link.
10746 (let*((link (let ((up (org-element-property :parent context)))
10747 (if (eq (org-element-type up) 'link) up context)))
10748 (type (org-element-property :type link))
10749 (path (org-link-unescape (org-element-property :path link))))
10750 ;; Switch back to REFERENCE-BUFFER needed when called in
10751 ;; a temporary buffer through `org-open-link-from-string'.
10752 (with-current-buffer (or reference-buffer (current-buffer))
10753 (cond
10754 ((equal type "file")
10755 (if (string-match "[*?{]" (file-name-nondirectory path))
10756 (dired path)
10757 ;; Look into `org-link-protocols' in order to find
10758 ;; a DEDICATED-FUNCTION to open file. The function
10759 ;; will be applied on raw link instead of parsed
10760 ;; link due to the limitation in `org-add-link-type'
10761 ;; ("open" function called with a single argument).
10762 ;; If no such function is found, fallback to
10763 ;; `org-open-file'.
10765 ;; Note : "file+emacs" and "file+sys" types are
10766 ;; hard-coded in order to escape the previous
10767 ;; limitation.
10768 (let* ((option (org-element-property :search-option link))
10769 (app (org-element-property :application link))
10770 (dedicated-function
10771 (nth 1 (assoc app org-link-protocols))))
10772 (if dedicated-function
10773 (funcall dedicated-function
10774 (concat path
10775 (and option (concat "::" option))))
10776 (apply 'org-open-file
10777 path
10778 (cond (arg)
10779 ((equal app "emacs") 'emacs)
10780 ((equal app "sys") 'system))
10781 (cond ((not option) nil)
10782 ((org-string-match-p "\\`[0-9]+\\'" option)
10783 (list (string-to-number option)))
10784 (t (list nil
10785 (org-link-unescape option)))))))))
10786 ((assoc type org-link-protocols)
10787 (funcall (nth 1 (assoc type org-link-protocols)) path))
10788 ((equal type "help")
10789 (let ((f-or-v (intern path)))
10790 (cond ((fboundp f-or-v) (describe-function f-or-v))
10791 ((boundp f-or-v) (describe-variable f-or-v))
10792 (t (error "Not a known function or variable")))))
10793 ((member type '("http" "https" "ftp" "mailto" "news"))
10794 (browse-url (org-link-escape-browser (concat type ":" path))))
10795 ((equal type "doi")
10796 (browse-url
10797 (org-link-escape-browser (concat org-doi-server-url path))))
10798 ((equal type "message") (browse-url (concat type ":" path)))
10799 ((equal type "shell")
10800 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10801 (cmd path))
10802 (if (or (and (org-string-nw-p
10803 org-confirm-shell-link-not-regexp)
10804 (string-match
10805 org-confirm-shell-link-not-regexp cmd))
10806 (not org-confirm-shell-link-function)
10807 (funcall org-confirm-shell-link-function
10808 (format "Execute \"%s\" in shell? "
10809 (org-add-props cmd nil
10810 'face 'org-warning))))
10811 (progn
10812 (message "Executing %s" cmd)
10813 (shell-command cmd buf)
10814 (when (featurep 'midnight)
10815 (setq clean-buffer-list-kill-buffer-names
10816 (cons buf
10817 clean-buffer-list-kill-buffer-names))))
10818 (user-error "Abort"))))
10819 ((equal type "elisp")
10820 (let ((cmd path))
10821 (if (or (and (org-string-nw-p
10822 org-confirm-elisp-link-not-regexp)
10823 (org-string-match-p
10824 org-confirm-elisp-link-not-regexp cmd))
10825 (not org-confirm-elisp-link-function)
10826 (funcall org-confirm-elisp-link-function
10827 (format "Execute \"%s\" as elisp? "
10828 (org-add-props cmd nil
10829 'face 'org-warning))))
10830 (message "%s => %s" cmd
10831 (if (eq (string-to-char cmd) ?\()
10832 (eval (read cmd))
10833 (call-interactively (read cmd))))
10834 (user-error "Abort"))))
10835 ((equal type "id")
10836 (require 'ord-id)
10837 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10838 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10839 (unless (run-hook-with-args-until-success
10840 'org-open-link-functions path)
10841 (if (not arg) (org-mark-ring-push)
10842 (switch-to-buffer-other-window
10843 (org-get-buffer-for-internal-link (current-buffer))))
10844 (let ((cmd `(org-link-search
10845 ,(if (member type '("custom-id" "coderef"))
10846 (org-element-property :raw-link link)
10847 path)
10848 ,(cond ((equal arg '(4)) 'occur)
10849 ((equal arg '(16)) 'org-occur))
10850 ,(org-element-property :begin link))))
10851 (condition-case nil
10852 (let ((org-link-search-inhibit-query t))
10853 (eval cmd))
10854 (error (progn (widen) (eval cmd)))))))
10855 (t (browse-url-at-point))))))
10856 ;; On a footnote reference or at a footnote definition's label.
10857 ((or (eq type 'footnote-reference)
10858 (and (eq type 'footnote-definition)
10859 (save-excursion
10860 ;; Do not validate action when point is on the
10861 ;; spaces right after the footnote label, in
10862 ;; order to be on par with behaviour on links.
10863 (skip-chars-forward " \t")
10864 (let ((begin
10865 (org-element-property :contents-begin context)))
10866 (if begin (< (point) begin)
10867 (= (org-element-property :post-affiliated context)
10868 (line-beginning-position)))))))
10869 (org-footnote-action))
10870 (t (user-error "No link found")))))
10871 (move-marker org-open-link-marker nil)
10872 (run-hook-with-args 'org-follow-link-hook)))
10874 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10875 "Offer links in the current entry and return the selected link.
10876 If there is only one link, return it.
10877 If NTH is an integer, return the NTH link found.
10878 If ZERO is a string, check also this string for a link, and if
10879 there is one, return it."
10880 (with-current-buffer buffer
10881 (save-excursion
10882 (save-restriction
10883 (widen)
10884 (goto-char marker)
10885 (let ((cnt ?0)
10886 (in-emacs (if (integerp nth) nil nth))
10887 have-zero end links link c)
10888 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10889 (push (match-string 0 zero) links)
10890 (setq cnt (1- cnt) have-zero t))
10891 (save-excursion
10892 (org-back-to-heading t)
10893 (setq end (save-excursion (outline-next-heading) (point)))
10894 (while (re-search-forward org-any-link-re end t)
10895 (push (match-string 0) links))
10896 (setq links (org-uniquify (reverse links))))
10897 (cond
10898 ((null links)
10899 (message "No links"))
10900 ((equal (length links) 1)
10901 (setq link (car links)))
10902 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10903 (setq link (nth (if have-zero nth (1- nth)) links)))
10904 (t ; we have to select a link
10905 (save-excursion
10906 (save-window-excursion
10907 (delete-other-windows)
10908 (with-output-to-temp-buffer "*Select Link*"
10909 (mapc (lambda (l)
10910 (if (not (string-match org-bracket-link-regexp l))
10911 (princ (format "[%c] %s\n" (incf cnt)
10912 (org-remove-angle-brackets l)))
10913 (if (match-end 3)
10914 (princ (format "[%c] %s (%s)\n" (incf cnt)
10915 (match-string 3 l) (match-string 1 l)))
10916 (princ (format "[%c] %s\n" (incf cnt)
10917 (match-string 1 l))))))
10918 links))
10919 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10920 (message "Select link to open, RET to open all:")
10921 (setq c (read-char-exclusive))
10922 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10923 (when (equal c ?q) (user-error "Abort"))
10924 (if (equal c ?\C-m)
10925 (setq link links)
10926 (setq nth (- c ?0))
10927 (if have-zero (setq nth (1+ nth)))
10928 (unless (and (integerp nth) (>= (length links) nth))
10929 (user-error "Invalid link selection"))
10930 (setq link (nth (1- nth) links)))))
10931 (cons link end))))))
10933 ;; TODO: These functions are deprecated since `org-open-at-point'
10934 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10935 (defun org-open-file-with-system (path)
10936 "Open file at PATH using the system way of opening it."
10937 (org-open-file path 'system))
10938 (defun org-open-file-with-emacs (path)
10939 "Open file at PATH in Emacs."
10940 (org-open-file path 'emacs))
10943 ;;; File search
10945 (defvar org-create-file-search-functions nil
10946 "List of functions to construct the right search string for a file link.
10947 These functions are called in turn with point at the location to
10948 which the link should point.
10950 A function in the hook should first test if it would like to
10951 handle this file type, for example by checking the `major-mode'
10952 or the file extension. If it decides not to handle this file, it
10953 should just return nil to give other functions a chance. If it
10954 does handle the file, it must return the search string to be used
10955 when following the link. The search string will be part of the
10956 file link, given after a double colon, and `org-open-at-point'
10957 will automatically search for it. If special measures must be
10958 taken to make the search successful, another function should be
10959 added to the companion hook `org-execute-file-search-functions',
10960 which see.
10962 A function in this hook may also use `setq' to set the variable
10963 `description' to provide a suggestion for the descriptive text to
10964 be used for this link when it gets inserted into an Org-mode
10965 buffer with \\[org-insert-link].")
10967 (defvar org-execute-file-search-functions nil
10968 "List of functions to execute a file search triggered by a link.
10970 Functions added to this hook must accept a single argument, the
10971 search string that was part of the file link, the part after the
10972 double colon. The function must first check if it would like to
10973 handle this search, for example by checking the `major-mode' or
10974 the file extension. If it decides not to handle this search, it
10975 should just return nil to give other functions a chance. If it
10976 does handle the search, it must return a non-nil value to keep
10977 other functions from trying.
10979 Each function can access the current prefix argument through the
10980 variable `current-prefix-arg'. Note that a single prefix is used
10981 to force opening a link in Emacs, so it may be good to only use a
10982 numeric or double prefix to guide the search function.
10984 In case this is needed, a function in this hook can also restore
10985 the window configuration before `org-open-at-point' was called using:
10987 (set-window-configuration org-window-config-before-follow-link)")
10989 (defun org-link-search (s &optional type avoid-pos stealth)
10990 "Search for a link search option.
10991 If S is surrounded by forward slashes, it is interpreted as a
10992 regular expression. In org-mode files, this will create an `org-occur'
10993 sparse tree. In ordinary files, `occur' will be used to list matches.
10994 If the current buffer is in `dired-mode', grep will be used to search
10995 in all files. If AVOID-POS is given, ignore matches near that position.
10997 When optional argument STEALTH is non-nil, do not modify
10998 visibility around point, thus ignoring
10999 `org-show-hierarchy-above', `org-show-following-heading' and
11000 `org-show-siblings' variables."
11001 (let ((case-fold-search t)
11002 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
11003 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
11004 (append '(("") (" ") ("\t") ("\n"))
11005 org-emphasis-alist)
11006 "\\|") "\\)"))
11007 (pos (point))
11008 (pre nil) (post nil)
11009 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
11010 (cond
11011 ;; First check if there are any special search functions
11012 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11013 ;; Now try the builtin stuff
11014 ((and (equal (string-to-char s0) ?#)
11015 (> (length s0) 1)
11016 (save-excursion
11017 (goto-char (point-min))
11018 (and
11019 (re-search-forward
11020 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
11021 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
11022 (setq type 'dedicated
11023 pos (match-beginning 0))))
11024 ;; There is an exact target for this
11025 (goto-char pos)
11026 (org-back-to-heading t)))
11027 ((save-excursion
11028 (goto-char (point-min))
11029 (and
11030 (re-search-forward
11031 (concat "<<" (regexp-quote s0) ">>") nil t)
11032 (setq type 'dedicated
11033 pos (match-beginning 0))))
11034 ;; There is an exact target for this
11035 (goto-char pos))
11036 ((save-excursion
11037 (goto-char (point-min))
11038 (and
11039 (re-search-forward
11040 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
11041 (setq type 'dedicated pos (match-beginning 0))))
11042 ;; Found an element with a matching #+name affiliated keyword.
11043 (goto-char pos))
11044 ((and (string-match "^(\\(.*\\))$" s0)
11045 (save-excursion
11046 (goto-char (point-min))
11047 (and
11048 (re-search-forward
11049 (concat "[^[]" (regexp-quote
11050 (format org-coderef-label-format
11051 (match-string 1 s0))))
11052 nil t)
11053 (setq type 'dedicated
11054 pos (1+ (match-beginning 0))))))
11055 ;; There is a coderef target for this
11056 (goto-char pos))
11057 ((string-match "^/\\(.*\\)/$" s)
11058 ;; A regular expression
11059 (cond
11060 ((derived-mode-p 'org-mode)
11061 (org-occur (match-string 1 s)))
11062 (t (org-do-occur (match-string 1 s)))))
11063 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
11064 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
11065 (goto-char (point-min))
11066 (cond
11067 ((let (case-fold-search)
11068 (re-search-forward (format org-complex-heading-regexp-format
11069 (regexp-quote s))
11070 nil t))
11071 ;; OK, found a match
11072 (setq type 'dedicated)
11073 (goto-char (match-beginning 0)))
11074 ((and (not org-link-search-inhibit-query)
11075 (eq org-link-search-must-match-exact-headline 'query-to-create)
11076 (y-or-n-p "No match - create this as a new heading? "))
11077 (goto-char (point-max))
11078 (or (bolp) (newline))
11079 (insert "* " s "\n")
11080 (beginning-of-line 0))
11082 (goto-char pos)
11083 (error "No match"))))
11085 ;; A normal search string
11086 (when (equal (string-to-char s) ?*)
11087 ;; Anchor on headlines, post may include tags.
11088 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
11089 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
11090 s (substring s 1)))
11091 (remove-text-properties
11092 0 (length s)
11093 '(face nil mouse-face nil keymap nil fontified nil) s)
11094 ;; Make a series of regular expressions to find a match
11095 (setq words (org-split-string s "[ \n\r\t]+")
11097 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11098 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11099 "\\)" markers)
11100 re2a_ (concat "\\(" (mapconcat 'downcase words
11101 "[ \t\r\n]+") "\\)[ \t\r\n]")
11102 re2a (concat "[ \t\r\n]" re2a_)
11103 re4_ (concat "\\(" (mapconcat 'downcase words
11104 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11105 re4 (concat "[^a-zA-Z_]" re4_)
11107 re1 (concat pre re2 post)
11108 re3 (concat pre (if pre re4_ re4) post)
11109 re5 (concat pre ".*" re4)
11110 re2 (concat pre re2)
11111 re2a (concat pre (if pre re2a_ re2a))
11112 re4 (concat pre (if pre re4_ re4))
11113 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11114 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11115 re5 "\\)"))
11116 (cond
11117 ((eq type 'org-occur) (org-occur reall))
11118 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11119 (t (goto-char (point-min))
11120 (setq type 'fuzzy)
11121 (if (or (and (org-search-not-self 1 re0 nil t)
11122 (setq type 'dedicated))
11123 (org-search-not-self 1 re1 nil t)
11124 (org-search-not-self 1 re2 nil t)
11125 (org-search-not-self 1 re2a nil t)
11126 (org-search-not-self 1 re3 nil t)
11127 (org-search-not-self 1 re4 nil t)
11128 (org-search-not-self 1 re5 nil t))
11129 (goto-char (match-beginning 1))
11130 (goto-char pos)
11131 (error "No match"))))))
11132 (and (derived-mode-p 'org-mode)
11133 (not stealth)
11134 (org-show-context 'link-search))
11135 type))
11137 (defun org-search-not-self (group &rest args)
11138 "Execute `re-search-forward', but only accept matches that do not
11139 enclose the position of `org-open-link-marker'."
11140 (let ((m org-open-link-marker))
11141 (catch 'exit
11142 (while (apply 're-search-forward args)
11143 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11144 (goto-char (match-end group))
11145 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11146 (> (match-beginning 0) (marker-position m))
11147 (< (match-end 0) (marker-position m)))
11148 (save-match-data
11149 (or (not (org-in-regexp
11150 org-bracket-link-analytic-regexp 1))
11151 (not (match-end 4)) ; no description
11152 (and (<= (match-beginning 4) (point))
11153 (>= (match-end 4) (point))))))
11154 (throw 'exit (point))))))))
11156 (defun org-get-buffer-for-internal-link (buffer)
11157 "Return a buffer to be used for displaying the link target of internal links."
11158 (cond
11159 ((not org-display-internal-link-with-indirect-buffer)
11160 buffer)
11161 ((string-match "(Clone)$" (buffer-name buffer))
11162 (message "Buffer is already a clone, not making another one")
11163 ;; we also do not modify visibility in this case
11164 buffer)
11165 (t ; make a new indirect buffer for displaying the link
11166 (let* ((bn (buffer-name buffer))
11167 (ibn (concat bn "(Clone)"))
11168 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11169 (with-current-buffer ib (org-overview))
11170 ib))))
11172 (defun org-do-occur (regexp &optional cleanup)
11173 "Call the Emacs command `occur'.
11174 If CLEANUP is non-nil, remove the printout of the regular expression
11175 in the *Occur* buffer. This is useful if the regex is long and not useful
11176 to read."
11177 (occur regexp)
11178 (when cleanup
11179 (let ((cwin (selected-window)) win beg end)
11180 (when (setq win (get-buffer-window "*Occur*"))
11181 (select-window win))
11182 (goto-char (point-min))
11183 (when (re-search-forward "match[a-z]+" nil t)
11184 (setq beg (match-end 0))
11185 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11186 (setq end (1- (match-beginning 0)))))
11187 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11188 (goto-char (point-min))
11189 (select-window cwin))))
11191 ;;; The mark ring for links jumps
11193 (defvar org-mark-ring nil
11194 "Mark ring for positions before jumps in Org-mode.")
11195 (defvar org-mark-ring-last-goto nil
11196 "Last position in the mark ring used to go back.")
11197 ;; Fill and close the ring
11198 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11199 (loop for i from 1 to org-mark-ring-length do
11200 (push (make-marker) org-mark-ring))
11201 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11202 org-mark-ring)
11204 (defun org-mark-ring-push (&optional pos buffer)
11205 "Put the current position or POS into the mark ring and rotate it."
11206 (interactive)
11207 (setq pos (or pos (point)))
11208 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11209 (move-marker (car org-mark-ring)
11210 (or pos (point))
11211 (or buffer (current-buffer)))
11212 (message "%s"
11213 (substitute-command-keys
11214 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11216 (defun org-mark-ring-goto (&optional n)
11217 "Jump to the previous position in the mark ring.
11218 With prefix arg N, jump back that many stored positions. When
11219 called several times in succession, walk through the entire ring.
11220 Org-mode commands jumping to a different position in the current file,
11221 or to another Org-mode file, automatically push the old position
11222 onto the ring."
11223 (interactive "p")
11224 (let (p m)
11225 (if (eq last-command this-command)
11226 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11227 (setq p org-mark-ring))
11228 (setq org-mark-ring-last-goto p)
11229 (setq m (car p))
11230 (org-pop-to-buffer-same-window (marker-buffer m))
11231 (goto-char m)
11232 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11234 (defun org-remove-angle-brackets (s)
11235 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11236 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11238 (defun org-add-angle-brackets (s)
11239 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11240 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11242 (defun org-remove-double-quotes (s)
11243 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11244 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11247 ;;; Following specific links
11249 (defun org-follow-timestamp-link ()
11250 "Open an agenda view for the time-stamp date/range at point."
11251 (cond
11252 ((org-at-date-range-p t)
11253 (let ((org-agenda-start-on-weekday)
11254 (t1 (match-string 1))
11255 (t2 (match-string 2)) tt1 tt2)
11256 (setq tt1 (time-to-days (org-time-string-to-time t1))
11257 tt2 (time-to-days (org-time-string-to-time t2)))
11258 (let ((org-agenda-buffer-tmp-name
11259 (format "*Org Agenda(a:%s)"
11260 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11261 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11262 ((org-at-timestamp-p t)
11263 (let ((org-agenda-buffer-tmp-name
11264 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11265 (org-agenda-list nil (time-to-days (org-time-string-to-time
11266 (substring (match-string 1) 0 10)))
11267 1)))
11268 (t (error "This should not happen"))))
11271 ;;; Following file links
11272 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11273 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11274 (declare-function mailcap-mime-info
11275 "mailcap" (string &optional request no-decode))
11276 (defvar org-wait nil)
11277 (defun org-open-file (path &optional in-emacs line search)
11278 "Open the file at PATH.
11279 First, this expands any special file name abbreviations. Then the
11280 configuration variable `org-file-apps' is checked if it contains an
11281 entry for this file type, and if yes, the corresponding command is launched.
11283 If no application is found, Emacs simply visits the file.
11285 With optional prefix argument IN-EMACS, Emacs will visit the file.
11286 With a double \\[universal-argument] \\[universal-argument] \
11287 prefix arg, Org tries to avoid opening in Emacs
11288 and to use an external application to visit the file.
11290 Optional LINE specifies a line to go to, optional SEARCH a string
11291 to search for. If LINE or SEARCH is given, the file will be
11292 opened in Emacs, unless an entry from org-file-apps that makes
11293 use of groups in a regexp matches.
11295 If you want to change the way frames are used when following a
11296 link, please customize `org-link-frame-setup'.
11298 If the file does not exist, an error is thrown."
11299 (let* ((file (if (equal path "")
11300 buffer-file-name
11301 (substitute-in-file-name (expand-file-name path))))
11302 (file-apps (append org-file-apps (org-default-apps)))
11303 (apps (org-remove-if
11304 'org-file-apps-entry-match-against-dlink-p file-apps))
11305 (apps-dlink (org-remove-if-not
11306 'org-file-apps-entry-match-against-dlink-p file-apps))
11307 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11308 (dirp (if remp nil (file-directory-p file)))
11309 (file (if (and dirp org-open-directory-means-index-dot-org)
11310 (concat (file-name-as-directory file) "index.org")
11311 file))
11312 (a-m-a-p (assq 'auto-mode apps))
11313 (dfile (downcase file))
11314 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11315 (link (cond ((and (eq line nil)
11316 (eq search nil))
11317 file)
11318 (line
11319 (concat file "::" (number-to-string line)))
11320 (search
11321 (concat file "::" search))))
11322 (dlink (downcase link))
11323 (old-buffer (current-buffer))
11324 (old-pos (point))
11325 (old-mode major-mode)
11326 ext cmd link-match-data)
11327 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11328 (setq ext (match-string 1 dfile))
11329 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11330 (setq ext (match-string 1 dfile))))
11331 (cond
11332 ((member in-emacs '((16) system))
11333 (setq cmd (cdr (assoc 'system apps))))
11334 (in-emacs (setq cmd 'emacs))
11336 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11337 (and dirp (cdr (assoc 'directory apps)))
11338 ; first, try matching against apps-dlink
11339 ; if we get a match here, store the match data for later
11340 (let ((match (assoc-default dlink apps-dlink
11341 'string-match)))
11342 (if match
11343 (progn (setq link-match-data (match-data))
11344 match)
11345 (progn (setq in-emacs (or in-emacs line search))
11346 nil))) ; if we have no match in apps-dlink,
11347 ; always open the file in emacs if line or search
11348 ; is given (for backwards compatibility)
11349 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11350 'string-match)
11351 (cdr (assoc ext apps))
11352 (cdr (assoc t apps))))))
11353 (when (eq cmd 'system)
11354 (setq cmd (cdr (assoc 'system apps))))
11355 (when (eq cmd 'default)
11356 (setq cmd (cdr (assoc t apps))))
11357 (when (eq cmd 'mailcap)
11358 (require 'mailcap)
11359 (mailcap-parse-mailcaps)
11360 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11361 (command (mailcap-mime-info mime-type)))
11362 (if (stringp command)
11363 (setq cmd command)
11364 (setq cmd 'emacs))))
11365 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11366 (not (file-exists-p file))
11367 (not org-open-non-existing-files))
11368 (user-error "No such file: %s" file))
11369 (cond
11370 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11371 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11372 (while (string-match "['\"]%s['\"]" cmd)
11373 (setq cmd (replace-match "%s" t t cmd)))
11374 (while (string-match "%s" cmd)
11375 (setq cmd (replace-match
11376 (save-match-data
11377 (shell-quote-argument
11378 (convert-standard-filename file)))
11379 t t cmd)))
11381 ;; Replace "%1", "%2" etc. in command with group matches from regex
11382 (save-match-data
11383 (let ((match-index 1)
11384 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11385 (set-match-data link-match-data)
11386 (while (<= match-index number-of-groups)
11387 (let ((regex (concat "%" (number-to-string match-index)))
11388 (replace-with (match-string match-index dlink)))
11389 (while (string-match regex cmd)
11390 (setq cmd (replace-match replace-with t t cmd))))
11391 (setq match-index (+ match-index 1)))))
11393 (save-window-excursion
11394 (message "Running %s...done" cmd)
11395 (start-process-shell-command cmd nil cmd)
11396 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11397 ((or (stringp cmd)
11398 (eq cmd 'emacs))
11399 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11400 (widen)
11401 (if line (progn (org-goto-line line)
11402 (if (derived-mode-p 'org-mode)
11403 (org-reveal)))
11404 (if search (org-link-search search))))
11405 ((consp cmd)
11406 (let ((file (convert-standard-filename file)))
11407 (save-match-data
11408 (set-match-data link-match-data)
11409 (eval cmd))))
11410 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11411 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11412 (or (not (equal old-buffer (current-buffer)))
11413 (not (equal old-pos (point))))
11414 (org-mark-ring-push old-pos old-buffer))))
11416 (defun org-file-apps-entry-match-against-dlink-p (entry)
11417 "This function returns non-nil if `entry' uses a regular
11418 expression which should be matched against the whole link by
11419 org-open-file.
11421 It assumes that is the case when the entry uses a regular
11422 expression which has at least one grouping construct and the
11423 action is either a lisp form or a command string containing
11424 '%1', i.e. using at least one subexpression match as a
11425 parameter."
11426 (let ((selector (car entry))
11427 (action (cdr entry)))
11428 (if (stringp selector)
11429 (and (> (regexp-opt-depth selector) 0)
11430 (or (and (stringp action)
11431 (string-match "%[0-9]" action))
11432 (consp action)))
11433 nil)))
11435 (defun org-default-apps ()
11436 "Return the default applications for this operating system."
11437 (cond
11438 ((eq system-type 'darwin)
11439 org-file-apps-defaults-macosx)
11440 ((eq system-type 'windows-nt)
11441 org-file-apps-defaults-windowsnt)
11442 (t org-file-apps-defaults-gnu)))
11444 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11445 "Convert extensions to regular expressions in the cars of LIST.
11446 Also, weed out any non-string entries, because the return value is used
11447 only for regexp matching.
11448 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11449 point to the symbol `emacs', indicating that the file should
11450 be opened in Emacs."
11451 (append
11452 (delq nil
11453 (mapcar (lambda (x)
11454 (if (not (stringp (car x)))
11456 (if (string-match "\\W" (car x))
11458 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11459 list))
11460 (if add-auto-mode
11461 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11463 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11464 (defun org-file-remote-p (file)
11465 "Test whether FILE specifies a location on a remote system.
11466 Return non-nil if the location is indeed remote.
11468 For example, the filename \"/user@host:/foo\" specifies a location
11469 on the system \"/user@host:\"."
11470 (cond ((fboundp 'file-remote-p)
11471 (file-remote-p file))
11472 ((fboundp 'tramp-handle-file-remote-p)
11473 (tramp-handle-file-remote-p file))
11474 ((and (boundp 'ange-ftp-name-format)
11475 (string-match (car ange-ftp-name-format) file))
11476 t)))
11479 ;;;; Refiling
11481 (defun org-get-org-file ()
11482 "Read a filename, with default directory `org-directory'."
11483 (let ((default (or org-default-notes-file remember-data-file)))
11484 (read-file-name (format "File name [%s]: " default)
11485 (file-name-as-directory org-directory)
11486 default)))
11488 (defun org-notes-order-reversed-p ()
11489 "Check if the current file should receive notes in reversed order."
11490 (cond
11491 ((not org-reverse-note-order) nil)
11492 ((eq t org-reverse-note-order) t)
11493 ((not (listp org-reverse-note-order)) nil)
11494 (t (catch 'exit
11495 (let ((all org-reverse-note-order)
11496 entry)
11497 (while (setq entry (pop all))
11498 (if (string-match (car entry) buffer-file-name)
11499 (throw 'exit (cdr entry))))
11500 nil)))))
11502 (defvar org-refile-target-table nil
11503 "The list of refile targets, created by `org-refile'.")
11505 (defvar org-agenda-new-buffers nil
11506 "Buffers created to visit agenda files.")
11508 (defvar org-refile-cache nil
11509 "Cache for refile targets.")
11511 (defvar org-refile-markers nil
11512 "All the markers used for caching refile locations.")
11514 (defun org-refile-marker (pos)
11515 "Get a new refile marker, but only if caching is in use."
11516 (if (not org-refile-use-cache)
11518 (let ((m (make-marker)))
11519 (move-marker m pos)
11520 (push m org-refile-markers)
11521 m)))
11523 (defun org-refile-cache-clear ()
11524 "Clear the refile cache and disable all the markers."
11525 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11526 (setq org-refile-markers nil)
11527 (setq org-refile-cache nil)
11528 (message "Refile cache has been cleared"))
11530 (defun org-refile-cache-check-set (set)
11531 "Check if all the markers in the cache still have live buffers."
11532 (let (marker)
11533 (catch 'exit
11534 (while (and set (setq marker (nth 3 (pop set))))
11535 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11536 (when (and marker (null (marker-buffer marker)))
11537 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11538 (sit-for 3)
11539 (throw 'exit nil)))
11540 t)))
11542 (defun org-refile-cache-put (set &rest identifiers)
11543 "Push the refile targets SET into the cache, under IDENTIFIERS."
11544 (let* ((key (sha1 (prin1-to-string identifiers)))
11545 (entry (assoc key org-refile-cache)))
11546 (if entry
11547 (setcdr entry set)
11548 (push (cons key set) org-refile-cache))))
11550 (defun org-refile-cache-get (&rest identifiers)
11551 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11552 (cond
11553 ((not org-refile-cache) nil)
11554 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11556 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11557 org-refile-cache))))
11558 (and set (org-refile-cache-check-set set) set)))))
11560 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11561 "Produce a table with refile targets."
11562 (let ((case-fold-search nil)
11563 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11564 (entries (or org-refile-targets '((nil . (:level . 1)))))
11565 targets tgs txt re files f desc descre fast-path-p level pos0)
11566 (message "Getting targets...")
11567 (with-current-buffer (or default-buffer (current-buffer))
11568 (while (setq entry (pop entries))
11569 (setq files (car entry) desc (cdr entry))
11570 (setq fast-path-p nil)
11571 (cond
11572 ((null files) (setq files (list (current-buffer))))
11573 ((eq files 'org-agenda-files)
11574 (setq files (org-agenda-files 'unrestricted)))
11575 ((and (symbolp files) (fboundp files))
11576 (setq files (funcall files)))
11577 ((and (symbolp files) (boundp files))
11578 (setq files (symbol-value files))))
11579 (if (stringp files) (setq files (list files)))
11580 (cond
11581 ((eq (car desc) :tag)
11582 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11583 ((eq (car desc) :todo)
11584 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11585 ((eq (car desc) :regexp)
11586 (setq descre (cdr desc)))
11587 ((eq (car desc) :level)
11588 (setq descre (concat "^\\*\\{" (number-to-string
11589 (if org-odd-levels-only
11590 (1- (* 2 (cdr desc)))
11591 (cdr desc)))
11592 "\\}[ \t]")))
11593 ((eq (car desc) :maxlevel)
11594 (setq fast-path-p t)
11595 (setq descre (concat "^\\*\\{1," (number-to-string
11596 (if org-odd-levels-only
11597 (1- (* 2 (cdr desc)))
11598 (cdr desc)))
11599 "\\}[ \t]")))
11600 (t (error "Bad refiling target description %s" desc)))
11601 (while (setq f (pop files))
11602 (with-current-buffer
11603 (if (bufferp f) f (org-get-agenda-file-buffer f))
11605 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11606 (progn
11607 (if (bufferp f) (setq f (buffer-file-name
11608 (buffer-base-buffer f))))
11609 (setq f (and f (expand-file-name f)))
11610 (if (eq org-refile-use-outline-path 'file)
11611 (push (list (file-name-nondirectory f) f nil nil) tgs))
11612 (save-excursion
11613 (save-restriction
11614 (widen)
11615 (goto-char (point-min))
11616 (while (re-search-forward descre nil t)
11617 (goto-char (setq pos0 (point-at-bol)))
11618 (catch 'next
11619 (when org-refile-target-verify-function
11620 (save-match-data
11621 (or (funcall org-refile-target-verify-function)
11622 (throw 'next t))))
11623 (when (and (looking-at org-complex-heading-regexp)
11624 (not (member (match-string 4) excluded-entries))
11625 (match-string 4))
11626 (setq level (org-reduced-level
11627 (- (match-end 1) (match-beginning 1)))
11628 txt (org-link-display-format (match-string 4))
11629 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11630 re (format org-complex-heading-regexp-format
11631 (regexp-quote (match-string 4))))
11632 (when org-refile-use-outline-path
11633 (setq txt (mapconcat
11634 'org-protect-slash
11635 (append
11636 (if (eq org-refile-use-outline-path
11637 'file)
11638 (list (file-name-nondirectory
11639 (buffer-file-name
11640 (buffer-base-buffer))))
11641 (if (eq org-refile-use-outline-path
11642 'full-file-path)
11643 (list (buffer-file-name
11644 (buffer-base-buffer)))))
11645 (org-get-outline-path fast-path-p
11646 level txt)
11647 (list txt))
11648 "/")))
11649 (push (list txt f re (org-refile-marker (point)))
11650 tgs)))
11651 (when (= (point) pos0)
11652 ;; verification function has not moved point
11653 (goto-char (point-at-eol))))))))
11654 (when org-refile-use-cache
11655 (org-refile-cache-put tgs (buffer-file-name) descre))
11656 (setq targets (append tgs targets))))))
11657 (message "Getting targets...done")
11658 (nreverse targets)))
11660 (defun org-protect-slash (s)
11661 (while (string-match "/" s)
11662 (setq s (replace-match "\\" t t s)))
11665 (defvar org-olpa (make-vector 20 nil))
11667 (defun org-get-outline-path (&optional fastp level heading)
11668 "Return the outline path to the current entry, as a list.
11670 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11671 routine which makes outline path derivations for an entire file,
11672 avoiding backtracing. Refile target collection makes use of that."
11673 (if fastp
11674 (progn
11675 (if (> level 19)
11676 (error "Outline path failure, more than 19 levels"))
11677 (loop for i from level upto 19 do
11678 (aset org-olpa i nil))
11679 (prog1
11680 (delq nil (append org-olpa nil))
11681 (aset org-olpa level heading)))
11682 (let (rtn case-fold-search)
11683 (save-excursion
11684 (save-restriction
11685 (widen)
11686 (while (org-up-heading-safe)
11687 (when (looking-at org-complex-heading-regexp)
11688 (push (org-trim
11689 (replace-regexp-in-string
11690 ;; Remove statistical/checkboxes cookies
11691 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11692 (org-match-string-no-properties 4)))
11693 rtn)))
11694 rtn)))))
11696 (defun org-format-outline-path (path &optional width prefix separator)
11697 "Format the outline path PATH for display.
11698 WIDTH is the maximum number of characters that is available.
11699 PREFIX is a prefix to be included in the returned string,
11700 such as the file name.
11701 SEPARATOR is inserted between the different parts of the path,
11702 the default is \"/\"."
11703 (setq width (or width 79))
11704 (if prefix (setq width (- width (length prefix))))
11705 (if (not path)
11706 (or prefix "")
11707 (let* ((nsteps (length path))
11708 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11709 (maxwidth (if (<= total-width width)
11710 10000 ;; everything fits
11711 ;; we need to shorten the level headings
11712 (/ (- width nsteps) nsteps)))
11713 (org-odd-levels-only nil)
11714 (n 0)
11715 (total (1+ (length prefix))))
11716 (setq maxwidth (max maxwidth 10))
11717 (concat prefix
11718 (if prefix (or separator "/"))
11719 (mapconcat
11720 (lambda (h)
11721 (setq n (1+ n))
11722 (if (and (= n nsteps) (< maxwidth 10000))
11723 (setq maxwidth (- total-width total)))
11724 (if (< (length h) maxwidth)
11725 (progn (setq total (+ total (length h) 1)) h)
11726 (setq h (substring h 0 (- maxwidth 2))
11727 total (+ total maxwidth 1))
11728 (if (string-match "[ \t]+\\'" h)
11729 (setq h (substring h 0 (match-beginning 0))))
11730 (setq h (concat h "..")))
11731 (org-add-props h nil 'face
11732 (nth (% (1- n) org-n-level-faces)
11733 org-level-faces))
11735 path (or separator "/"))))))
11737 (defun org-display-outline-path (&optional file current separator just-return-string)
11738 "Display the current outline path in the echo area.
11740 If FILE is non-nil, prepend the output with the file name.
11741 If CURRENT is non-nil, append the current heading to the output.
11742 SEPARATOR is passed through to `org-format-outline-path'. It separates
11743 the different parts of the path and defaults to \"/\".
11744 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11745 (interactive "P")
11746 (let* (case-fold-search
11747 (bfn (buffer-file-name (buffer-base-buffer)))
11748 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11749 res)
11750 (if current (setq path (append path
11751 (save-excursion
11752 (org-back-to-heading t)
11753 (if (looking-at org-complex-heading-regexp)
11754 (list (match-string 4)))))))
11755 (setq res
11756 (org-format-outline-path
11757 path
11758 (1- (frame-width))
11759 (and file bfn (concat (file-name-nondirectory bfn) separator))
11760 separator))
11761 (if just-return-string
11762 (org-no-properties res)
11763 (org-unlogged-message "%s" res))))
11765 (defvar org-refile-history nil
11766 "History for refiling operations.")
11768 (defvar org-after-refile-insert-hook nil
11769 "Hook run after `org-refile' has inserted its stuff at the new location.
11770 Note that this is still *before* the stuff will be removed from
11771 the *old* location.")
11773 (defvar org-capture-last-stored-marker)
11774 (defvar org-refile-keep nil
11775 "Non-nil means `org-refile' will copy instead of refile.")
11777 (defun org-copy ()
11778 "Like `org-refile', but copy."
11779 (interactive)
11780 (let ((org-refile-keep t))
11781 (funcall 'org-refile nil nil nil "Copy")))
11783 (defun org-refile (&optional arg default-buffer rfloc msg)
11784 "Move the entry or entries at point to another heading.
11785 The list of target headings is compiled using the information in
11786 `org-refile-targets', which see.
11788 At the target location, the entry is filed as a subitem of the
11789 target heading. Depending on `org-reverse-note-order', the new
11790 subitem will either be the first or the last subitem.
11792 If there is an active region, all entries in that region will be
11793 refiled. However, the region must fulfill the requirement that
11794 the first heading sets the top-level of the moved text.
11796 With prefix arg ARG, the command will only visit the target
11797 location and not actually move anything.
11799 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11800 refiling operation has put the subtree.
11802 With a numeric prefix argument of `2', refile to the running clock.
11804 With a numeric prefix argument of `3', emulate `org-refile-keep'
11805 being set to `t' and copy to the target location, don't move it.
11806 Beware that keeping refiled entries may result in duplicated ID
11807 properties.
11809 RFLOC can be a refile location obtained in a different way.
11811 MSG is a string to replace \"Refile\" in the default prompt with
11812 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11814 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11816 If you are using target caching (see `org-refile-use-cache'), you
11817 have to clear the target cache in order to find new targets.
11818 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11819 prefix argument (`C-u C-u C-u C-c C-w')."
11820 (interactive "P")
11821 (if (member arg '(0 (64)))
11822 (org-refile-cache-clear)
11823 (let* ((actionmsg (cond (msg msg)
11824 ((equal arg 3) "Refile (and keep)")
11825 (t "Refile")))
11826 (cbuf (current-buffer))
11827 (regionp (org-region-active-p))
11828 (region-start (and regionp (region-beginning)))
11829 (region-end (and regionp (region-end)))
11830 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11831 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11832 pos it nbuf file re level reversed)
11833 (setq last-command nil)
11834 (when regionp
11835 (goto-char region-start)
11836 (or (bolp) (goto-char (point-at-bol)))
11837 (setq region-start (point))
11838 (unless (or (org-kill-is-subtree-p
11839 (buffer-substring region-start region-end))
11840 (prog1 org-refile-active-region-within-subtree
11841 (let ((s (point-at-eol)))
11842 (org-toggle-heading)
11843 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11844 (user-error "The region is not a (sequence of) subtree(s)")))
11845 (if (equal arg '(16))
11846 (org-refile-goto-last-stored)
11847 (when (or
11848 (and (equal arg 2)
11849 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11850 (prog1
11851 (setq it (list (or org-clock-heading "running clock")
11852 (buffer-file-name
11853 (marker-buffer org-clock-hd-marker))
11855 (marker-position org-clock-hd-marker)))
11856 (setq arg nil)))
11857 (setq it (or rfloc
11858 (let (heading-text)
11859 (save-excursion
11860 (unless (and arg (listp arg))
11861 (org-back-to-heading t)
11862 (setq heading-text
11863 (replace-regexp-in-string
11864 org-bracket-link-regexp
11865 "\\3"
11866 (nth 4 (org-heading-components)))))
11867 (org-refile-get-location
11868 (cond ((and arg (listp arg)) "Goto")
11869 (regionp (concat actionmsg " region to"))
11870 (t (concat actionmsg " subtree \""
11871 heading-text "\" to")))
11872 default-buffer
11873 (and (not (equal '(4) arg))
11874 org-refile-allow-creating-parent-nodes)
11875 arg))))))
11876 (setq file (nth 1 it)
11877 re (nth 2 it)
11878 pos (nth 3 it))
11879 (if (and (not arg)
11881 (equal (buffer-file-name) file)
11882 (if regionp
11883 (and (>= pos region-start)
11884 (<= pos region-end))
11885 (and (>= pos (point))
11886 (< pos (save-excursion
11887 (org-end-of-subtree t t))))))
11888 (error "Cannot refile to position inside the tree or region"))
11889 (setq nbuf (or (find-buffer-visiting file)
11890 (find-file-noselect file)))
11891 (if (and arg (not (equal arg 3)))
11892 (progn
11893 (org-pop-to-buffer-same-window nbuf)
11894 (goto-char pos)
11895 (org-show-context 'org-goto))
11896 (if regionp
11897 (progn
11898 (org-kill-new (buffer-substring region-start region-end))
11899 (org-save-markers-in-region region-start region-end))
11900 (org-copy-subtree 1 nil t))
11901 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11902 (find-file-noselect file)))
11903 (setq reversed (org-notes-order-reversed-p))
11904 (save-excursion
11905 (save-restriction
11906 (widen)
11907 (if pos
11908 (progn
11909 (goto-char pos)
11910 (looking-at org-outline-regexp)
11911 (setq level (org-get-valid-level (funcall outline-level) 1))
11912 (goto-char
11913 (if reversed
11914 (or (outline-next-heading) (point-max))
11915 (or (save-excursion (org-get-next-sibling))
11916 (org-end-of-subtree t t)
11917 (point-max)))))
11918 (setq level 1)
11919 (if (not reversed)
11920 (goto-char (point-max))
11921 (goto-char (point-min))
11922 (or (outline-next-heading) (goto-char (point-max)))))
11923 (if (not (bolp)) (newline))
11924 (org-paste-subtree level nil nil t)
11925 (when org-log-refile
11926 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11927 (unless (eq org-log-refile 'note)
11928 (save-excursion (org-add-log-note))))
11929 (and org-auto-align-tags
11930 (let ((org-loop-over-headlines-in-active-region nil))
11931 (org-set-tags nil t)))
11932 (let ((bookmark-name (plist-get org-bookmark-names-plist
11933 :last-refile)))
11934 (when bookmark-name
11935 (with-demoted-errors
11936 (bookmark-set bookmark-name))))
11937 ;; If we are refiling for capture, make sure that the
11938 ;; last-capture pointers point here
11939 (when (org-bound-and-true-p org-refile-for-capture)
11940 (let ((bookmark-name (plist-get org-bookmark-names-plist
11941 :last-capture-marker)))
11942 (when bookmark-name
11943 (with-demoted-errors
11944 (bookmark-set bookmark-name))))
11945 (move-marker org-capture-last-stored-marker (point)))
11946 (if (fboundp 'deactivate-mark) (deactivate-mark))
11947 (run-hooks 'org-after-refile-insert-hook))))
11948 (unless org-refile-keep
11949 (if regionp
11950 (delete-region (point) (+ (point) (- region-end region-start)))
11951 (delete-region
11952 (and (org-back-to-heading t) (point))
11953 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11954 (when (featurep 'org-inlinetask)
11955 (org-inlinetask-remove-END-maybe))
11956 (setq org-markers-to-move nil)
11957 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11959 (defun org-refile-goto-last-stored ()
11960 "Go to the location where the last refile was stored."
11961 (interactive)
11962 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11963 (message "This is the location of the last refile"))
11965 (defun org-refile--get-location (refloc tbl)
11966 "When user refile to REFLOC, find the associated target in TBL.
11967 Also check `org-refile-target-table'."
11968 (car (delq
11970 (mapcar
11971 (lambda (r) (or (assoc r tbl)
11972 (assoc r org-refile-target-table)))
11973 (list (replace-regexp-in-string "/$" "" refloc)
11974 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11976 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11977 no-exclude)
11978 "Prompt the user for a refile location, using PROMPT.
11979 PROMPT should not be suffixed with a colon and a space, because
11980 this function appends the default value from
11981 `org-refile-history' automatically, if that is not empty.
11982 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11983 this is used for the GOTO interface."
11984 (let ((org-refile-targets org-refile-targets)
11985 (org-refile-use-outline-path org-refile-use-outline-path)
11986 excluded-entries)
11987 (when (and (derived-mode-p 'org-mode)
11988 (not org-refile-use-cache)
11989 (not no-exclude))
11990 (org-map-tree
11991 (lambda()
11992 (setq excluded-entries
11993 (append excluded-entries (list (org-get-heading t t)))))))
11994 (setq org-refile-target-table
11995 (org-refile-get-targets default-buffer excluded-entries)))
11996 (unless org-refile-target-table
11997 (user-error "No refile targets"))
11998 (let* ((cbuf (current-buffer))
11999 (partial-completion-mode nil)
12000 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12001 (cfunc (if (and org-refile-use-outline-path
12002 org-outline-path-complete-in-steps)
12003 'org-olpath-completing-read
12004 'org-icompleting-read))
12005 (extra (if org-refile-use-outline-path "/" ""))
12006 (cbnex (concat (buffer-name) extra))
12007 (filename (and cfn (expand-file-name cfn)))
12008 (tbl (mapcar
12009 (lambda (x)
12010 (if (and (not (member org-refile-use-outline-path
12011 '(file full-file-path)))
12012 (not (equal filename (nth 1 x))))
12013 (cons (concat (car x) extra " ("
12014 (file-name-nondirectory (nth 1 x)) ")")
12015 (cdr x))
12016 (cons (concat (car x) extra) (cdr x))))
12017 org-refile-target-table))
12018 (completion-ignore-case t)
12019 cdef
12020 (prompt (concat prompt
12021 (or (and (car org-refile-history)
12022 (concat " (default " (car org-refile-history) ")"))
12023 (and (assoc cbnex tbl) (setq cdef cbnex)
12024 (concat " (default " cbnex ")"))) ": "))
12025 pa answ parent-target child parent old-hist)
12026 (setq old-hist org-refile-history)
12027 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12028 nil 'org-refile-history (or cdef (car org-refile-history))))
12029 (if (setq pa (org-refile--get-location answ tbl))
12030 (progn
12031 (org-refile-check-position pa)
12032 (when (or (not org-refile-history)
12033 (not (eq old-hist org-refile-history))
12034 (not (equal (car pa) (car org-refile-history))))
12035 (setq org-refile-history
12036 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12037 org-refile-history
12038 (cdr org-refile-history))))
12039 (if (equal (car org-refile-history) (nth 1 org-refile-history))
12040 (pop org-refile-history)))
12042 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12043 (progn
12044 (setq parent (match-string 1 answ)
12045 child (match-string 2 answ))
12046 (setq parent-target (org-refile--get-location parent tbl))
12047 (when (and parent-target
12048 (or (eq new-nodes t)
12049 (and (eq new-nodes 'confirm)
12050 (y-or-n-p (format "Create new node \"%s\"? "
12051 child)))))
12052 (org-refile-new-child parent-target child)))
12053 (user-error "Invalid target location")))))
12055 (declare-function org-string-nw-p "org-macs" (s))
12056 (defun org-refile-check-position (refile-pointer)
12057 "Check if the refile pointer matches the headline to which it points."
12058 (let* ((file (nth 1 refile-pointer))
12059 (re (nth 2 refile-pointer))
12060 (pos (nth 3 refile-pointer))
12061 buffer)
12062 (if (and (not (markerp pos)) (not file))
12063 (user-error "Please indicate a target file in the refile path")
12064 (when (org-string-nw-p re)
12065 (setq buffer (if (markerp pos)
12066 (marker-buffer pos)
12067 (or (find-buffer-visiting file)
12068 (find-file-noselect file))))
12069 (with-current-buffer buffer
12070 (save-excursion
12071 (save-restriction
12072 (widen)
12073 (goto-char pos)
12074 (beginning-of-line 1)
12075 (unless (org-looking-at-p re)
12076 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12078 (defun org-refile-new-child (parent-target child)
12079 "Use refile target PARENT-TARGET to add new CHILD below it."
12080 (unless parent-target
12081 (error "Cannot find parent for new node"))
12082 (let ((file (nth 1 parent-target))
12083 (pos (nth 3 parent-target))
12084 level)
12085 (with-current-buffer (or (find-buffer-visiting file)
12086 (find-file-noselect file))
12087 (save-excursion
12088 (save-restriction
12089 (widen)
12090 (if pos
12091 (goto-char pos)
12092 (goto-char (point-max))
12093 (if (not (bolp)) (newline)))
12094 (when (looking-at org-outline-regexp)
12095 (setq level (funcall outline-level))
12096 (org-end-of-subtree t t))
12097 (org-back-over-empty-lines)
12098 (insert "\n" (make-string
12099 (if pos (org-get-valid-level level 1) 1) ?*)
12100 " " child "\n")
12101 (beginning-of-line 0)
12102 (list (concat (car parent-target) "/" child) file "" (point)))))))
12104 (defun org-olpath-completing-read (prompt collection &rest args)
12105 "Read an outline path like a file name."
12106 (let ((thetable collection)
12107 (org-completion-use-ido nil) ; does not work with ido.
12108 (org-completion-use-iswitchb nil)) ; or iswitchb
12109 (apply
12110 'org-icompleting-read prompt
12111 (lambda (string predicate &optional flag)
12112 (let (rtn r f (l (length string)))
12113 (cond
12114 ((eq flag nil)
12115 ;; try completion
12116 (try-completion string thetable))
12117 ((eq flag t)
12118 ;; all-completions
12119 (setq rtn (all-completions string thetable predicate))
12120 (mapcar
12121 (lambda (x)
12122 (setq r (substring x l))
12123 (if (string-match " ([^)]*)$" x)
12124 (setq f (match-string 0 x))
12125 (setq f ""))
12126 (if (string-match "/" r)
12127 (concat string (substring r 0 (match-end 0)) f)
12129 rtn))
12130 ((eq flag 'lambda)
12131 ;; exact match?
12132 (assoc string thetable)))))
12133 args)))
12135 ;;;; Dynamic blocks
12137 (defun org-find-dblock (name)
12138 "Find the first dynamic block with name NAME in the buffer.
12139 If not found, stay at current position and return nil."
12140 (let ((case-fold-search t) pos)
12141 (save-excursion
12142 (goto-char (point-min))
12143 (setq pos (and (re-search-forward
12144 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12145 (match-beginning 0))))
12146 (if pos (goto-char pos))
12147 pos))
12149 (defun org-create-dblock (plist)
12150 "Create a dynamic block section, with parameters taken from PLIST.
12151 PLIST must contain a :name entry which is used as the name of the block."
12152 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12153 (end-of-line 1)
12154 (newline))
12155 (let ((col (current-column))
12156 (name (plist-get plist :name)))
12157 (insert "#+BEGIN: " name)
12158 (while plist
12159 (if (eq (car plist) :name)
12160 (setq plist (cddr plist))
12161 (insert " " (prin1-to-string (pop plist)))))
12162 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12163 (beginning-of-line -2)))
12165 (defun org-prepare-dblock ()
12166 "Prepare dynamic block for refresh.
12167 This empties the block, puts the cursor at the insert position and returns
12168 the property list including an extra property :name with the block name."
12169 (unless (looking-at org-dblock-start-re)
12170 (user-error "Not at a dynamic block"))
12171 (let* ((begdel (1+ (match-end 0)))
12172 (name (org-no-properties (match-string 1)))
12173 (params (append (list :name name)
12174 (read (concat "(" (match-string 3) ")")))))
12175 (save-excursion
12176 (beginning-of-line 1)
12177 (skip-chars-forward " \t")
12178 (setq params (plist-put params :indentation-column (current-column))))
12179 (unless (re-search-forward org-dblock-end-re nil t)
12180 (error "Dynamic block not terminated"))
12181 (setq params
12182 (append params
12183 (list :content (buffer-substring
12184 begdel (match-beginning 0)))))
12185 (delete-region begdel (match-beginning 0))
12186 (goto-char begdel)
12187 (open-line 1)
12188 params))
12190 (defun org-map-dblocks (&optional command)
12191 "Apply COMMAND to all dynamic blocks in the current buffer.
12192 If COMMAND is not given, use `org-update-dblock'."
12193 (let ((cmd (or command 'org-update-dblock)))
12194 (save-excursion
12195 (goto-char (point-min))
12196 (while (re-search-forward org-dblock-start-re nil t)
12197 (goto-char (match-beginning 0))
12198 (save-excursion
12199 (condition-case nil
12200 (funcall cmd)
12201 (error (message "Error during update of dynamic block"))))
12202 (unless (re-search-forward org-dblock-end-re nil t)
12203 (error "Dynamic block not terminated"))))))
12205 (defun org-dblock-update (&optional arg)
12206 "User command for updating dynamic blocks.
12207 Update the dynamic block at point. With prefix ARG, update all dynamic
12208 blocks in the buffer."
12209 (interactive "P")
12210 (if arg
12211 (org-update-all-dblocks)
12212 (or (looking-at org-dblock-start-re)
12213 (org-beginning-of-dblock))
12214 (org-update-dblock)))
12216 (defun org-update-dblock ()
12217 "Update the dynamic block at point.
12218 This means to empty the block, parse for parameters and then call
12219 the correct writing function."
12220 (interactive)
12221 (save-excursion
12222 (let* ((win (selected-window))
12223 (pos (point))
12224 (line (org-current-line))
12225 (params (org-prepare-dblock))
12226 (name (plist-get params :name))
12227 (indent (plist-get params :indentation-column))
12228 (cmd (intern (concat "org-dblock-write:" name))))
12229 (message "Updating dynamic block `%s' at line %d..." name line)
12230 (funcall cmd params)
12231 (message "Updating dynamic block `%s' at line %d...done" name line)
12232 (goto-char pos)
12233 (when (and indent (> indent 0))
12234 (setq indent (make-string indent ?\ ))
12235 (save-excursion
12236 (select-window win)
12237 (org-beginning-of-dblock)
12238 (forward-line 1)
12239 (while (not (looking-at org-dblock-end-re))
12240 (insert indent)
12241 (beginning-of-line 2))
12242 (when (looking-at org-dblock-end-re)
12243 (and (looking-at "[ \t]+")
12244 (replace-match ""))
12245 (insert indent)))))))
12247 (defun org-beginning-of-dblock ()
12248 "Find the beginning of the dynamic block at point.
12249 Error if there is no such block at point."
12250 (let ((pos (point))
12251 beg)
12252 (end-of-line 1)
12253 (if (and (re-search-backward org-dblock-start-re nil t)
12254 (setq beg (match-beginning 0))
12255 (re-search-forward org-dblock-end-re nil t)
12256 (> (match-end 0) pos))
12257 (goto-char beg)
12258 (goto-char pos)
12259 (error "Not in a dynamic block"))))
12261 (defun org-update-all-dblocks ()
12262 "Update all dynamic blocks in the buffer.
12263 This function can be used in a hook."
12264 (interactive)
12265 (when (derived-mode-p 'org-mode)
12266 (org-map-dblocks 'org-update-dblock)))
12269 ;;;; Completion
12271 (declare-function org-export-backend-name "org-export" (cl-x))
12272 (declare-function org-export-backend-options "org-export" (cl-x))
12273 (defun org-get-export-keywords ()
12274 "Return a list of all currently understood export keywords.
12275 Export keywords include options, block names, attributes and
12276 keywords relative to each registered export back-end."
12277 (let (keywords)
12278 (dolist (backend
12279 (org-bound-and-true-p org-export--registered-backends)
12280 (delq nil keywords))
12281 ;; Back-end name (for keywords, like #+LATEX:)
12282 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12283 (dolist (option-entry (org-export-backend-options backend))
12284 ;; Back-end options.
12285 (push (nth 1 option-entry) keywords)))))
12287 (defconst org-options-keywords
12288 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12289 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12290 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12291 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12292 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12294 (defcustom org-structure-template-alist
12295 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12296 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12297 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12298 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12299 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12300 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12301 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX")
12302 ("L" "#+LaTeX: ")
12303 ("h" "#+BEGIN_HTML\n?\n#+END_HTML")
12304 ("H" "#+HTML: ")
12305 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
12306 ("A" "#+ASCII: ")
12307 ("i" "#+INDEX: ?")
12308 ("I" "#+INCLUDE: %file ?"))
12309 "Structure completion elements.
12310 This is a list of abbreviation keys and values. The value gets inserted
12311 if you type `<' followed by the key and then press the completion key,
12312 usually `TAB'. %file will be replaced by a file name after prompting
12313 for the file using completion. The cursor will be placed at the position
12314 of the `?` in the template.
12315 There are two templates for each key, the first uses the original Org syntax,
12316 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12317 the default when the /org-mtags.el/ module has been loaded. See also the
12318 variable `org-mtags-prefer-muse-templates'."
12319 :group 'org-completion
12320 :type '(repeat
12321 (list
12322 (string :tag "Key")
12323 (string :tag "Template")))
12324 :version "25.1"
12325 :package-version '(Org . "8.3"))
12327 (defun org-try-structure-completion ()
12328 "Try to complete a structure template before point.
12329 This looks for strings like \"<e\" on an otherwise empty line and
12330 expands them."
12331 (let ((l (buffer-substring (point-at-bol) (point)))
12333 (when (and (looking-at "[ \t]*$")
12334 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12335 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12336 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12337 (match-beginning 1)) a)
12338 t)))
12340 (defun org-complete-expand-structure-template (start cell)
12341 "Expand a structure template."
12342 (let ((rpl (nth 1 cell))
12343 (ind ""))
12344 (delete-region start (point))
12345 (when (string-match "\\`[ \t]*#\\+" rpl)
12346 (cond
12347 ((bolp))
12348 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12349 (setq ind (buffer-substring (point-at-bol) (point))))
12350 (t (newline))))
12351 (setq start (point))
12352 (if (string-match "%file" rpl)
12353 (setq rpl (replace-match
12354 (concat
12355 "\""
12356 (save-match-data
12357 (abbreviate-file-name (read-file-name "Include file: ")))
12358 "\"")
12359 t t rpl)))
12360 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12361 (concat "\n" ind)))
12362 (insert rpl)
12363 (if (re-search-backward "\\?" start t) (delete-char 1))))
12365 ;;;; TODO, DEADLINE, Comments
12367 (defun org-toggle-comment ()
12368 "Change the COMMENT state of an entry."
12369 (interactive)
12370 (save-excursion
12371 (org-back-to-heading)
12372 (looking-at org-complex-heading-regexp)
12373 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12374 (skip-chars-forward " \t")
12375 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12376 (if (org-in-commented-heading-p t)
12377 (delete-region (point)
12378 (progn (search-forward " " (line-end-position) 'move)
12379 (skip-chars-forward " \t")
12380 (point)))
12381 (insert org-comment-string)
12382 (unless (eolp) (insert " ")))))
12384 (defvar org-last-todo-state-is-todo nil
12385 "This is non-nil when the last TODO state change led to a TODO state.
12386 If the last change removed the TODO tag or switched to DONE, then
12387 this is nil.")
12389 (defvar org-setting-tags nil) ; dynamically skipped
12391 (defvar org-todo-setup-filter-hook nil
12392 "Hook for functions that pre-filter todo specs.
12393 Each function takes a todo spec and returns either nil or the spec
12394 transformed into canonical form." )
12396 (defvar org-todo-get-default-hook nil
12397 "Hook for functions that get a default item for todo.
12398 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12399 nil or a string to be used for the todo mark." )
12401 (defvar org-agenda-headline-snapshot-before-repeat)
12403 (defun org-current-effective-time ()
12404 "Return current time adjusted for `org-extend-today-until' variable."
12405 (let* ((ct (org-current-time))
12406 (dct (decode-time ct))
12407 (ct1
12408 (cond
12409 (org-use-last-clock-out-time-as-effective-time
12410 (or (org-clock-get-last-clock-out-time) ct))
12411 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12412 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12413 (t ct))))
12414 ct1))
12416 (defun org-todo-yesterday (&optional arg)
12417 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12418 (interactive "P")
12419 (if (eq major-mode 'org-agenda-mode)
12420 (apply 'org-agenda-todo-yesterday arg)
12421 (let* ((org-use-effective-time t)
12422 (hour (third (decode-time
12423 (org-current-time))))
12424 (org-extend-today-until (1+ hour)))
12425 (org-todo arg))))
12427 (defvar org-block-entry-blocking ""
12428 "First entry preventing the TODO state change.")
12430 (defun org-cancel-repeater ()
12431 "Cancel a repeater by setting its numeric value to zero."
12432 (interactive)
12433 (save-excursion
12434 (org-back-to-heading t)
12435 (let ((bound1 (point))
12436 (bound0 (save-excursion (outline-next-heading) (point))))
12437 (when (re-search-forward
12438 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12439 org-deadline-time-regexp "\\)\\|\\("
12440 org-ts-regexp "\\)")
12441 bound0 t)
12442 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12443 (replace-match "0" t nil nil 1))))))
12445 (defun org-todo (&optional arg)
12446 "Change the TODO state of an item.
12447 The state of an item is given by a keyword at the start of the heading,
12448 like
12449 *** TODO Write paper
12450 *** DONE Call mom
12452 The different keywords are specified in the variable `org-todo-keywords'.
12453 By default the available states are \"TODO\" and \"DONE\".
12454 So for this example: when the item starts with TODO, it is changed to DONE.
12455 When it starts with DONE, the DONE is removed. And when neither TODO nor
12456 DONE are present, add TODO at the beginning of the heading.
12458 With \\[universal-argument] prefix arg, use completion to determine the new \
12459 state.
12460 With numeric prefix arg, switch to that state.
12461 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12462 keywords (nextset).
12463 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12464 With a numeric prefix arg of 0, inhibit note taking for the change.
12465 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12467 When called through ELisp, arg is also interpreted in the following way:
12468 'none -> empty state
12469 \"\"(empty string) -> switch to empty state
12470 'done -> switch to DONE
12471 'nextset -> switch to the next set of keywords
12472 'previousset -> switch to the previous set of keywords
12473 \"WAITING\" -> switch to the specified keyword, but only if it
12474 really is a member of `org-todo-keywords'."
12475 (interactive "P")
12476 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12477 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12478 'region-start-level 'region))
12479 org-loop-over-headlines-in-active-region)
12480 (org-map-entries
12481 `(org-todo ,arg)
12482 org-loop-over-headlines-in-active-region
12483 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12484 (if (equal arg '(16)) (setq arg 'nextset))
12485 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12486 (let ((org-blocker-hook org-blocker-hook)
12487 commentp
12488 case-fold-search)
12489 (when (equal arg '(64))
12490 (setq arg nil org-blocker-hook nil))
12491 (when (and org-blocker-hook
12492 (or org-inhibit-blocking
12493 (org-entry-get nil "NOBLOCKING")))
12494 (setq org-blocker-hook nil))
12495 (save-excursion
12496 (catch 'exit
12497 (org-back-to-heading t)
12498 (when (org-in-commented-heading-p t)
12499 (org-toggle-comment)
12500 (setq commentp t))
12501 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12502 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12503 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12504 (let* ((match-data (match-data))
12505 (startpos (point-at-bol))
12506 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12507 (org-log-done org-log-done)
12508 (org-log-repeat org-log-repeat)
12509 (org-todo-log-states org-todo-log-states)
12510 (org-inhibit-logging
12511 (if (equal arg 0)
12512 (progn (setq arg nil) 'note) org-inhibit-logging))
12513 (this (match-string 1))
12514 (hl-pos (match-beginning 0))
12515 (head (org-get-todo-sequence-head this))
12516 (ass (assoc head org-todo-kwd-alist))
12517 (interpret (nth 1 ass))
12518 (done-word (nth 3 ass))
12519 (final-done-word (nth 4 ass))
12520 (org-last-state (or this ""))
12521 (completion-ignore-case t)
12522 (member (member this org-todo-keywords-1))
12523 (tail (cdr member))
12524 (org-state (cond
12525 ((and org-todo-key-trigger
12526 (or (and (equal arg '(4))
12527 (eq org-use-fast-todo-selection 'prefix))
12528 (and (not arg) org-use-fast-todo-selection
12529 (not (eq org-use-fast-todo-selection
12530 'prefix)))))
12531 ;; Use fast selection
12532 (org-fast-todo-selection))
12533 ((and (equal arg '(4))
12534 (or (not org-use-fast-todo-selection)
12535 (not org-todo-key-trigger)))
12536 ;; Read a state with completion
12537 (org-icompleting-read
12538 "State: " (mapcar 'list org-todo-keywords-1)
12539 nil t))
12540 ((eq arg 'right)
12541 (if this
12542 (if tail (car tail) nil)
12543 (car org-todo-keywords-1)))
12544 ((eq arg 'left)
12545 (if (equal member org-todo-keywords-1)
12547 (if this
12548 (nth (- (length org-todo-keywords-1)
12549 (length tail) 2)
12550 org-todo-keywords-1)
12551 (org-last org-todo-keywords-1))))
12552 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12553 (setq arg nil))) ; hack to fall back to cycling
12554 (arg
12555 ;; user or caller requests a specific state
12556 (cond
12557 ((equal arg "") nil)
12558 ((eq arg 'none) nil)
12559 ((eq arg 'done) (or done-word (car org-done-keywords)))
12560 ((eq arg 'nextset)
12561 (or (car (cdr (member head org-todo-heads)))
12562 (car org-todo-heads)))
12563 ((eq arg 'previousset)
12564 (let ((org-todo-heads (reverse org-todo-heads)))
12565 (or (car (cdr (member head org-todo-heads)))
12566 (car org-todo-heads))))
12567 ((car (member arg org-todo-keywords-1)))
12568 ((stringp arg)
12569 (user-error "State `%s' not valid in this file" arg))
12570 ((nth (1- (prefix-numeric-value arg))
12571 org-todo-keywords-1))))
12572 ((null member) (or head (car org-todo-keywords-1)))
12573 ((equal this final-done-word) nil) ;; -> make empty
12574 ((null tail) nil) ;; -> first entry
12575 ((memq interpret '(type priority))
12576 (if (eq this-command last-command)
12577 (car tail)
12578 (if (> (length tail) 0)
12579 (or done-word (car org-done-keywords))
12580 nil)))
12582 (car tail))))
12583 (org-state (or
12584 (run-hook-with-args-until-success
12585 'org-todo-get-default-hook org-state org-last-state)
12586 org-state))
12587 (next (if org-state (concat " " org-state " ") " "))
12588 (change-plist (list :type 'todo-state-change :from this :to org-state
12589 :position startpos))
12590 dolog now-done-p)
12591 (when org-blocker-hook
12592 (setq org-last-todo-state-is-todo
12593 (not (member this org-done-keywords)))
12594 (unless (save-excursion
12595 (save-match-data
12596 (org-with-wide-buffer
12597 (run-hook-with-args-until-failure
12598 'org-blocker-hook change-plist))))
12599 (if (org-called-interactively-p 'interactive)
12600 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12601 this org-state org-block-entry-blocking)
12602 ;; fail silently
12603 (message "TODO state change from %s to %s blocked (by \"%s\")"
12604 this org-state org-block-entry-blocking)
12605 (throw 'exit nil))))
12606 (store-match-data match-data)
12607 (replace-match next t t)
12608 (cond ((equal this org-state)
12609 (message "TODO state was already %s" (org-trim next)))
12610 ((pos-visible-in-window-p hl-pos)
12611 (message "TODO state changed to %s" (org-trim next))))
12612 (unless head
12613 (setq head (org-get-todo-sequence-head org-state)
12614 ass (assoc head org-todo-kwd-alist)
12615 interpret (nth 1 ass)
12616 done-word (nth 3 ass)
12617 final-done-word (nth 4 ass)))
12618 (when (memq arg '(nextset previousset))
12619 (message "Keyword-Set %d/%d: %s"
12620 (- (length org-todo-sets) -1
12621 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12622 (length org-todo-sets)
12623 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12624 (setq org-last-todo-state-is-todo
12625 (not (member org-state org-done-keywords)))
12626 (setq now-done-p (and (member org-state org-done-keywords)
12627 (not (member this org-done-keywords))))
12628 (and logging (org-local-logging logging))
12629 (when (and (or org-todo-log-states org-log-done)
12630 (not (eq org-inhibit-logging t))
12631 (not (memq arg '(nextset previousset))))
12632 ;; we need to look at recording a time and note
12633 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12634 (nth 2 (assoc this org-todo-log-states))))
12635 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12636 (setq dolog 'time))
12637 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12638 (and org-state
12639 (member org-state org-not-done-keywords)
12640 (not (member this org-not-done-keywords))))
12641 ;; This is now a todo state and was not one before
12642 ;; If there was a CLOSED time stamp, get rid of it.
12643 (org-add-planning-info nil nil 'closed))
12644 (when (and now-done-p org-log-done)
12645 ;; It is now done, and it was not done before
12646 (org-add-planning-info 'closed (org-current-effective-time))
12647 (if (and (not dolog) (eq 'note org-log-done))
12648 (org-add-log-setup 'done org-state this 'findpos 'note)))
12649 (when (and org-state dolog)
12650 ;; This is a non-nil state, and we need to log it
12651 (org-add-log-setup 'state org-state this 'findpos dolog)))
12652 ;; Fixup tag positioning
12653 (org-todo-trigger-tag-changes org-state)
12654 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12655 (when org-provide-todo-statistics
12656 (org-update-parent-todo-statistics))
12657 (run-hooks 'org-after-todo-state-change-hook)
12658 (if (and arg (not (member org-state org-done-keywords)))
12659 (setq head (org-get-todo-sequence-head org-state)))
12660 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12661 ;; Do we need to trigger a repeat?
12662 (when now-done-p
12663 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12664 ;; This is for the agenda, take a snapshot of the headline.
12665 (save-match-data
12666 (setq org-agenda-headline-snapshot-before-repeat
12667 (org-get-heading))))
12668 (org-auto-repeat-maybe org-state))
12669 ;; Fixup cursor location if close to the keyword
12670 (if (and (outline-on-heading-p)
12671 (not (bolp))
12672 (save-excursion (beginning-of-line 1)
12673 (looking-at org-todo-line-regexp))
12674 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12675 (progn
12676 (goto-char (or (match-end 2) (match-end 1)))
12677 (and (looking-at " ") (just-one-space))))
12678 (when org-trigger-hook
12679 (save-excursion
12680 (run-hook-with-args 'org-trigger-hook change-plist)))
12681 (when commentp (org-toggle-comment))))))))
12683 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12684 "Block turning an entry into a TODO, using the hierarchy.
12685 This checks whether the current task should be blocked from state
12686 changes. Such blocking occurs when:
12688 1. The task has children which are not all in a completed state.
12690 2. A task has a parent with the property :ORDERED:, and there
12691 are siblings prior to the current task with incomplete
12692 status.
12694 3. The parent of the task is blocked because it has siblings that should
12695 be done first, or is child of a block grandparent TODO entry."
12697 (if (not org-enforce-todo-dependencies)
12698 t ; if locally turned off don't block
12699 (catch 'dont-block
12700 ;; If this is not a todo state change, or if this entry is already DONE,
12701 ;; do not block
12702 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12703 (member (plist-get change-plist :from)
12704 (cons 'done org-done-keywords))
12705 (member (plist-get change-plist :to)
12706 (cons 'todo org-not-done-keywords))
12707 (not (plist-get change-plist :to)))
12708 (throw 'dont-block t))
12709 ;; If this task has children, and any are undone, it's blocked
12710 (save-excursion
12711 (org-back-to-heading t)
12712 (let ((this-level (funcall outline-level)))
12713 (outline-next-heading)
12714 (let ((child-level (funcall outline-level)))
12715 (while (and (not (eobp))
12716 (> child-level this-level))
12717 ;; this todo has children, check whether they are all
12718 ;; completed
12719 (if (and (not (org-entry-is-done-p))
12720 (org-entry-is-todo-p))
12721 (progn (setq org-block-entry-blocking (org-get-heading))
12722 (throw 'dont-block nil)))
12723 (outline-next-heading)
12724 (setq child-level (funcall outline-level))))))
12725 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12726 ;; any previous siblings are undone, it's blocked
12727 (save-excursion
12728 (org-back-to-heading t)
12729 (let* ((pos (point))
12730 (parent-pos (and (org-up-heading-safe) (point))))
12731 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12732 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12733 (forward-line 1)
12734 (re-search-forward org-not-done-heading-regexp pos t))
12735 (setq org-block-entry-blocking (match-string 0))
12736 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12737 ;; Search further up the hierarchy, to see if an ancestor is blocked
12738 (while t
12739 (goto-char parent-pos)
12740 (if (not (looking-at org-not-done-heading-regexp))
12741 (throw 'dont-block t)) ; do not block, parent is not a TODO
12742 (setq pos (point))
12743 (setq parent-pos (and (org-up-heading-safe) (point)))
12744 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12745 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12746 (forward-line 1)
12747 (re-search-forward org-not-done-heading-regexp pos t)
12748 (setq org-block-entry-blocking (org-get-heading)))
12749 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12751 (defcustom org-track-ordered-property-with-tag nil
12752 "Should the ORDERED property also be shown as a tag?
12753 The ORDERED property decides if an entry should require subtasks to be
12754 completed in sequence. Since a property is not very visible, setting
12755 this option means that toggling the ORDERED property with the command
12756 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12757 not relevant for the behavior, but it makes things more visible.
12759 Note that toggling the tag with tags commands will not change the property
12760 and therefore not influence behavior!
12762 This can be t, meaning the tag ORDERED should be used, It can also be a
12763 string to select a different tag for this task."
12764 :group 'org-todo
12765 :type '(choice
12766 (const :tag "No tracking" nil)
12767 (const :tag "Track with ORDERED tag" t)
12768 (string :tag "Use other tag")))
12770 (defun org-toggle-ordered-property ()
12771 "Toggle the ORDERED property of the current entry.
12772 For better visibility, you can track the value of this property with a tag.
12773 See variable `org-track-ordered-property-with-tag'."
12774 (interactive)
12775 (let* ((t1 org-track-ordered-property-with-tag)
12776 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12777 (save-excursion
12778 (org-back-to-heading)
12779 (if (org-entry-get nil "ORDERED")
12780 (progn
12781 (org-delete-property "ORDERED")
12782 (and tag (org-toggle-tag tag 'off))
12783 (message "Subtasks can be completed in arbitrary order"))
12784 (org-entry-put nil "ORDERED" "t")
12785 (and tag (org-toggle-tag tag 'on))
12786 (message "Subtasks must be completed in sequence")))))
12788 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12789 (defun org-block-todo-from-checkboxes (change-plist)
12790 "Block turning an entry into a TODO, using checkboxes.
12791 This checks whether the current task should be blocked from state
12792 changes because there are unchecked boxes in this entry."
12793 (if (not org-enforce-todo-checkbox-dependencies)
12794 t ; if locally turned off don't block
12795 (catch 'dont-block
12796 ;; If this is not a todo state change, or if this entry is already DONE,
12797 ;; do not block
12798 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12799 (member (plist-get change-plist :from)
12800 (cons 'done org-done-keywords))
12801 (member (plist-get change-plist :to)
12802 (cons 'todo org-not-done-keywords))
12803 (not (plist-get change-plist :to)))
12804 (throw 'dont-block t))
12805 ;; If this task has checkboxes that are not checked, it's blocked
12806 (save-excursion
12807 (org-back-to-heading t)
12808 (let ((beg (point)) end)
12809 (outline-next-heading)
12810 (setq end (point))
12811 (goto-char beg)
12812 (if (org-list-search-forward
12813 (concat (org-item-beginning-re)
12814 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12815 "\\[[- ]\\]")
12816 end t)
12817 (progn
12818 (if (boundp 'org-blocked-by-checkboxes)
12819 (setq org-blocked-by-checkboxes t))
12820 (throw 'dont-block nil)))))
12821 t))) ; do not block
12823 (defun org-entry-blocked-p ()
12824 "Is the current entry blocked?"
12825 (org-with-silent-modifications
12826 (if (org-entry-get nil "NOBLOCKING")
12827 nil ;; Never block this entry
12828 (not (run-hook-with-args-until-failure
12829 'org-blocker-hook
12830 (list :type 'todo-state-change
12831 :position (point)
12832 :from 'todo
12833 :to 'done))))))
12835 (defun org-update-statistics-cookies (all)
12836 "Update the statistics cookie, either from TODO or from checkboxes.
12837 This should be called with the cursor in a line with a statistics cookie."
12838 (interactive "P")
12839 (if all
12840 (progn
12841 (org-update-checkbox-count 'all)
12842 (org-map-entries 'org-update-parent-todo-statistics))
12843 (if (not (org-at-heading-p))
12844 (org-update-checkbox-count)
12845 (let ((pos (point-marker))
12846 end l1 l2)
12847 (ignore-errors (org-back-to-heading t))
12848 (if (not (org-at-heading-p))
12849 (org-update-checkbox-count)
12850 (setq l1 (org-outline-level))
12851 (setq end (save-excursion
12852 (outline-next-heading)
12853 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12854 (point)))
12855 (if (and (save-excursion
12856 (re-search-forward
12857 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12858 (not (save-excursion (re-search-forward
12859 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12860 (org-update-checkbox-count)
12861 (if (and l2 (> l2 l1))
12862 (progn
12863 (goto-char end)
12864 (org-update-parent-todo-statistics))
12865 (goto-char pos)
12866 (beginning-of-line 1)
12867 (while (re-search-forward
12868 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12869 (point-at-eol) t)
12870 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12871 (goto-char pos)
12872 (move-marker pos nil)))))
12874 (defvar org-entry-property-inherited-from) ;; defined below
12875 (defun org-update-parent-todo-statistics ()
12876 "Update any statistics cookie in the parent of the current headline.
12877 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12878 the entire subtree and this will travel up the hierarchy and update
12879 statistics everywhere."
12880 (let* ((prop (save-excursion (org-up-heading-safe)
12881 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12882 (recursive (or (not org-hierarchical-todo-statistics)
12883 (and prop (string-match "\\<recursive\\>" prop))))
12884 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12886 (first t)
12887 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12888 level ltoggle l1 new ndel
12889 (cnt-all 0) (cnt-done 0) is-percent kwd
12890 checkbox-beg ov ovs ove cookie-present)
12891 (catch 'exit
12892 (save-excursion
12893 (beginning-of-line 1)
12894 (setq ltoggle (funcall outline-level))
12895 ;; Three situations are to consider:
12897 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12898 ;; to the top-level ancestor on the headline;
12900 ;; 2. If parent has "recursive" property, repeat up to the
12901 ;; headline setting that property, taking inheritance into
12902 ;; account;
12904 ;; 3. Else, move up to direct parent and proceed only once.
12905 (while (and (setq level (org-up-heading-safe))
12906 (or recursive first)
12907 (>= (point) lim))
12908 (setq first nil cookie-present nil)
12909 (unless (and level
12910 (not (string-match
12911 "\\<checkbox\\>"
12912 (downcase (or (org-entry-get nil "COOKIE_DATA")
12913 "")))))
12914 (throw 'exit nil))
12915 (while (re-search-forward box-re (point-at-eol) t)
12916 (setq cnt-all 0 cnt-done 0 cookie-present t)
12917 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12918 (save-match-data
12919 (unless (outline-next-heading) (throw 'exit nil))
12920 (while (and (looking-at org-complex-heading-regexp)
12921 (> (setq l1 (length (match-string 1))) level))
12922 (setq kwd (and (or recursive (= l1 ltoggle))
12923 (match-string 2)))
12924 (if (or (eq org-provide-todo-statistics 'all-headlines)
12925 (and (eq org-provide-todo-statistics t)
12926 (or (member kwd org-done-keywords)))
12927 (and (listp org-provide-todo-statistics)
12928 (stringp (car org-provide-todo-statistics))
12929 (or (member kwd org-provide-todo-statistics)
12930 (member kwd org-done-keywords)))
12931 (and (listp org-provide-todo-statistics)
12932 (listp (car org-provide-todo-statistics))
12933 (or (member kwd (car org-provide-todo-statistics))
12934 (and (member kwd org-done-keywords)
12935 (member kwd (cadr org-provide-todo-statistics))))))
12936 (setq cnt-all (1+ cnt-all))
12937 (if (eq org-provide-todo-statistics t)
12938 (and kwd (setq cnt-all (1+ cnt-all)))))
12939 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12940 (member kwd org-done-keywords))
12941 (and (listp org-provide-todo-statistics)
12942 (listp (car org-provide-todo-statistics))
12943 (member kwd org-done-keywords)
12944 (member kwd (cadr org-provide-todo-statistics)))
12945 (and (listp org-provide-todo-statistics)
12946 (stringp (car org-provide-todo-statistics))
12947 (member kwd org-done-keywords)))
12948 (setq cnt-done (1+ cnt-done)))
12949 (outline-next-heading)))
12950 (setq new
12951 (if is-percent
12952 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12953 (format "[%d/%d]" cnt-done cnt-all))
12954 ndel (- (match-end 0) checkbox-beg))
12955 ;; handle overlays when updating cookie from column view
12956 (when (setq ov (car (overlays-at checkbox-beg)))
12957 (setq ovs (overlay-start ov) ove (overlay-end ov))
12958 (delete-overlay ov))
12959 (goto-char checkbox-beg)
12960 (insert new)
12961 (delete-region (point) (+ (point) ndel))
12962 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12963 (when ov (move-overlay ov ovs ove)))
12964 (when cookie-present
12965 (run-hook-with-args 'org-after-todo-statistics-hook
12966 cnt-done (- cnt-all cnt-done))))))
12967 (run-hooks 'org-todo-statistics-hook)))
12969 (defvar org-after-todo-statistics-hook nil
12970 "Hook that is called after a TODO statistics cookie has been updated.
12971 Each function is called with two arguments: the number of not-done entries
12972 and the number of done entries.
12974 For example, the following function, when added to this hook, will switch
12975 an entry to DONE when all children are done, and back to TODO when new
12976 entries are set to a TODO status. Note that this hook is only called
12977 when there is a statistics cookie in the headline!
12979 (defun org-summary-todo (n-done n-not-done)
12980 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12981 (let (org-log-done org-log-states) ; turn off logging
12982 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12985 (defvar org-todo-statistics-hook nil
12986 "Hook that is run whenever Org thinks TODO statistics should be updated.
12987 This hook runs even if there is no statistics cookie present, in which case
12988 `org-after-todo-statistics-hook' would not run.")
12990 (defun org-todo-trigger-tag-changes (state)
12991 "Apply the changes defined in `org-todo-state-tags-triggers'."
12992 (let ((l org-todo-state-tags-triggers)
12993 changes)
12994 (when (or (not state) (equal state ""))
12995 (setq changes (append changes (cdr (assoc "" l)))))
12996 (when (and (stringp state) (> (length state) 0))
12997 (setq changes (append changes (cdr (assoc state l)))))
12998 (when (member state org-not-done-keywords)
12999 (setq changes (append changes (cdr (assoc 'todo l)))))
13000 (when (member state org-done-keywords)
13001 (setq changes (append changes (cdr (assoc 'done l)))))
13002 (dolist (c changes)
13003 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13005 (defun org-local-logging (value)
13006 "Get logging settings from a property VALUE."
13007 (let* (words w a)
13008 ;; directly set the variables, they are already local.
13009 (setq org-log-done nil
13010 org-log-repeat nil
13011 org-todo-log-states nil)
13012 (setq words (org-split-string value))
13013 (while (setq w (pop words))
13014 (cond
13015 ((setq a (assoc w org-startup-options))
13016 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13017 (set (nth 1 a) (nth 2 a))))
13018 ((setq a (org-extract-log-state-settings w))
13019 (and (member (car a) org-todo-keywords-1)
13020 (push a org-todo-log-states)))))))
13022 (defun org-get-todo-sequence-head (kwd)
13023 "Return the head of the TODO sequence to which KWD belongs.
13024 If KWD is not set, check if there is a text property remembering the
13025 right sequence."
13026 (let (p)
13027 (cond
13028 ((not kwd)
13029 (or (get-text-property (point-at-bol) 'org-todo-head)
13030 (progn
13031 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13032 nil (point-at-eol)))
13033 (get-text-property p 'org-todo-head))))
13034 ((not (member kwd org-todo-keywords-1))
13035 (car org-todo-keywords-1))
13036 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13038 (defun org-fast-todo-selection ()
13039 "Fast TODO keyword selection with single keys.
13040 Returns the new TODO keyword, or nil if no state change should occur."
13041 (let* ((fulltable org-todo-key-alist)
13042 (done-keywords org-done-keywords) ;; needed for the faces.
13043 (maxlen (apply 'max (mapcar
13044 (lambda (x)
13045 (if (stringp (car x)) (string-width (car x)) 0))
13046 fulltable)))
13047 (expert nil)
13048 (fwidth (+ maxlen 3 1 3))
13049 (ncol (/ (- (window-width) 4) fwidth))
13050 tg cnt e c tbl
13051 groups ingroup)
13052 (save-excursion
13053 (save-window-excursion
13054 (if expert
13055 (set-buffer (get-buffer-create " *Org todo*"))
13056 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13057 (erase-buffer)
13058 (org-set-local 'org-done-keywords done-keywords)
13059 (setq tbl fulltable cnt 0)
13060 (while (setq e (pop tbl))
13061 (cond
13062 ((equal e '(:startgroup))
13063 (push '() groups) (setq ingroup t)
13064 (when (not (= cnt 0))
13065 (setq cnt 0)
13066 (insert "\n"))
13067 (insert "{ "))
13068 ((equal e '(:endgroup))
13069 (setq ingroup nil cnt 0)
13070 (insert "}\n"))
13071 ((equal e '(:newline))
13072 (when (not (= cnt 0))
13073 (setq cnt 0)
13074 (insert "\n")
13075 (setq e (car tbl))
13076 (while (equal (car tbl) '(:newline))
13077 (insert "\n")
13078 (setq tbl (cdr tbl)))))
13080 (setq tg (car e) c (cdr e))
13081 (if ingroup (push tg (car groups)))
13082 (setq tg (org-add-props tg nil 'face
13083 (org-get-todo-face tg)))
13084 (if (and (= cnt 0) (not ingroup)) (insert " "))
13085 (insert "[" c "] " tg (make-string
13086 (- fwidth 4 (length tg)) ?\ ))
13087 (when (= (setq cnt (1+ cnt)) ncol)
13088 (insert "\n")
13089 (if ingroup (insert " "))
13090 (setq cnt 0)))))
13091 (insert "\n")
13092 (goto-char (point-min))
13093 (if (not expert) (org-fit-window-to-buffer))
13094 (message "[a-z..]:Set [SPC]:clear")
13095 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13096 (cond
13097 ((or (= c ?\C-g)
13098 (and (= c ?q) (not (rassoc c fulltable))))
13099 (setq quit-flag t))
13100 ((= c ?\ ) nil)
13101 ((setq e (rassoc c fulltable) tg (car e))
13103 (t (setq quit-flag t)))))))
13105 (defun org-entry-is-todo-p ()
13106 (member (org-get-todo-state) org-not-done-keywords))
13108 (defun org-entry-is-done-p ()
13109 (member (org-get-todo-state) org-done-keywords))
13111 (defun org-get-todo-state ()
13112 "Return the TODO keyword of the current subtree."
13113 (save-excursion
13114 (org-back-to-heading t)
13115 (and (looking-at org-todo-line-regexp)
13116 (match-end 2)
13117 (match-string 2))))
13119 (defun org-at-date-range-p (&optional inactive-ok)
13120 "Is the cursor inside a date range?"
13121 (interactive)
13122 (save-excursion
13123 (catch 'exit
13124 (let ((pos (point)))
13125 (skip-chars-backward "^[<\r\n")
13126 (skip-chars-backward "<[")
13127 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13128 (>= (match-end 0) pos)
13129 (throw 'exit t))
13130 (skip-chars-backward "^<[\r\n")
13131 (skip-chars-backward "<[")
13132 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13133 (>= (match-end 0) pos)
13134 (throw 'exit t)))
13135 nil)))
13137 (defun org-get-repeat (&optional tagline)
13138 "Check if there is a deadline/schedule with repeater in this entry."
13139 (save-match-data
13140 (save-excursion
13141 (org-back-to-heading t)
13142 (and (re-search-forward (if tagline
13143 (concat tagline "\\s-*" org-repeat-re)
13144 org-repeat-re)
13145 (org-entry-end-position) t)
13146 (match-string-no-properties 1)))))
13148 (defvar org-last-changed-timestamp)
13149 (defvar org-last-inserted-timestamp)
13150 (defvar org-log-post-message)
13151 (defvar org-log-note-purpose)
13152 (defvar org-log-note-how nil)
13153 (defvar org-log-note-extra)
13154 (defun org-auto-repeat-maybe (done-word)
13155 "Check if the current headline contains a repeated deadline/schedule.
13156 If yes, set TODO state back to what it was and change the base date
13157 of repeating deadline/scheduled time stamps to new date.
13158 This function is run automatically after each state change to a DONE state."
13159 ;; last-state is dynamically scoped into this function
13160 (let* ((repeat (org-get-repeat))
13161 (aa (assoc org-last-state org-todo-kwd-alist))
13162 (interpret (nth 1 aa))
13163 (head (nth 2 aa))
13164 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13165 (msg "Entry repeats: ")
13166 (org-log-done nil)
13167 (org-todo-log-states nil)
13168 re type n what ts time to-state)
13169 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13170 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
13171 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
13172 org-todo-repeat-to-state))
13173 (unless (and to-state (member to-state org-todo-keywords-1))
13174 (setq to-state (if (eq interpret 'type) org-last-state head)))
13175 (org-todo to-state)
13176 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13177 (org-entry-put nil "LAST_REPEAT" (format-time-string
13178 (org-time-stamp-format t t))))
13179 (when org-log-repeat
13180 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13181 (memq 'org-add-log-note post-command-hook))
13182 ;; OK, we are already setup for some record
13183 (if (eq org-log-repeat 'note)
13184 ;; make sure we take a note, not only a time stamp
13185 (setq org-log-note-how 'note))
13186 ;; Set up for taking a record
13187 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13188 org-last-state
13189 'findpos org-log-repeat)))
13190 (org-back-to-heading t)
13191 (org-add-planning-info nil nil 'closed)
13192 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13193 org-deadline-time-regexp "\\)\\|\\("
13194 org-ts-regexp "\\)"))
13195 (while (re-search-forward
13196 re (save-excursion (outline-next-heading) (point)) t)
13197 (setq type (if (match-end 1) org-scheduled-string
13198 (if (match-end 3) org-deadline-string "Plain:"))
13199 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13200 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13201 (setq n (string-to-number (match-string 2 ts))
13202 what (match-string 3 ts))
13203 (if (equal what "w") (setq n (* n 7) what "d"))
13204 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13205 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13206 ;; Preparation, see if we need to modify the start date for the change
13207 (when (match-end 1)
13208 (setq time (save-match-data (org-time-string-to-time ts)))
13209 (cond
13210 ((equal (match-string 1 ts) ".")
13211 ;; Shift starting date to today
13212 (org-timestamp-change
13213 (- (org-today) (time-to-days time))
13214 'day))
13215 ((equal (match-string 1 ts) "+")
13216 (let ((nshiftmax 10) (nshift 0))
13217 (while (or (= nshift 0)
13218 (<= (time-to-days time)
13219 (time-to-days (current-time))))
13220 (when (= (incf nshift) nshiftmax)
13221 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13222 (user-error "Abort")))
13223 (org-timestamp-change n (cdr (assoc what whata)))
13224 (org-at-timestamp-p t)
13225 (setq ts (match-string 1))
13226 (setq time (save-match-data (org-time-string-to-time ts)))))
13227 (org-timestamp-change (- n) (cdr (assoc what whata)))
13228 ;; rematch, so that we have everything in place for the real shift
13229 (org-at-timestamp-p t)
13230 (setq ts (match-string 1))
13231 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13232 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13233 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13234 (setq org-log-post-message msg)
13235 (message "%s" msg))))
13237 (defun org-show-todo-tree (arg)
13238 "Make a compact tree which shows all headlines marked with TODO.
13239 The tree will show the lines where the regexp matches, and all higher
13240 headlines above the match.
13241 With a \\[universal-argument] prefix, prompt for a regexp to match.
13242 With a numeric prefix N, construct a sparse tree for the Nth element
13243 of `org-todo-keywords-1'."
13244 (interactive "P")
13245 (let ((case-fold-search nil)
13246 (kwd-re
13247 (cond ((null arg) org-not-done-regexp)
13248 ((equal arg '(4))
13249 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13250 (mapcar 'list org-todo-keywords-1))))
13251 (concat "\\("
13252 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13253 "\\)\\>")))
13254 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13255 (regexp-quote (nth (1- (prefix-numeric-value arg))
13256 org-todo-keywords-1)))
13257 (t (user-error "Invalid prefix argument: %s" arg)))))
13258 (message "%d TODO entries found"
13259 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13261 (defun org-deadline (arg &optional time)
13262 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13263 With one universal prefix argument, remove any deadline from the item.
13264 With two universal prefix arguments, prompt for a warning delay.
13265 With argument TIME, set the deadline at the corresponding date. TIME
13266 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13267 (interactive "P")
13268 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13269 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13270 'region-start-level 'region))
13271 org-loop-over-headlines-in-active-region)
13272 (org-map-entries
13273 `(org-deadline ',arg ,time)
13274 org-loop-over-headlines-in-active-region
13275 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13276 (let* ((old-date (org-entry-get nil "DEADLINE"))
13277 (old-date-time (if old-date (org-time-string-to-time old-date)))
13278 (repeater (and old-date
13279 (string-match
13280 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13281 old-date)
13282 (match-string 1 old-date))))
13283 (cond
13284 ((equal arg '(4))
13285 (when (and old-date org-log-redeadline)
13286 (org-add-log-setup 'deldeadline nil old-date 'findpos
13287 org-log-redeadline))
13288 (org-remove-timestamp-with-keyword org-deadline-string)
13289 (message "Item no longer has a deadline."))
13290 ((equal arg '(16))
13291 (save-excursion
13292 (org-back-to-heading t)
13293 (if (re-search-forward
13294 org-deadline-time-regexp
13295 (save-excursion (outline-next-heading) (point)) t)
13296 (let* ((rpl0 (match-string 1))
13297 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13298 (replace-match
13299 (concat org-deadline-string
13300 " <" rpl
13301 (format " -%dd"
13302 (abs
13303 (- (time-to-days
13304 (save-match-data
13305 (org-read-date nil t nil "Warn starting from" old-date-time)))
13306 (time-to-days old-date-time))))
13307 ">") t t))
13308 (user-error "No deadline information to update"))))
13310 (org-add-planning-info 'deadline time 'closed)
13311 (when (and old-date org-log-redeadline
13312 (not (equal old-date
13313 (substring org-last-inserted-timestamp 1 -1))))
13314 (org-add-log-setup 'redeadline nil old-date 'findpos
13315 org-log-redeadline))
13316 (when repeater
13317 (save-excursion
13318 (org-back-to-heading t)
13319 (when (re-search-forward (concat org-deadline-string " "
13320 org-last-inserted-timestamp)
13321 (save-excursion
13322 (outline-next-heading) (point)) t)
13323 (goto-char (1- (match-end 0)))
13324 (insert " " repeater)
13325 (setq org-last-inserted-timestamp
13326 (concat (substring org-last-inserted-timestamp 0 -1)
13327 " " repeater
13328 (substring org-last-inserted-timestamp -1))))))
13329 (message "Deadline on %s" org-last-inserted-timestamp))))))
13331 (defun org-schedule (arg &optional time)
13332 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13333 With one universal prefix argument, remove any scheduling date from the item.
13334 With two universal prefix arguments, prompt for a delay cookie.
13335 With argument TIME, scheduled at the corresponding date. TIME can
13336 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13337 (interactive "P")
13338 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13339 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13340 'region-start-level 'region))
13341 org-loop-over-headlines-in-active-region)
13342 (org-map-entries
13343 `(org-schedule ',arg ,time)
13344 org-loop-over-headlines-in-active-region
13345 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13346 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13347 (old-date-time (if old-date (org-time-string-to-time old-date)))
13348 (repeater (and old-date
13349 (string-match
13350 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13351 old-date)
13352 (match-string 1 old-date))))
13353 (cond
13354 ((equal arg '(4))
13355 (progn
13356 (when (and old-date org-log-reschedule)
13357 (org-add-log-setup 'delschedule nil old-date 'findpos
13358 org-log-reschedule))
13359 (org-remove-timestamp-with-keyword org-scheduled-string)
13360 (message "Item is no longer scheduled.")))
13361 ((equal arg '(16))
13362 (save-excursion
13363 (org-back-to-heading t)
13364 (if (re-search-forward
13365 org-scheduled-time-regexp
13366 (save-excursion (outline-next-heading) (point)) t)
13367 (let* ((rpl0 (match-string 1))
13368 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13369 (replace-match
13370 (concat org-scheduled-string
13371 " <" rpl
13372 (format " -%dd"
13373 (abs
13374 (- (time-to-days
13375 (save-match-data
13376 (org-read-date nil t nil "Delay until" old-date-time)))
13377 (time-to-days old-date-time))))
13378 ">") t t))
13379 (user-error "No scheduled information to update"))))
13381 (org-add-planning-info 'scheduled time 'closed)
13382 (when (and old-date org-log-reschedule
13383 (not (equal old-date
13384 (substring org-last-inserted-timestamp 1 -1))))
13385 (org-add-log-setup 'reschedule nil old-date 'findpos
13386 org-log-reschedule))
13387 (when repeater
13388 (save-excursion
13389 (org-back-to-heading t)
13390 (when (re-search-forward (concat org-scheduled-string " "
13391 org-last-inserted-timestamp)
13392 (save-excursion
13393 (outline-next-heading) (point)) t)
13394 (goto-char (1- (match-end 0)))
13395 (insert " " repeater)
13396 (setq org-last-inserted-timestamp
13397 (concat (substring org-last-inserted-timestamp 0 -1)
13398 " " repeater
13399 (substring org-last-inserted-timestamp -1))))))
13400 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13402 (defun org-get-scheduled-time (pom &optional inherit)
13403 "Get the scheduled time as a time tuple, of a format suitable
13404 for calling org-schedule with, or if there is no scheduling,
13405 returns nil."
13406 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13407 (when time
13408 (apply 'encode-time (org-parse-time-string time)))))
13410 (defun org-get-deadline-time (pom &optional inherit)
13411 "Get the deadline as a time tuple, of a format suitable for
13412 calling org-deadline with, or if there is no scheduling, returns
13413 nil."
13414 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13415 (when time
13416 (apply 'encode-time (org-parse-time-string time)))))
13418 (defun org-remove-timestamp-with-keyword (keyword)
13419 "Remove all time stamps with KEYWORD in the current entry."
13420 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13421 beg)
13422 (save-excursion
13423 (org-back-to-heading t)
13424 (setq beg (point))
13425 (outline-next-heading)
13426 (while (re-search-backward re beg t)
13427 (replace-match "")
13428 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13429 (equal (char-before) ?\ ))
13430 (backward-delete-char 1)
13431 (if (string-match "^[ \t]*$" (buffer-substring
13432 (point-at-bol) (point-at-eol)))
13433 (delete-region (point-at-bol)
13434 (min (point-max) (1+ (point-at-eol))))))))))
13436 (defvar org-time-was-given) ; dynamically scoped parameter
13437 (defvar org-end-time-was-given) ; dynamically scoped parameter
13439 (defun org-at-planning-p ()
13440 "Non-nil when point is on a planning info line."
13441 ;; This is as accurate and faster than `org-element-at-point' since
13442 ;; planning info location is fixed in the section.
13443 (org-with-wide-buffer
13444 (beginning-of-line)
13445 (and (org-looking-at-p org-planning-line-re)
13446 (eq (point)
13447 (ignore-errors
13448 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13449 (org-back-to-heading t)
13450 (org-with-limited-levels (org-back-to-heading t)))
13451 (line-beginning-position 2))))))
13453 (defun org-add-planning-info (what &optional time &rest remove)
13454 "Insert new timestamp with keyword in the planning line.
13455 WHAT indicates what kind of time stamp to add. It is a symbol
13456 among `closed', `deadline', `scheduled' and nil. TIME indicates
13457 the time to use. If none is given, the user is prompted for
13458 a date. REMOVE indicates what kind of entries to remove. An old
13459 WHAT entry will also be removed."
13460 (let (org-time-was-given org-end-time-was-given default-time default-input)
13461 (catch 'exit
13462 (when (and (memq what '(scheduled deadline))
13463 (or (not time)
13464 (and (stringp time)
13465 (string-match "^[-+]+[0-9]" time))))
13466 ;; Try to get a default date/time from existing timestamp
13467 (save-excursion
13468 (org-back-to-heading t)
13469 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13470 (when (re-search-forward (if (eq what 'scheduled)
13471 org-scheduled-time-regexp
13472 org-deadline-time-regexp)
13473 end t)
13474 (setq ts (match-string 1)
13475 default-time (apply 'encode-time (org-parse-time-string ts))
13476 default-input (and ts (org-get-compact-tod ts)))))))
13477 (when what
13478 (setq time
13479 (if (stringp time)
13480 ;; This is a string (relative or absolute), set
13481 ;; proper date.
13482 (apply #'encode-time
13483 (org-read-date-analyze
13484 time default-time (decode-time default-time)))
13485 ;; If necessary, get the time from the user
13486 (or time (org-read-date nil 'to-time nil nil
13487 default-time default-input)))))
13489 (org-with-wide-buffer
13490 (org-back-to-heading t)
13491 (forward-line)
13492 (unless (bolp) (insert "\n"))
13493 (cond ((org-looking-at-p org-planning-line-re)
13494 ;; Move to current indentation.
13495 (skip-chars-forward " \t")
13496 ;; Check if we have to remove something.
13497 (dolist (type (if what (cons what remove) remove))
13498 (when (save-excursion
13499 (re-search-forward
13500 (case type
13501 (closed org-closed-time-regexp)
13502 (deadline org-deadline-time-regexp)
13503 (scheduled org-scheduled-time-regexp)
13504 (otherwise (error "Invalid planning type: %s" type)))
13505 (line-end-position) t))
13506 (replace-match "")
13507 (when (looking-at "--+<[^>]+>") (replace-match ""))
13508 (when (and (not what) (eq type 'closed))
13509 (save-excursion
13510 (beginning-of-line)
13511 (if (looking-at "[ \t]*$")
13512 (delete-region (point) (1+ (point-at-eol)))))))
13513 ;; Remove leading white spaces.
13514 (when (and (not (bolp)) (looking-at "[ \t]+")) (replace-match ""))))
13515 ((not what) (throw 'exit nil)) ; Nothing to do.
13516 (t (insert-before-markers "\n")
13517 (backward-char 1)
13518 (when org-adapt-indentation
13519 (org-indent-to-column (1+ (org-outline-level))))))
13520 (when what
13521 ;; Insert planning keyword.
13522 (insert (case what
13523 (closed org-closed-string)
13524 (deadline org-deadline-string)
13525 (scheduled org-scheduled-string)
13526 (otherwise (error "Invalid planning type: %s" what)))
13527 " ")
13528 ;; Insert associated timestamp.
13529 (let ((ts (org-insert-time-stamp
13530 time
13531 (or org-time-was-given
13532 (and (eq what 'closed) org-log-done-with-time))
13533 (eq what 'closed)
13534 nil nil (list org-end-time-was-given))))
13535 (unless (eolp) (insert " "))
13536 ts))))))
13538 (defvar org-log-note-marker (make-marker))
13539 (defvar org-log-note-purpose nil)
13540 (defvar org-log-note-state nil)
13541 (defvar org-log-note-previous-state nil)
13542 (defvar org-log-note-extra nil)
13543 (defvar org-log-note-window-configuration nil)
13544 (defvar org-log-note-return-to (make-marker))
13545 (defvar org-log-note-effective-time nil
13546 "Remembered current time so that dynamically scoped
13547 `org-extend-today-until' affects tha timestamps in state change
13548 log")
13550 (defvar org-log-post-message nil
13551 "Message to be displayed after a log note has been stored.
13552 The auto-repeater uses this.")
13554 (defun org-add-note ()
13555 "Add a note to the current entry.
13556 This is done in the same way as adding a state change note."
13557 (interactive)
13558 (org-add-log-setup 'note nil nil 'findpos nil))
13560 (defun org-log-beginning (&optional create)
13561 "Return expected start of log notes in current entry.
13562 When optional argument CREATE is non-nil, the function creates
13563 a drawer to store notes, if necessary. Returned position ignores
13564 narrowing."
13565 (org-with-wide-buffer
13566 (org-back-to-heading t)
13567 ;; Skip planning info and property drawer.
13568 (forward-line)
13569 (when (org-looking-at-p org-planning-line-re) (forward-line))
13570 (when (looking-at org-property-drawer-re)
13571 (goto-char (match-end 0))
13572 (forward-line))
13573 (let ((end (if (org-at-heading-p) (point)
13574 (save-excursion (outline-next-heading) (point))))
13575 (drawer (org-log-into-drawer)))
13576 (cond
13577 (drawer
13578 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13579 (case-fold-search t))
13580 (catch 'exit
13581 ;; Try to find existing drawer.
13582 (while (re-search-forward regexp end t)
13583 (let ((element (org-element-at-point)))
13584 (when (eq (org-element-type element) 'drawer)
13585 (let ((cend (org-element-property :contents-end element)))
13586 (when (and (not org-log-states-order-reversed) cend)
13587 (goto-char cend)))
13588 (throw 'exit nil))))
13589 ;; No drawer found. Create one, if permitted.
13590 (when create
13591 (unless (bolp) (insert "\n"))
13592 (let ((beg (point)))
13593 (insert ":" drawer ":\n:END:\n")
13594 (org-indent-region beg (point)))
13595 (end-of-line -1)))))
13596 (org-log-state-notes-insert-after-drawers
13597 (while (and (looking-at org-drawer-regexp)
13598 (progn (goto-char (match-end 0))
13599 (re-search-forward org-property-end-re end t)))
13600 (forward-line)))))
13601 (if (bolp) (point) (line-beginning-position 2))))
13603 (defun org-add-log-setup (&optional purpose state prev-state findpos how extra)
13604 "Set up the post command hook to take a note.
13605 If this is about to TODO state change, the new state is expected in STATE.
13606 When FINDPOS is non-nil, find the correct position for the note in
13607 the current entry. If not, assume that it can be inserted at point.
13608 HOW is an indicator what kind of note should be created.
13609 EXTRA is additional text that will be inserted into the notes buffer."
13610 (org-with-wide-buffer
13611 (when findpos
13612 (goto-char (org-log-beginning t))
13613 (unless org-log-states-order-reversed
13614 (org-skip-over-state-notes)
13615 (skip-chars-backward " \t\n\r")
13616 (forward-line)))
13617 (move-marker org-log-note-marker (point))
13618 ;; Preserve position even if a property drawer is inserted in the
13619 ;; process.
13620 (set-marker-insertion-type org-log-note-marker t)
13621 (setq org-log-note-purpose purpose
13622 org-log-note-state state
13623 org-log-note-previous-state prev-state
13624 org-log-note-how how
13625 org-log-note-extra extra
13626 org-log-note-effective-time (org-current-effective-time))
13627 (add-hook 'post-command-hook 'org-add-log-note 'append)))
13629 (defun org-skip-over-state-notes ()
13630 "Skip past the list of State notes in an entry."
13631 (when (ignore-errors (goto-char (org-in-item-p)))
13632 (let* ((struct (org-list-struct))
13633 (prevs (org-list-prevs-alist struct))
13634 (regexp
13635 (concat "[ \t]*- +"
13636 (replace-regexp-in-string
13637 " +" " +"
13638 (org-replace-escapes
13639 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13640 `(("%d" . ,org-ts-regexp-inactive)
13641 ("%D" . ,org-ts-regexp)
13642 ("%s" . "\"\\S-+\"")
13643 ("%S" . "\"\\S-+\"")
13644 ("%t" . ,org-ts-regexp-inactive)
13645 ("%T" . ,org-ts-regexp)
13646 ("%u" . ".*?")
13647 ("%U" . ".*?")))))))
13648 (while (org-looking-at-p regexp)
13649 (goto-char (or (org-list-get-next-item (point) struct prevs)
13650 (org-list-get-item-end (point) struct)))))))
13652 (defun org-add-log-note (&optional purpose)
13653 "Pop up a window for taking a note, and add this note later at point."
13654 (remove-hook 'post-command-hook 'org-add-log-note)
13655 (setq org-log-note-window-configuration (current-window-configuration))
13656 (delete-other-windows)
13657 (move-marker org-log-note-return-to (point))
13658 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13659 (goto-char org-log-note-marker)
13660 (org-switch-to-buffer-other-window "*Org Note*")
13661 (erase-buffer)
13662 (if (memq org-log-note-how '(time state))
13663 (let (current-prefix-arg) (org-store-log-note))
13664 (let ((org-inhibit-startup t)) (org-mode))
13665 (insert (format "# Insert note for %s.
13666 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13667 (cond
13668 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13669 ((eq org-log-note-purpose 'done) "closed todo item")
13670 ((eq org-log-note-purpose 'state)
13671 (format "state change from \"%s\" to \"%s\""
13672 (or org-log-note-previous-state "")
13673 (or org-log-note-state "")))
13674 ((eq org-log-note-purpose 'reschedule)
13675 "rescheduling")
13676 ((eq org-log-note-purpose 'delschedule)
13677 "no longer scheduled")
13678 ((eq org-log-note-purpose 'redeadline)
13679 "changing deadline")
13680 ((eq org-log-note-purpose 'deldeadline)
13681 "removing deadline")
13682 ((eq org-log-note-purpose 'refile)
13683 "refiling")
13684 ((eq org-log-note-purpose 'note)
13685 "this entry")
13686 (t (error "This should not happen")))))
13687 (if org-log-note-extra (insert org-log-note-extra))
13688 (org-set-local 'org-finish-function 'org-store-log-note)
13689 (run-hooks 'org-log-buffer-setup-hook)))
13691 (defvar org-note-abort nil) ; dynamically scoped
13692 (defun org-store-log-note ()
13693 "Finish taking a log note, and insert it to where it belongs."
13694 (let ((txt (buffer-string)))
13695 (kill-buffer (current-buffer))
13696 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings))) lines)
13697 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13698 (setq txt (replace-match "" t t txt)))
13699 (if (string-match "\\s-+\\'" txt)
13700 (setq txt (replace-match "" t t txt)))
13701 (setq lines (org-split-string txt "\n"))
13702 (when (and note (string-match "\\S-" note))
13703 (setq note
13704 (org-replace-escapes
13705 note
13706 (list (cons "%u" (user-login-name))
13707 (cons "%U" user-full-name)
13708 (cons "%t" (format-time-string
13709 (org-time-stamp-format 'long 'inactive)
13710 org-log-note-effective-time))
13711 (cons "%T" (format-time-string
13712 (org-time-stamp-format 'long nil)
13713 org-log-note-effective-time))
13714 (cons "%d" (format-time-string
13715 (org-time-stamp-format nil 'inactive)
13716 org-log-note-effective-time))
13717 (cons "%D" (format-time-string
13718 (org-time-stamp-format nil nil)
13719 org-log-note-effective-time))
13720 (cons "%s" (if org-log-note-state
13721 (concat "\"" org-log-note-state "\"")
13722 ""))
13723 (cons "%S" (if org-log-note-previous-state
13724 (concat "\"" org-log-note-previous-state "\"")
13725 "\"\"")))))
13726 (when lines (setq note (concat note " \\\\")))
13727 (push note lines))
13728 (when (or current-prefix-arg org-note-abort)
13729 (when (org-log-into-drawer)
13730 (org-remove-empty-drawer-at org-log-note-marker))
13731 (setq lines nil))
13732 (when lines
13733 (with-current-buffer (marker-buffer org-log-note-marker)
13734 (save-excursion
13735 (goto-char org-log-note-marker)
13736 (move-marker org-log-note-marker nil)
13737 ;; Make sure point is at the beginning of an empty line.
13738 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13739 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13740 ;; In an existing list, add a new item at the top level.
13741 ;; Otherwise, indent line like a regular one.
13742 (let ((itemp (org-in-item-p)))
13743 (if itemp
13744 (org-indent-line-to
13745 (let ((struct (save-excursion
13746 (goto-char itemp) (org-list-struct))))
13747 (org-list-get-ind (org-list-get-top-point struct) struct)))
13748 (org-indent-line)))
13749 (insert (org-list-bullet-string "-") (pop lines))
13750 (let ((ind (org-list-item-body-column (line-beginning-position))))
13751 (dolist (line lines)
13752 (insert "\n")
13753 (org-indent-line-to ind)
13754 (insert line)))
13755 (message "Note stored")
13756 (org-back-to-heading t)
13757 (org-cycle-hide-drawers 'children))
13758 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13759 ;; from within `org-add-log-note' because `buffer-undo-list'
13760 ;; is then modified outside of `org-with-remote-undo'.
13761 (when (eq this-command 'org-agenda-todo)
13762 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13763 ;; Don't add undo information when called from `org-agenda-todo'
13764 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13765 (set-window-configuration org-log-note-window-configuration)
13766 (with-current-buffer (marker-buffer org-log-note-return-to)
13767 (goto-char org-log-note-return-to))
13768 (move-marker org-log-note-return-to nil)
13769 (and org-log-post-message (message "%s" org-log-post-message))))
13771 (defun org-remove-empty-drawer-at (pos)
13772 "Remove an empty drawer at position POS.
13773 POS may also be a marker."
13774 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13775 (org-with-wide-buffer
13776 (goto-char pos)
13777 (let ((drawer (org-element-at-point)))
13778 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13779 (not (org-element-property :contents-begin drawer)))
13780 (delete-region (org-element-property :begin drawer)
13781 (progn (goto-char (org-element-property :end drawer))
13782 (skip-chars-backward " \r\t\n")
13783 (forward-line)
13784 (point))))))))
13786 (defvar org-ts-type nil)
13787 (defun org-sparse-tree (&optional arg type)
13788 "Create a sparse tree, prompt for the details.
13789 This command can create sparse trees. You first need to select the type
13790 of match used to create the tree:
13792 t Show all TODO entries.
13793 T Show entries with a specific TODO keyword.
13794 m Show entries selected by a tags/property match.
13795 p Enter a property name and its value (both with completion on existing
13796 names/values) and show entries with that property.
13797 r Show entries matching a regular expression (`/' can be used as well).
13798 b Show deadlines and scheduled items before a date.
13799 a Show deadlines and scheduled items after a date.
13800 d Show deadlines due within `org-deadline-warning-days'.
13801 D Show deadlines and scheduled items between a date range."
13802 (interactive "P")
13803 (setq type (or type org-sparse-tree-default-date-type))
13804 (setq org-ts-type type)
13805 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13806 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13807 [c]ycle through date types: %s"
13808 (case type
13809 (all "all timestamps")
13810 (scheduled "only scheduled")
13811 (deadline "only deadline")
13812 (active "only active timestamps")
13813 (inactive "only inactive timestamps")
13814 (closed "with a closed time-stamp")
13815 (otherwise "scheduled/deadline")))
13816 (let ((answer (read-char-exclusive)))
13817 (case answer
13819 (org-sparse-tree
13821 (cadr
13822 (memq type '(nil all scheduled deadline active inactive closed)))))
13823 (?d (call-interactively 'org-check-deadlines))
13824 (?b (call-interactively 'org-check-before-date))
13825 (?a (call-interactively 'org-check-after-date))
13826 (?D (call-interactively 'org-check-dates-range))
13827 (?t (call-interactively 'org-show-todo-tree))
13828 (?T (org-show-todo-tree '(4)))
13829 (?m (call-interactively 'org-match-sparse-tree))
13830 ((?p ?P)
13831 (let* ((kwd (org-icompleting-read
13832 "Property: " (mapcar 'list (org-buffer-property-keys))))
13833 (value (org-icompleting-read
13834 "Value: " (mapcar 'list (org-property-values kwd)))))
13835 (unless (string-match "\\`{.*}\\'" value)
13836 (setq value (concat "\"" value "\"")))
13837 (org-match-sparse-tree arg (concat kwd "=" value))))
13838 ((?r ?R ?/) (call-interactively 'org-occur))
13839 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13841 (defvar org-occur-highlights nil
13842 "List of overlays used for occur matches.")
13843 (make-variable-buffer-local 'org-occur-highlights)
13844 (defvar org-occur-parameters nil
13845 "Parameters of the active org-occur calls.
13846 This is a list, each call to org-occur pushes as cons cell,
13847 containing the regular expression and the callback, onto the list.
13848 The list can contain several entries if `org-occur' has been called
13849 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13850 will only contain one set of parameters. When the highlights are
13851 removed (for example with `C-c C-c', or with the next edit (depending
13852 on `org-remove-highlights-with-change'), this variable is emptied
13853 as well.")
13854 (make-variable-buffer-local 'org-occur-parameters)
13856 (defun org-occur (regexp &optional keep-previous callback)
13857 "Make a compact tree which shows all matches of REGEXP.
13858 The tree will show the lines where the regexp matches, and all higher
13859 headlines above the match. It will also show the heading after the match,
13860 to make sure editing the matching entry is easy.
13861 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13862 call to `org-occur' will be kept, to allow stacking of calls to this
13863 command.
13864 If CALLBACK is non-nil, it is a function which is called to confirm
13865 that the match should indeed be shown."
13866 (interactive "sRegexp: \nP")
13867 (when (equal regexp "")
13868 (user-error "Regexp cannot be empty"))
13869 (unless keep-previous
13870 (org-remove-occur-highlights nil nil t))
13871 (push (cons regexp callback) org-occur-parameters)
13872 (let ((cnt 0))
13873 (save-excursion
13874 (goto-char (point-min))
13875 (if (or (not keep-previous) ; do not want to keep
13876 (not org-occur-highlights)) ; no previous matches
13877 ;; hide everything
13878 (org-overview))
13879 (while (re-search-forward regexp nil t)
13880 (when (or (not callback)
13881 (save-match-data (funcall callback)))
13882 (setq cnt (1+ cnt))
13883 (when org-highlight-sparse-tree-matches
13884 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13885 (org-show-context 'occur-tree))))
13886 (when org-remove-highlights-with-change
13887 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13888 nil 'local))
13889 (unless org-sparse-tree-open-archived-trees
13890 (org-hide-archived-subtrees (point-min) (point-max)))
13891 (run-hooks 'org-occur-hook)
13892 (if (org-called-interactively-p 'interactive)
13893 (message "%d match(es) for regexp %s" cnt regexp))
13894 cnt))
13896 (defun org-occur-next-match (&optional n reset)
13897 "Function for `next-error-function' to find sparse tree matches.
13898 N is the number of matches to move, when negative move backwards.
13899 RESET is entirely ignored - this function always goes back to the
13900 starting point when no match is found."
13901 (let* ((limit (if (< n 0) (point-min) (point-max)))
13902 (search-func (if (< n 0)
13903 'previous-single-char-property-change
13904 'next-single-char-property-change))
13905 (n (abs n))
13906 (pos (point))
13908 (catch 'exit
13909 (while (setq p1 (funcall search-func (point) 'org-type))
13910 (when (equal p1 limit)
13911 (goto-char pos)
13912 (user-error "No more matches"))
13913 (when (equal (get-char-property p1 'org-type) 'org-occur)
13914 (setq n (1- n))
13915 (when (= n 0)
13916 (goto-char p1)
13917 (throw 'exit (point))))
13918 (goto-char p1))
13919 (goto-char p1)
13920 (user-error "No more matches"))))
13922 (defun org-show-context (&optional key)
13923 "Make sure point and context are visible.
13924 How much context is shown depends upon the variables
13925 `org-show-hierarchy-above', `org-show-following-heading',
13926 `org-show-entry-below' and `org-show-siblings'."
13927 (let ((heading-p (org-at-heading-p t))
13928 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13929 (following-p (org-get-alist-option org-show-following-heading key))
13930 (entry-p (org-get-alist-option org-show-entry-below key))
13931 (siblings-p (org-get-alist-option org-show-siblings key)))
13932 ;; Show heading or entry text
13933 (if (and heading-p (not entry-p))
13934 (org-flag-heading nil) ; only show the heading
13935 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13936 (org-show-hidden-entry))) ; show entire entry
13937 (when following-p
13938 ;; Show next sibling, or heading below text
13939 (save-excursion
13940 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13941 (org-flag-heading nil))))
13942 (when siblings-p (org-show-siblings))
13943 (when hierarchy-p
13944 ;; show all higher headings, possibly with siblings
13945 (save-excursion
13946 (while (and (ignore-errors (progn (org-up-heading-all 1) t))
13947 (not (bobp)))
13948 (org-flag-heading nil)
13949 (when siblings-p (org-show-siblings)))))))
13951 (defvar org-reveal-start-hook nil
13952 "Hook run before revealing a location.")
13954 (defun org-reveal (&optional siblings)
13955 "Show current entry, hierarchy above it, and the following headline.
13956 This can be used to show a consistent set of context around locations
13957 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13958 not t for the search context.
13960 With optional argument SIBLINGS, on each level of the hierarchy all
13961 siblings are shown. This repairs the tree structure to what it would
13962 look like when opened with hierarchical calls to `org-cycle'.
13963 With double optional argument \\[universal-argument] \\[universal-argument], \
13964 go to the parent and show the
13965 entire tree."
13966 (interactive "P")
13967 (run-hooks 'org-reveal-start-hook)
13968 (let ((org-show-hierarchy-above t)
13969 (org-show-following-heading t)
13970 (org-show-siblings (if siblings t org-show-siblings)))
13971 (org-show-context nil))
13972 (when (equal siblings '(16))
13973 (save-excursion
13974 (when (org-up-heading-safe)
13975 (org-show-subtree)
13976 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13978 (defun org-highlight-new-match (beg end)
13979 "Highlight from BEG to END and mark the highlight is an occur headline."
13980 (let ((ov (make-overlay beg end)))
13981 (overlay-put ov 'face 'secondary-selection)
13982 (overlay-put ov 'org-type 'org-occur)
13983 (push ov org-occur-highlights)))
13985 (defun org-remove-occur-highlights (&optional beg end noremove)
13986 "Remove the occur highlights from the buffer.
13987 BEG and END are ignored. If NOREMOVE is nil, remove this function
13988 from the `before-change-functions' in the current buffer."
13989 (interactive)
13990 (unless org-inhibit-highlight-removal
13991 (mapc 'delete-overlay org-occur-highlights)
13992 (setq org-occur-highlights nil)
13993 (setq org-occur-parameters nil)
13994 (unless noremove
13995 (remove-hook 'before-change-functions
13996 'org-remove-occur-highlights 'local))))
13998 ;;;; Priorities
14000 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14001 "Regular expression matching the priority indicator.")
14003 (defvar org-remove-priority-next-time nil)
14005 (defun org-priority-up ()
14006 "Increase the priority of the current item."
14007 (interactive)
14008 (org-priority 'up))
14010 (defun org-priority-down ()
14011 "Decrease the priority of the current item."
14012 (interactive)
14013 (org-priority 'down))
14015 (defun org-priority (&optional action show)
14016 "Change the priority of an item.
14017 ACTION can be `set', `up', `down', or a character."
14018 (interactive "P")
14019 (if (equal action '(4))
14020 (org-show-priority)
14021 (unless org-enable-priority-commands
14022 (user-error "Priority commands are disabled"))
14023 (setq action (or action 'set))
14024 (let (current new news have remove)
14025 (save-excursion
14026 (org-back-to-heading t)
14027 (if (looking-at org-priority-regexp)
14028 (setq current (string-to-char (match-string 2))
14029 have t))
14030 (cond
14031 ((eq action 'remove)
14032 (setq remove t new ?\ ))
14033 ((or (eq action 'set)
14034 (if (featurep 'xemacs) (characterp action) (integerp action)))
14035 (if (not (eq action 'set))
14036 (setq new action)
14037 (message "Priority %c-%c, SPC to remove: "
14038 org-highest-priority org-lowest-priority)
14039 (save-match-data
14040 (setq new (read-char-exclusive))))
14041 (if (and (= (upcase org-highest-priority) org-highest-priority)
14042 (= (upcase org-lowest-priority) org-lowest-priority))
14043 (setq new (upcase new)))
14044 (cond ((equal new ?\ ) (setq remove t))
14045 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14046 (user-error "Priority must be between `%c' and `%c'"
14047 org-highest-priority org-lowest-priority))))
14048 ((eq action 'up)
14049 (setq new (if have
14050 (1- current) ; normal cycling
14051 ;; last priority was empty
14052 (if (eq last-command this-command)
14053 org-lowest-priority ; wrap around empty to lowest
14054 ;; default
14055 (if org-priority-start-cycle-with-default
14056 org-default-priority
14057 (1- org-default-priority))))))
14058 ((eq action 'down)
14059 (setq new (if have
14060 (1+ current) ; normal cycling
14061 ;; last priority was empty
14062 (if (eq last-command this-command)
14063 org-highest-priority ; wrap around empty to highest
14064 ;; default
14065 (if org-priority-start-cycle-with-default
14066 org-default-priority
14067 (1+ org-default-priority))))))
14068 (t (user-error "Invalid action")))
14069 (if (or (< (upcase new) org-highest-priority)
14070 (> (upcase new) org-lowest-priority))
14071 (if (and (memq action '(up down))
14072 (not have) (not (eq last-command this-command)))
14073 ;; `new' is from default priority
14074 (error
14075 "The default can not be set, see `org-default-priority' why")
14076 ;; normal cycling: `new' is beyond highest/lowest priority
14077 ;; and is wrapped around to the empty priority
14078 (setq remove t)))
14079 (setq news (format "%c" new))
14080 (if have
14081 (if remove
14082 (replace-match "" t t nil 1)
14083 (replace-match news t t nil 2))
14084 (if remove
14085 (user-error "No priority cookie found in line")
14086 (let ((case-fold-search nil))
14087 (looking-at org-todo-line-regexp))
14088 (if (match-end 2)
14089 (progn
14090 (goto-char (match-end 2))
14091 (insert " [#" news "]"))
14092 (goto-char (match-beginning 3))
14093 (insert "[#" news "] "))))
14094 (org-set-tags nil 'align))
14095 (if remove
14096 (message "Priority removed")
14097 (message "Priority of current item set to %s" news)))))
14099 (defun org-show-priority ()
14100 "Show the priority of the current item.
14101 This priority is composed of the main priority given with the [#A] cookies,
14102 and by additional input from the age of a schedules or deadline entry."
14103 (interactive)
14104 (let ((pri (if (eq major-mode 'org-agenda-mode)
14105 (org-get-at-bol 'priority)
14106 (save-excursion
14107 (save-match-data
14108 (beginning-of-line)
14109 (and (looking-at org-heading-regexp)
14110 (org-get-priority (match-string 0))))))))
14111 (message "Priority is %d" (if pri pri -1000))))
14113 (defun org-get-priority (s)
14114 "Find priority cookie and return priority."
14115 (save-match-data
14116 (if (functionp org-get-priority-function)
14117 (funcall org-get-priority-function)
14118 (if (not (string-match org-priority-regexp s))
14119 (* 1000 (- org-lowest-priority org-default-priority))
14120 (* 1000 (- org-lowest-priority
14121 (string-to-char (match-string 2 s))))))))
14123 ;;;; Tags
14125 (defvar org-agenda-archives-mode)
14126 (defvar org-map-continue-from nil
14127 "Position from where mapping should continue.
14128 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14130 (defvar org-scanner-tags nil
14131 "The current tag list while the tags scanner is running.")
14132 (defvar org-trust-scanner-tags nil
14133 "Should `org-get-tags-at' use the tags for the scanner.
14134 This is for internal dynamical scoping only.
14135 When this is non-nil, the function `org-get-tags-at' will return the value
14136 of `org-scanner-tags' instead of building the list by itself. This
14137 can lead to large speed-ups when the tags scanner is used in a file with
14138 many entries, and when the list of tags is retrieved, for example to
14139 obtain a list of properties. Building the tags list for each entry in such
14140 a file becomes an N^2 operation - but with this variable set, it scales
14141 as N.")
14143 (defun org-scan-tags (action matcher todo-only &optional start-level)
14144 "Scan headline tags with inheritance and produce output ACTION.
14146 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14147 or `agenda' to produce an entry list for an agenda view. It can also be
14148 a Lisp form or a function that should be called at each matched headline, in
14149 this case the return value is a list of all return values from these calls.
14151 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
14152 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
14153 only lines with a not-done TODO keyword are included in the output.
14154 This should be the same variable that was scoped into
14155 and set by `org-make-tags-matcher' when it constructed MATCHER.
14157 START-LEVEL can be a string with asterisks, reducing the scope to
14158 headlines matching this string."
14159 (require 'org-agenda)
14160 (let* ((re (concat "^"
14161 (if start-level
14162 ;; Get the correct level to match
14163 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14164 org-outline-regexp)
14165 " *\\(\\<\\("
14166 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14167 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14168 (props (list 'face 'default
14169 'done-face 'org-agenda-done
14170 'undone-face 'default
14171 'mouse-face 'highlight
14172 'org-not-done-regexp org-not-done-regexp
14173 'org-todo-regexp org-todo-regexp
14174 'org-complex-heading-regexp org-complex-heading-regexp
14175 'help-echo
14176 (format "mouse-2 or RET jump to org file %s"
14177 (abbreviate-file-name
14178 (or (buffer-file-name (buffer-base-buffer))
14179 (buffer-name (buffer-base-buffer)))))))
14180 (org-map-continue-from nil)
14181 lspos tags tags-list
14182 (tags-alist (list (cons 0 org-file-tags)))
14183 (llast 0) rtn rtn1 level category i txt
14184 todo marker entry priority)
14185 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
14186 (setq action (list 'lambda nil action)))
14187 (save-excursion
14188 (goto-char (point-min))
14189 (when (eq action 'sparse-tree)
14190 (org-overview)
14191 (org-remove-occur-highlights))
14192 (while (let (case-fold-search)
14193 (re-search-forward re nil t))
14194 (setq org-map-continue-from nil)
14195 (catch :skip
14196 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14197 tags (if (match-end 4) (org-match-string-no-properties 4)))
14198 (goto-char (setq lspos (match-beginning 0)))
14199 (setq level (org-reduced-level (org-outline-level))
14200 category (org-get-category))
14201 (setq i llast llast level)
14202 ;; remove tag lists from same and sublevels
14203 (while (>= i level)
14204 (when (setq entry (assoc i tags-alist))
14205 (setq tags-alist (delete entry tags-alist)))
14206 (setq i (1- i)))
14207 ;; add the next tags
14208 (when tags
14209 (setq tags (org-split-string tags ":")
14210 tags-alist
14211 (cons (cons level tags) tags-alist)))
14212 ;; compile tags for current headline
14213 (setq tags-list
14214 (if org-use-tag-inheritance
14215 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14216 tags)
14217 org-scanner-tags tags-list)
14218 (when org-use-tag-inheritance
14219 (setcdr (car tags-alist)
14220 (mapcar (lambda (x)
14221 (setq x (copy-sequence x))
14222 (org-add-prop-inherited x))
14223 (cdar tags-alist))))
14224 (when (and tags org-use-tag-inheritance
14225 (or (not (eq t org-use-tag-inheritance))
14226 org-tags-exclude-from-inheritance))
14227 ;; selective inheritance, remove uninherited ones
14228 (setcdr (car tags-alist)
14229 (org-remove-uninherited-tags (cdar tags-alist))))
14230 (when (and
14232 ;; eval matcher only when the todo condition is OK
14233 (and (or (not todo-only) (member todo org-not-done-keywords))
14234 (let ((case-fold-search t) (org-trust-scanner-tags t))
14235 (eval matcher)))
14237 ;; Call the skipper, but return t if it does not skip,
14238 ;; so that the `and' form continues evaluating
14239 (progn
14240 (unless (eq action 'sparse-tree) (org-agenda-skip))
14243 ;; Check if timestamps are deselecting this entry
14244 (or (not todo-only)
14245 (and (member todo org-not-done-keywords)
14246 (or (not org-agenda-tags-todo-honor-ignore-options)
14247 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14249 ;; select this headline
14250 (cond
14251 ((eq action 'sparse-tree)
14252 (and org-highlight-sparse-tree-matches
14253 (org-get-heading) (match-end 0)
14254 (org-highlight-new-match
14255 (match-beginning 1) (match-end 1)))
14256 (org-show-context 'tags-tree))
14257 ((eq action 'agenda)
14258 (setq txt (org-agenda-format-item
14260 (concat
14261 (if (eq org-tags-match-list-sublevels 'indented)
14262 (make-string (1- level) ?.) "")
14263 (org-get-heading))
14264 level category
14265 tags-list)
14266 priority (org-get-priority txt))
14267 (goto-char lspos)
14268 (setq marker (org-agenda-new-marker))
14269 (org-add-props txt props
14270 'org-marker marker 'org-hd-marker marker 'org-category category
14271 'todo-state todo
14272 'priority priority 'type "tagsmatch")
14273 (push txt rtn))
14274 ((functionp action)
14275 (setq org-map-continue-from nil)
14276 (save-excursion
14277 (setq rtn1 (funcall action))
14278 (push rtn1 rtn)))
14279 (t (user-error "Invalid action")))
14281 ;; if we are to skip sublevels, jump to end of subtree
14282 (unless org-tags-match-list-sublevels
14283 (org-end-of-subtree t)
14284 (backward-char 1))))
14285 ;; Get the correct position from where to continue
14286 (if org-map-continue-from
14287 (goto-char org-map-continue-from)
14288 (and (= (point) lspos) (end-of-line 1)))))
14289 (when (and (eq action 'sparse-tree)
14290 (not org-sparse-tree-open-archived-trees))
14291 (org-hide-archived-subtrees (point-min) (point-max)))
14292 (nreverse rtn)))
14294 (defun org-remove-uninherited-tags (tags)
14295 "Remove all tags that are not inherited from the list TAGS."
14296 (cond
14297 ((eq org-use-tag-inheritance t)
14298 (if org-tags-exclude-from-inheritance
14299 (org-delete-all org-tags-exclude-from-inheritance tags)
14300 tags))
14301 ((not org-use-tag-inheritance) nil)
14302 ((stringp org-use-tag-inheritance)
14303 (delq nil (mapcar
14304 (lambda (x)
14305 (if (and (string-match org-use-tag-inheritance x)
14306 (not (member x org-tags-exclude-from-inheritance)))
14307 x nil))
14308 tags)))
14309 ((listp org-use-tag-inheritance)
14310 (delq nil (mapcar
14311 (lambda (x)
14312 (if (member x org-use-tag-inheritance) x nil))
14313 tags)))))
14315 (defun org-match-sparse-tree (&optional todo-only match)
14316 "Create a sparse tree according to tags string MATCH.
14317 MATCH can contain positive and negative selection of tags, like
14318 \"+WORK+URGENT-WITHBOSS\".
14319 If optional argument TODO-ONLY is non-nil, only select lines that are
14320 also TODO lines."
14321 (interactive "P")
14322 (org-agenda-prepare-buffers (list (current-buffer)))
14323 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14325 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14327 (defvar org-cached-props nil)
14328 (defun org-cached-entry-get (pom property)
14329 (if (or (eq t org-use-property-inheritance)
14330 (and (stringp org-use-property-inheritance)
14331 (let ((case-fold-search t))
14332 (org-string-match-p org-use-property-inheritance property)))
14333 (and (listp org-use-property-inheritance)
14334 (member-ignore-case property org-use-property-inheritance)))
14335 ;; Caching is not possible, check it directly.
14336 (org-entry-get pom property 'inherit)
14337 ;; Get all properties, so we can do complicated checks easily.
14338 (cdr (assoc-string property
14339 (or org-cached-props
14340 (setq org-cached-props (org-entry-properties pom)))
14341 t))))
14343 (defun org-global-tags-completion-table (&optional files)
14344 "Return the list of all tags in all agenda buffer/files.
14345 Optional FILES argument is a list of files which can be used
14346 instead of the agenda files."
14347 (save-excursion
14348 (org-uniquify
14349 (delq nil
14350 (apply 'append
14351 (mapcar
14352 (lambda (file)
14353 (set-buffer (find-file-noselect file))
14354 (append (org-get-buffer-tags)
14355 (mapcar (lambda (x) (if (stringp (car-safe x))
14356 (list (car-safe x)) nil))
14357 org-tag-alist)))
14358 (if (and files (car files))
14359 files
14360 (org-agenda-files))))))))
14362 (defun org-make-tags-matcher (match)
14363 "Create the TAGS/TODO matcher form for the selection string MATCH.
14365 The variable `todo-only' is scoped dynamically into this function.
14366 It will be set to t if the matcher restricts matching to TODO entries,
14367 otherwise will not be touched.
14369 Returns a cons of the selection string MATCH and the constructed
14370 lisp form implementing the matcher. The matcher is to be evaluated
14371 at an Org entry, with point on the headline, and returns t if the
14372 entry matches the selection string MATCH. The returned lisp form
14373 references two variables with information about the entry, which
14374 must be bound around the form's evaluation: todo, the TODO keyword
14375 at the entry (or nil of none); and tags-list, the list of all tags
14376 at the entry including inherited ones. Additionally, the category
14377 of the entry (if any) must be specified as the text property
14378 'org-category on the headline.
14380 See also `org-scan-tags'.
14382 (declare (special todo-only))
14383 (unless (boundp 'todo-only)
14384 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14385 (unless match
14386 ;; Get a new match request, with completion against the global
14387 ;; tags table and the local tags in current buffer
14388 (let ((org-last-tags-completion-table
14389 (org-uniquify
14390 (delq nil (append (org-get-buffer-tags)
14391 (org-global-tags-completion-table))))))
14392 (setq match (org-completing-read-no-i
14393 "Match: " 'org-tags-completion-function nil nil nil
14394 'org-tags-history))))
14396 ;; Parse the string and create a lisp form
14397 (let ((match0 match)
14398 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14399 minus tag mm
14400 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14401 orterms term orlist re-p str-p level-p level-op time-p
14402 prop-p pn pv po gv rest (start 0) (ss 0))
14403 ;; Expand group tags
14404 (setq match (org-tags-expand match))
14406 ;; Check if there is a TODO part of this match, which would be the
14407 ;; part after a "/". TO make sure that this slash is not part of
14408 ;; a property value to be matched against, we also check that there
14409 ;; is no " after that slash.
14410 ;; First, find the last slash
14411 (while (string-match "/+" match ss)
14412 (setq start (match-beginning 0) ss (match-end 0)))
14413 (if (and (string-match "/+" match start)
14414 (not (save-match-data (string-match "\"" match start))))
14415 ;; match contains also a todo-matching request
14416 (progn
14417 (setq tagsmatch (substring match 0 (match-beginning 0))
14418 todomatch (substring match (match-end 0)))
14419 (if (string-match "^!" todomatch)
14420 (setq todo-only t todomatch (substring todomatch 1)))
14421 (if (string-match "^\\s-*$" todomatch)
14422 (setq todomatch nil)))
14423 ;; only matching tags
14424 (setq tagsmatch match todomatch nil))
14426 ;; Make the tags matcher
14427 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14428 (setq tagsmatcher t)
14429 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14430 (while (setq term (pop orterms))
14431 (while (and (equal (substring term -1) "\\") orterms)
14432 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14433 (while (string-match re term)
14434 (setq rest (substring term (match-end 0))
14435 minus (and (match-end 1)
14436 (equal (match-string 1 term) "-"))
14437 tag (save-match-data (replace-regexp-in-string
14438 "\\\\-" "-"
14439 (match-string 2 term)))
14440 re-p (equal (string-to-char tag) ?{)
14441 level-p (match-end 4)
14442 prop-p (match-end 5)
14443 mm (cond
14444 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14445 (level-p
14446 (setq level-op (org-op-to-function (match-string 3 term)))
14447 `(,level-op level ,(string-to-number
14448 (match-string 4 term))))
14449 (prop-p
14450 (setq pn (match-string 5 term)
14451 po (match-string 6 term)
14452 pv (match-string 7 term)
14453 re-p (equal (string-to-char pv) ?{)
14454 str-p (equal (string-to-char pv) ?\")
14455 time-p (save-match-data
14456 (string-match "^\"[[<].*[]>]\"$" pv))
14457 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14458 (if time-p (setq pv (org-matcher-time pv)))
14459 (setq po (org-op-to-function po (if time-p 'time str-p)))
14460 (cond
14461 ((equal pn "CATEGORY")
14462 (setq gv '(get-text-property (point) 'org-category)))
14463 ((equal pn "TODO")
14464 (setq gv 'todo))
14466 (setq gv `(org-cached-entry-get nil ,pn))))
14467 (if re-p
14468 (if (eq po 'org<>)
14469 `(not (string-match ,pv (or ,gv "")))
14470 `(string-match ,pv (or ,gv "")))
14471 (if str-p
14472 `(,po (or ,gv "") ,pv)
14473 `(,po (string-to-number (or ,gv ""))
14474 ,(string-to-number pv) ))))
14475 (t `(member ,tag tags-list)))
14476 mm (if minus (list 'not mm) mm)
14477 term rest)
14478 (push mm tagsmatcher))
14479 (push (if (> (length tagsmatcher) 1)
14480 (cons 'and tagsmatcher)
14481 (car tagsmatcher))
14482 orlist)
14483 (setq tagsmatcher nil))
14484 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14485 (setq tagsmatcher
14486 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14487 ;; Make the todo matcher
14488 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14489 (setq todomatcher t)
14490 (setq orterms (org-split-string todomatch "|") orlist nil)
14491 (while (setq term (pop orterms))
14492 (while (string-match re term)
14493 (setq minus (and (match-end 1)
14494 (equal (match-string 1 term) "-"))
14495 kwd (match-string 2 term)
14496 re-p (equal (string-to-char kwd) ?{)
14497 term (substring term (match-end 0))
14498 mm (if re-p
14499 `(string-match ,(substring kwd 1 -1) todo)
14500 (list 'equal 'todo kwd))
14501 mm (if minus (list 'not mm) mm))
14502 (push mm todomatcher))
14503 (push (if (> (length todomatcher) 1)
14504 (cons 'and todomatcher)
14505 (car todomatcher))
14506 orlist)
14507 (setq todomatcher nil))
14508 (setq todomatcher (if (> (length orlist) 1)
14509 (cons 'or orlist) (car orlist))))
14511 ;; Return the string and lisp forms of the matcher
14512 (setq matcher (if todomatcher
14513 (list 'and tagsmatcher todomatcher)
14514 tagsmatcher))
14515 (when todo-only
14516 (setq matcher (list 'and '(member todo org-not-done-keywords)
14517 matcher)))
14518 (cons match0 matcher)))
14520 (defun org-tags-expand (match &optional single-as-list downcased)
14521 "Expand group tags in MATCH.
14523 This replaces every group tag in MATCH with a regexp tag search.
14524 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14525 will be replaced like this:
14527 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14528 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14529 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14531 Replacing by a regexp preserves the structure of the match.
14532 E.g., this expansion
14534 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14536 will match anything tagged with \"Lab\" and \"Home\", or tagged
14537 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14539 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14540 assumed to be a single group tag, and the function will return
14541 the list of tags in this group.
14543 When DOWNCASE is non-nil, expand downcased TAGS."
14544 (if org-group-tags
14545 (let* ((case-fold-search t)
14546 (stable org-mode-syntax-table)
14547 (tal (or org-tag-groups-alist-for-agenda
14548 org-tag-groups-alist))
14549 (tal (if downcased
14550 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14551 (tml (mapcar 'car tal))
14552 (rtnmatch match) rpl)
14553 ;; @ and _ are allowed as word-components in tags
14554 (modify-syntax-entry ?@ "w" stable)
14555 (modify-syntax-entry ?_ "w" stable)
14556 (while (and tml
14557 (with-syntax-table stable
14558 (string-match
14559 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14560 (regexp-opt tml) "\\>\\)") rtnmatch)))
14561 (let* ((dir (match-string 1 rtnmatch))
14562 (tag (match-string 2 rtnmatch))
14563 (tag (if downcased (downcase tag) tag)))
14564 (setq tml (delete tag tml))
14565 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14566 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14567 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14568 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14569 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14570 (if single-as-list
14571 (or (reverse rpl) (list rtnmatch))
14572 rtnmatch))
14573 (if single-as-list (list (if downcased (downcase match) match))
14574 match)))
14576 (defun org-op-to-function (op &optional stringp)
14577 "Turn an operator into the appropriate function."
14578 (setq op
14579 (cond
14580 ((equal op "<" ) '(< string< org-time<))
14581 ((equal op ">" ) '(> org-string> org-time>))
14582 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14583 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14584 ((member op '("=" "==")) '(= string= org-time=))
14585 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14586 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14588 (defun org<> (a b) (not (= a b)))
14589 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14590 (defun org-string>= (a b) (not (string< a b)))
14591 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14592 (defun org-string<> (a b) (not (string= a b)))
14593 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14594 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14595 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14596 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14597 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14598 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14599 (defun org-2ft (s)
14600 "Convert S to a floating point time.
14601 If S is already a number, just return it. If it is a string, parse
14602 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14603 (cond
14604 ((numberp s) s)
14605 ((stringp s)
14606 (condition-case nil
14607 (float-time (apply 'encode-time (org-parse-time-string s)))
14608 (error 0.)))
14609 (t 0.)))
14611 (defun org-time-today ()
14612 "Time in seconds today at 0:00.
14613 Returns the float number of seconds since the beginning of the
14614 epoch to the beginning of today (00:00)."
14615 (float-time (apply 'encode-time
14616 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14618 (defun org-matcher-time (s)
14619 "Interpret a time comparison value."
14620 (save-match-data
14621 (cond
14622 ((string= s "<now>") (float-time))
14623 ((string= s "<today>") (org-time-today))
14624 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14625 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14626 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14627 (+ (org-time-today)
14628 (* (string-to-number (match-string 1 s))
14629 (cdr (assoc (match-string 2 s)
14630 '(("d" . 86400.0) ("w" . 604800.0)
14631 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14632 (t (org-2ft s)))))
14634 (defun org-match-any-p (re list)
14635 "Does re match any element of list?"
14636 (setq list (mapcar (lambda (x) (string-match re x)) list))
14637 (delq nil list))
14639 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14640 (defvar org-tags-overlay (make-overlay 1 1))
14641 (org-detach-overlay org-tags-overlay)
14643 (defun org-get-local-tags-at (&optional pos)
14644 "Get a list of tags defined in the current headline."
14645 (org-get-tags-at pos 'local))
14647 (defun org-get-local-tags ()
14648 "Get a list of tags defined in the current headline."
14649 (org-get-tags-at nil 'local))
14651 (defun org-get-tags-at (&optional pos local)
14652 "Get a list of all headline tags applicable at POS.
14653 POS defaults to point. If tags are inherited, the list contains
14654 the targets in the same sequence as the headlines appear, i.e.
14655 the tags of the current headline come last.
14656 When LOCAL is non-nil, only return tags from the current headline,
14657 ignore inherited ones."
14658 (interactive)
14659 (if (and org-trust-scanner-tags
14660 (or (not pos) (equal pos (point)))
14661 (not local))
14662 org-scanner-tags
14663 (let (tags ltags lastpos parent)
14664 (save-excursion
14665 (save-restriction
14666 (widen)
14667 (goto-char (or pos (point)))
14668 (save-match-data
14669 (catch 'done
14670 (condition-case nil
14671 (progn
14672 (org-back-to-heading t)
14673 (while (not (equal lastpos (point)))
14674 (setq lastpos (point))
14675 (when (looking-at
14676 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14677 (setq ltags (org-split-string
14678 (org-match-string-no-properties 1) ":"))
14679 (when parent
14680 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14681 (setq tags (append
14682 (if parent
14683 (org-remove-uninherited-tags ltags)
14684 ltags)
14685 tags)))
14686 (or org-use-tag-inheritance (throw 'done t))
14687 (if local (throw 'done t))
14688 (or (org-up-heading-safe) (error nil))
14689 (setq parent t)))
14690 (error nil)))))
14691 (if local
14692 tags
14693 (reverse (delete-dups
14694 (reverse (append
14695 (org-remove-uninherited-tags
14696 org-file-tags) tags)))))))))
14698 (defun org-add-prop-inherited (s)
14699 (add-text-properties 0 (length s) '(inherited t) s)
14702 (defun org-toggle-tag (tag &optional onoff)
14703 "Toggle the tag TAG for the current line.
14704 If ONOFF is `on' or `off', don't toggle but set to this state."
14705 (let (res current)
14706 (save-excursion
14707 (org-back-to-heading t)
14708 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14709 (point-at-eol) t)
14710 (progn
14711 (setq current (match-string 1))
14712 (replace-match ""))
14713 (setq current ""))
14714 (setq current (nreverse (org-split-string current ":")))
14715 (cond
14716 ((eq onoff 'on)
14717 (setq res t)
14718 (or (member tag current) (push tag current)))
14719 ((eq onoff 'off)
14720 (or (not (member tag current)) (setq current (delete tag current))))
14721 (t (if (member tag current)
14722 (setq current (delete tag current))
14723 (setq res t)
14724 (push tag current))))
14725 (end-of-line 1)
14726 (if current
14727 (progn
14728 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14729 (org-set-tags nil t))
14730 (delete-horizontal-space))
14731 (run-hooks 'org-after-tags-change-hook))
14732 res))
14734 (defun org-align-tags-here (to-col)
14735 ;; Assumes that this is a headline
14736 "Align tags on the current headline to TO-COL."
14737 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14738 (beginning-of-line 1)
14739 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14740 (< pos (match-beginning 2)))
14741 (progn
14742 (setq tags-l (- (match-end 2) (match-beginning 2)))
14743 (goto-char (match-beginning 1))
14744 (insert " ")
14745 (delete-region (point) (1+ (match-beginning 2)))
14746 (setq ncol (max (current-column)
14747 (1+ col)
14748 (if (> to-col 0)
14749 to-col
14750 (- (abs to-col) tags-l))))
14751 (setq p (point))
14752 (insert (make-string (- ncol (current-column)) ?\ ))
14753 (setq ncol (current-column))
14754 (when indent-tabs-mode (tabify p (point-at-eol)))
14755 (org-move-to-column (min ncol col)))
14756 (goto-char pos))))
14758 (defun org-set-tags-command (&optional arg just-align)
14759 "Call the set-tags command for the current entry."
14760 (interactive "P")
14761 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14762 (org-set-tags arg just-align)
14763 (save-excursion
14764 (unless (and (org-region-active-p)
14765 org-loop-over-headlines-in-active-region)
14766 (org-back-to-heading t))
14767 (org-set-tags arg just-align))))
14769 (defun org-set-tags-to (data)
14770 "Set the tags of the current entry to DATA, replacing the current tags.
14771 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14772 If DATA is nil or the empty string, any tags will be removed."
14773 (interactive "sTags: ")
14774 (setq data
14775 (cond
14776 ((eq data nil) "")
14777 ((equal data "") "")
14778 ((stringp data)
14779 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14780 ":"))
14781 ((listp data)
14782 (concat ":" (mapconcat 'identity data ":") ":"))))
14783 (when data
14784 (save-excursion
14785 (org-back-to-heading t)
14786 (when (looking-at org-complex-heading-regexp)
14787 (if (match-end 5)
14788 (progn
14789 (goto-char (match-beginning 5))
14790 (insert data)
14791 (delete-region (point) (point-at-eol))
14792 (org-set-tags nil 'align))
14793 (goto-char (point-at-eol))
14794 (insert " " data)
14795 (org-set-tags nil 'align)))
14796 (beginning-of-line 1)
14797 (if (looking-at ".*?\\([ \t]+\\)$")
14798 (delete-region (match-beginning 1) (match-end 1))))))
14800 (defun org-align-all-tags ()
14801 "Align the tags i all headings."
14802 (interactive)
14803 (save-excursion
14804 (or (ignore-errors (org-back-to-heading t))
14805 (outline-next-heading))
14806 (if (org-at-heading-p)
14807 (org-set-tags t)
14808 (message "No headings"))))
14810 (defvar org-indent-indentation-per-level)
14811 (defun org-set-tags (&optional arg just-align)
14812 "Set the tags for the current headline.
14813 With prefix ARG, realign all tags in headings in the current buffer.
14814 When JUST-ALIGN is non-nil, only align tags."
14815 (interactive "P")
14816 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14817 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14818 'region-start-level 'region))
14819 org-loop-over-headlines-in-active-region)
14820 (org-map-entries
14821 ;; We don't use ARG and JUST-ALIGN here because these args
14822 ;; are not useful when looping over headlines.
14823 `(org-set-tags)
14824 org-loop-over-headlines-in-active-region
14825 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14826 (let* ((re org-outline-regexp-bol)
14827 (current (unless arg (org-get-tags-string)))
14828 (col (current-column))
14829 (org-setting-tags t)
14830 table current-tags inherited-tags ; computed below when needed
14831 tags p0 c0 c1 rpl di tc level)
14832 (if arg
14833 (save-excursion
14834 (goto-char (point-min))
14835 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14836 (while (re-search-forward re nil t)
14837 (org-set-tags nil t)
14838 (end-of-line 1)))
14839 (message "All tags realigned to column %d" org-tags-column))
14840 (if just-align
14841 (setq tags current)
14842 ;; Get a new set of tags from the user
14843 (save-excursion
14844 (setq table (append org-tag-persistent-alist
14845 (or org-tag-alist (org-get-buffer-tags))
14846 (and
14847 org-complete-tags-always-offer-all-agenda-tags
14848 (org-global-tags-completion-table
14849 (org-agenda-files))))
14850 org-last-tags-completion-table table
14851 current-tags (org-split-string current ":")
14852 inherited-tags (nreverse
14853 (nthcdr (length current-tags)
14854 (nreverse (org-get-tags-at))))
14855 tags
14856 (if (or (eq t org-use-fast-tag-selection)
14857 (and org-use-fast-tag-selection
14858 (delq nil (mapcar 'cdr table))))
14859 (org-fast-tag-selection
14860 current-tags inherited-tags table
14861 (if org-fast-tag-selection-include-todo
14862 org-todo-key-alist))
14863 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14864 (org-trim
14865 (org-icompleting-read "Tags: "
14866 'org-tags-completion-function
14867 nil nil current 'org-tags-history))))))
14868 (while (string-match "[-+&]+" tags)
14869 ;; No boolean logic, just a list
14870 (setq tags (replace-match ":" t t tags))))
14872 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14874 (if org-tags-sort-function
14875 (setq tags (mapconcat 'identity
14876 (sort (org-split-string
14877 tags (org-re "[^[:alnum:]_@#%]+"))
14878 org-tags-sort-function) ":")))
14880 (if (string-match "\\`[\t ]*\\'" tags)
14881 (setq tags "")
14882 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14883 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14885 ;; Insert new tags at the correct column
14886 (beginning-of-line 1)
14887 (setq level (or (and (looking-at org-outline-regexp)
14888 (- (match-end 0) (point) 1))
14890 (cond
14891 ((and (equal current "") (equal tags "")))
14892 ((re-search-forward
14893 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14894 (point-at-eol) t)
14895 (if (equal tags "")
14896 (setq rpl "")
14897 (goto-char (match-beginning 0))
14898 (setq c0 (current-column)
14899 ;; compute offset for the case of org-indent-mode active
14900 di (if (org-bound-and-true-p org-indent-mode)
14901 (* (1- org-indent-indentation-per-level) (1- level))
14903 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14904 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14905 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14906 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14907 (replace-match rpl t t)
14908 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14909 tags)
14910 (t (error "Tags alignment failed")))
14911 (org-move-to-column col)
14912 (unless just-align
14913 (run-hooks 'org-after-tags-change-hook))))))
14915 (defun org-change-tag-in-region (beg end tag off)
14916 "Add or remove TAG for each entry in the region.
14917 This works in the agenda, and also in an org-mode buffer."
14918 (interactive
14919 (list (region-beginning) (region-end)
14920 (let ((org-last-tags-completion-table
14921 (if (derived-mode-p 'org-mode)
14922 (org-uniquify
14923 (delq nil (append (org-get-buffer-tags)
14924 (org-global-tags-completion-table))))
14925 (org-global-tags-completion-table))))
14926 (org-icompleting-read
14927 "Tag: " 'org-tags-completion-function nil nil nil
14928 'org-tags-history))
14929 (progn
14930 (message "[s]et or [r]emove? ")
14931 (equal (read-char-exclusive) ?r))))
14932 (if (fboundp 'deactivate-mark) (deactivate-mark))
14933 (let ((agendap (equal major-mode 'org-agenda-mode))
14934 l1 l2 m buf pos newhead (cnt 0))
14935 (goto-char end)
14936 (setq l2 (1- (org-current-line)))
14937 (goto-char beg)
14938 (setq l1 (org-current-line))
14939 (loop for l from l1 to l2 do
14940 (org-goto-line l)
14941 (setq m (get-text-property (point) 'org-hd-marker))
14942 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14943 (and agendap m))
14944 (setq buf (if agendap (marker-buffer m) (current-buffer))
14945 pos (if agendap m (point)))
14946 (with-current-buffer buf
14947 (save-excursion
14948 (save-restriction
14949 (goto-char pos)
14950 (setq cnt (1+ cnt))
14951 (org-toggle-tag tag (if off 'off 'on))
14952 (setq newhead (org-get-heading)))))
14953 (and agendap (org-agenda-change-all-lines newhead m))))
14954 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14956 (defun org-tags-completion-function (string predicate &optional flag)
14957 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14958 (confirm (lambda (x) (stringp (car x)))))
14959 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14960 (setq s1 (match-string 1 string)
14961 s2 (match-string 2 string))
14962 (setq s1 "" s2 string))
14963 (cond
14964 ((eq flag nil)
14965 ;; try completion
14966 (setq rtn (try-completion s2 ctable confirm))
14967 (if (stringp rtn)
14968 (setq rtn
14969 (concat s1 s2 (substring rtn (length s2))
14970 (if (and org-add-colon-after-tag-completion
14971 (assoc rtn ctable))
14972 ":" ""))))
14973 rtn)
14974 ((eq flag t)
14975 ;; all-completions
14976 (all-completions s2 ctable confirm))
14977 ((eq flag 'lambda)
14978 ;; exact match?
14979 (assoc s2 ctable)))))
14981 (defun org-fast-tag-insert (kwd tags face &optional end)
14982 "Insert KDW, and the TAGS, the latter with face FACE.
14983 Also insert END."
14984 (insert (format "%-12s" (concat kwd ":"))
14985 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14986 (or end "")))
14988 (defun org-fast-tag-show-exit (flag)
14989 (save-excursion
14990 (org-goto-line 3)
14991 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14992 (replace-match ""))
14993 (when flag
14994 (end-of-line 1)
14995 (org-move-to-column (- (window-width) 19) t)
14996 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14998 (defun org-set-current-tags-overlay (current prefix)
14999 "Add an overlay to CURRENT tag with PREFIX."
15000 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15001 (if (featurep 'xemacs)
15002 (org-overlay-display org-tags-overlay (concat prefix s)
15003 'secondary-selection)
15004 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15005 (org-overlay-display org-tags-overlay (concat prefix s)))))
15007 (defvar org-last-tag-selection-key nil)
15008 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15009 "Fast tag selection with single keys.
15010 CURRENT is the current list of tags in the headline, INHERITED is the
15011 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15012 possibly with grouping information. TODO-TABLE is a similar table with
15013 TODO keywords, should these have keys assigned to them.
15014 If the keys are nil, a-z are automatically assigned.
15015 Returns the new tags string, or nil to not change the current settings."
15016 (let* ((fulltable (append table todo-table))
15017 (maxlen (apply 'max (mapcar
15018 (lambda (x)
15019 (if (stringp (car x)) (string-width (car x)) 0))
15020 fulltable)))
15021 (buf (current-buffer))
15022 (expert (eq org-fast-tag-selection-single-key 'expert))
15023 (buffer-tags nil)
15024 (fwidth (+ maxlen 3 1 3))
15025 (ncol (/ (- (window-width) 4) fwidth))
15026 (i-face 'org-done)
15027 (c-face 'org-todo)
15028 tg cnt e c char c1 c2 ntable tbl rtn
15029 ov-start ov-end ov-prefix
15030 (exit-after-next org-fast-tag-selection-single-key)
15031 (done-keywords org-done-keywords)
15032 groups ingroup)
15033 (save-excursion
15034 (beginning-of-line 1)
15035 (if (looking-at
15036 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15037 (setq ov-start (match-beginning 1)
15038 ov-end (match-end 1)
15039 ov-prefix "")
15040 (setq ov-start (1- (point-at-eol))
15041 ov-end (1+ ov-start))
15042 (skip-chars-forward "^\n\r")
15043 (setq ov-prefix
15044 (concat
15045 (buffer-substring (1- (point)) (point))
15046 (if (> (current-column) org-tags-column)
15048 (make-string (- org-tags-column (current-column)) ?\ ))))))
15049 (move-overlay org-tags-overlay ov-start ov-end)
15050 (save-window-excursion
15051 (if expert
15052 (set-buffer (get-buffer-create " *Org tags*"))
15053 (delete-other-windows)
15054 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15055 (org-switch-to-buffer-other-window " *Org tags*"))
15056 (erase-buffer)
15057 (org-set-local 'org-done-keywords done-keywords)
15058 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15059 (org-fast-tag-insert "Current" current c-face "\n\n")
15060 (org-fast-tag-show-exit exit-after-next)
15061 (org-set-current-tags-overlay current ov-prefix)
15062 (setq tbl fulltable char ?a cnt 0)
15063 (while (setq e (pop tbl))
15064 (cond
15065 ((equal (car e) :startgroup)
15066 (push '() groups) (setq ingroup t)
15067 (when (not (= cnt 0))
15068 (setq cnt 0)
15069 (insert "\n"))
15070 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15071 ((equal (car e) :endgroup)
15072 (setq ingroup nil cnt 0)
15073 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15074 ((equal e '(:newline))
15075 (when (not (= cnt 0))
15076 (setq cnt 0)
15077 (insert "\n")
15078 (setq e (car tbl))
15079 (while (equal (car tbl) '(:newline))
15080 (insert "\n")
15081 (setq tbl (cdr tbl)))))
15082 ((equal e '(:grouptags)) nil)
15084 (setq tg (copy-sequence (car e)) c2 nil)
15085 (if (cdr e)
15086 (setq c (cdr e))
15087 ;; automatically assign a character.
15088 (setq c1 (string-to-char
15089 (downcase (substring
15090 tg (if (= (string-to-char tg) ?@) 1 0)))))
15091 (if (or (rassoc c1 ntable) (rassoc c1 table))
15092 (while (or (rassoc char ntable) (rassoc char table))
15093 (setq char (1+ char)))
15094 (setq c2 c1))
15095 (setq c (or c2 char)))
15096 (if ingroup (push tg (car groups)))
15097 (setq tg (org-add-props tg nil 'face
15098 (cond
15099 ((not (assoc tg table))
15100 (org-get-todo-face tg))
15101 ((member tg current) c-face)
15102 ((member tg inherited) i-face))))
15103 (if (equal (caar tbl) :grouptags)
15104 (org-add-props tg nil 'face 'org-tag-group))
15105 (if (and (= cnt 0) (not ingroup)) (insert " "))
15106 (insert "[" c "] " tg (make-string
15107 (- fwidth 4 (length tg)) ?\ ))
15108 (push (cons tg c) ntable)
15109 (when (= (setq cnt (1+ cnt)) ncol)
15110 (insert "\n")
15111 (if ingroup (insert " "))
15112 (setq cnt 0)))))
15113 (setq ntable (nreverse ntable))
15114 (insert "\n")
15115 (goto-char (point-min))
15116 (if (not expert) (org-fit-window-to-buffer))
15117 (setq rtn
15118 (catch 'exit
15119 (while t
15120 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15121 (if (not groups) "no " "")
15122 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15123 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15124 (setq org-last-tag-selection-key c)
15125 (cond
15126 ((= c ?\r) (throw 'exit t))
15127 ((= c ?!)
15128 (setq groups (not groups))
15129 (goto-char (point-min))
15130 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15131 ((= c ?\C-c)
15132 (if (not expert)
15133 (org-fast-tag-show-exit
15134 (setq exit-after-next (not exit-after-next)))
15135 (setq expert nil)
15136 (delete-other-windows)
15137 (set-window-buffer (split-window-vertically) " *Org tags*")
15138 (org-switch-to-buffer-other-window " *Org tags*")
15139 (org-fit-window-to-buffer)))
15140 ((or (= c ?\C-g)
15141 (and (= c ?q) (not (rassoc c ntable))))
15142 (org-detach-overlay org-tags-overlay)
15143 (setq quit-flag t))
15144 ((= c ?\ )
15145 (setq current nil)
15146 (if exit-after-next (setq exit-after-next 'now)))
15147 ((= c ?\t)
15148 (condition-case nil
15149 (setq tg (org-icompleting-read
15150 "Tag: "
15151 (or buffer-tags
15152 (with-current-buffer buf
15153 (org-get-buffer-tags)))))
15154 (quit (setq tg "")))
15155 (when (string-match "\\S-" tg)
15156 (add-to-list 'buffer-tags (list tg))
15157 (if (member tg current)
15158 (setq current (delete tg current))
15159 (push tg current)))
15160 (if exit-after-next (setq exit-after-next 'now)))
15161 ((setq e (rassoc c todo-table) tg (car e))
15162 (with-current-buffer buf
15163 (save-excursion (org-todo tg)))
15164 (if exit-after-next (setq exit-after-next 'now)))
15165 ((setq e (rassoc c ntable) tg (car e))
15166 (if (member tg current)
15167 (setq current (delete tg current))
15168 (loop for g in groups do
15169 (if (member tg g)
15170 (mapc (lambda (x)
15171 (setq current (delete x current)))
15172 g)))
15173 (push tg current))
15174 (if exit-after-next (setq exit-after-next 'now))))
15176 ;; Create a sorted list
15177 (setq current
15178 (sort current
15179 (lambda (a b)
15180 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15181 (if (eq exit-after-next 'now) (throw 'exit t))
15182 (goto-char (point-min))
15183 (beginning-of-line 2)
15184 (delete-region (point) (point-at-eol))
15185 (org-fast-tag-insert "Current" current c-face)
15186 (org-set-current-tags-overlay current ov-prefix)
15187 (while (re-search-forward
15188 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15189 (setq tg (match-string 1))
15190 (add-text-properties
15191 (match-beginning 1) (match-end 1)
15192 (list 'face
15193 (cond
15194 ((member tg current) c-face)
15195 ((member tg inherited) i-face)
15196 (t (get-text-property (match-beginning 1) 'face))))))
15197 (goto-char (point-min)))))
15198 (org-detach-overlay org-tags-overlay)
15199 (if rtn
15200 (mapconcat 'identity current ":")
15201 nil))))
15203 (defun org-get-tags-string ()
15204 "Get the TAGS string in the current headline."
15205 (unless (org-at-heading-p t)
15206 (user-error "Not on a heading"))
15207 (save-excursion
15208 (beginning-of-line 1)
15209 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15210 (org-match-string-no-properties 1)
15211 "")))
15213 (defun org-get-tags ()
15214 "Get the list of tags specified in the current headline."
15215 (org-split-string (org-get-tags-string) ":"))
15217 (defun org-get-buffer-tags ()
15218 "Get a table of all tags used in the buffer, for completion."
15219 (org-with-wide-buffer
15220 (goto-char (point-min))
15221 (let ((tag-re (concat org-outline-regexp-bol
15222 "\\(?:.*?[ \t]\\)?"
15223 (org-re ":\\([[:alnum:]_@#%:]+\\):[ \t]*$")))
15224 tags)
15225 (while (re-search-forward tag-re nil t)
15226 (dolist (tag (org-split-string (org-match-string-no-properties 1) ":"))
15227 (push tag tags)))
15228 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15230 ;;;; The mapping API
15232 (defun org-map-entries (func &optional match scope &rest skip)
15233 "Call FUNC at each headline selected by MATCH in SCOPE.
15235 FUNC is a function or a lisp form. The function will be called without
15236 arguments, with the cursor positioned at the beginning of the headline.
15237 The return values of all calls to the function will be collected and
15238 returned as a list.
15240 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15241 does not need to preserve point. After evaluation, the cursor will be
15242 moved to the end of the line (presumably of the headline of the
15243 processed entry) and search continues from there. Under some
15244 circumstances, this may not produce the wanted results. For example,
15245 if you have removed (e.g. archived) the current (sub)tree it could
15246 mean that the next entry will be skipped entirely. In such cases, you
15247 can specify the position from where search should continue by making
15248 FUNC set the variable `org-map-continue-from' to the desired buffer
15249 position.
15251 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15252 Only headlines that are matched by this query will be considered during
15253 the iteration. When MATCH is nil or t, all headlines will be
15254 visited by the iteration.
15256 SCOPE determines the scope of this command. It can be any of:
15258 nil The current buffer, respecting the restriction if any
15259 tree The subtree started with the entry at point
15260 region The entries within the active region, if any
15261 region-start-level
15262 The entries within the active region, but only those at
15263 the same level than the first one.
15264 file The current buffer, without restriction
15265 file-with-archives
15266 The current buffer, and any archives associated with it
15267 agenda All agenda files
15268 agenda-with-archives
15269 All agenda files with any archive files associated with them
15270 \(file1 file2 ...)
15271 If this is a list, all files in the list will be scanned
15273 The remaining args are treated as settings for the skipping facilities of
15274 the scanner. The following items can be given here:
15276 archive skip trees with the archive tag
15277 comment skip trees with the COMMENT keyword
15278 function or Emacs Lisp form:
15279 will be used as value for `org-agenda-skip-function', so
15280 whenever the function returns a position, FUNC will not be
15281 called for that entry and search will continue from the
15282 position returned
15284 If your function needs to retrieve the tags including inherited tags
15285 at the *current* entry, you can use the value of the variable
15286 `org-scanner-tags' which will be much faster than getting the value
15287 with `org-get-tags-at'. If your function gets properties with
15288 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15289 to t around the call to `org-entry-properties' to get the same speedup.
15290 Note that if your function moves around to retrieve tags and properties at
15291 a *different* entry, you cannot use these techniques."
15292 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15293 (not (org-region-active-p)))
15294 (let* ((org-agenda-archives-mode nil) ; just to make sure
15295 (org-agenda-skip-archived-trees (memq 'archive skip))
15296 (org-agenda-skip-comment-trees (memq 'comment skip))
15297 (org-agenda-skip-function
15298 (car (org-delete-all '(comment archive) skip)))
15299 (org-tags-match-list-sublevels t)
15300 (start-level (eq scope 'region-start-level))
15301 matcher file res
15302 org-todo-keywords-for-agenda
15303 org-done-keywords-for-agenda
15304 org-todo-keyword-alist-for-agenda
15305 org-tag-alist-for-agenda
15306 todo-only)
15308 (cond
15309 ((eq match t) (setq matcher t))
15310 ((eq match nil) (setq matcher t))
15311 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15313 (save-excursion
15314 (save-restriction
15315 (cond ((eq scope 'tree)
15316 (org-back-to-heading t)
15317 (org-narrow-to-subtree)
15318 (setq scope nil))
15319 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15320 (org-region-active-p))
15321 ;; If needed, set start-level to a string like "2"
15322 (when start-level
15323 (save-excursion
15324 (goto-char (region-beginning))
15325 (unless (org-at-heading-p) (outline-next-heading))
15326 (setq start-level (org-current-level))))
15327 (narrow-to-region (region-beginning)
15328 (save-excursion
15329 (goto-char (region-end))
15330 (unless (and (bolp) (org-at-heading-p))
15331 (outline-next-heading))
15332 (point)))
15333 (setq scope nil)))
15335 (if (not scope)
15336 (progn
15337 (org-agenda-prepare-buffers
15338 (list (buffer-file-name (current-buffer))))
15339 (setq res (org-scan-tags func matcher todo-only start-level)))
15340 ;; Get the right scope
15341 (cond
15342 ((and scope (listp scope) (symbolp (car scope)))
15343 (setq scope (eval scope)))
15344 ((eq scope 'agenda)
15345 (setq scope (org-agenda-files t)))
15346 ((eq scope 'agenda-with-archives)
15347 (setq scope (org-agenda-files t))
15348 (setq scope (org-add-archive-files scope)))
15349 ((eq scope 'file)
15350 (setq scope (list (buffer-file-name))))
15351 ((eq scope 'file-with-archives)
15352 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15353 (org-agenda-prepare-buffers scope)
15354 (while (setq file (pop scope))
15355 (with-current-buffer (org-find-base-buffer-visiting file)
15356 (save-excursion
15357 (save-restriction
15358 (widen)
15359 (goto-char (point-min))
15360 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15361 res)))
15363 ;;; Properties API
15365 (defconst org-special-properties
15366 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15367 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15368 "The special properties valid in Org mode.
15369 These are properties that are not defined in the property drawer,
15370 but in some other way.")
15372 (defconst org-default-properties
15373 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15374 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15375 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15376 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15377 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15378 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15379 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15380 "Some properties that are used by Org mode for various purposes.
15381 Being in this list makes sure that they are offered for completion.")
15383 (defun org--update-property-plist (key val props)
15384 "Associate KEY to VAL in alist PROPS.
15385 Modifications are made by side-effect. Return new alist."
15386 (let* ((appending (string= (substring key -1) "+"))
15387 (key (if appending (substring key 0 -1) key))
15388 (old (assoc-string key props t)))
15389 (if (not old) (cons (cons key val) props)
15390 (setcdr old (if appending (concat (cdr old) " " val) val))
15391 props)))
15393 (defun org-get-property-block (&optional beg force)
15394 "Return the (beg . end) range of the body of the property drawer.
15395 BEG is the beginning of the current subtree, or of the part
15396 before the first headline. If it is not given, it will be found.
15397 If the drawer does not exist, create it if FORCE is non-nil, or
15398 return nil."
15399 (org-with-wide-buffer
15400 (when beg (goto-char beg))
15401 (unless (org-before-first-heading-p)
15402 (let ((beg (cond (beg)
15403 ((or (not (featurep 'org-inlinetask))
15404 (org-inlinetask-in-task-p))
15405 (org-back-to-heading t))
15406 (t (org-with-limited-levels (org-back-to-heading t))))))
15407 (forward-line)
15408 (when (org-looking-at-p org-planning-line-re) (forward-line))
15409 (cond ((looking-at org-property-drawer-re)
15410 (forward-line)
15411 (cons (point) (progn (goto-char (match-end 0))
15412 (line-beginning-position))))
15413 (force
15414 (goto-char beg)
15415 (org-insert-property-drawer)
15416 (let ((pos (save-excursion (search-forward ":END:")
15417 (line-beginning-position))))
15418 (cons pos pos))))))))
15420 (defun org-at-property-p ()
15421 "Non-nil when point is inside a property drawer.
15422 See `org-property-re' for match data, if applicable."
15423 (save-excursion
15424 (beginning-of-line)
15425 (and (looking-at org-property-re)
15426 (let ((property-drawer (save-match-data (org-get-property-block))))
15427 (and property-drawer (< (point) (cdr property-drawer)))))))
15429 (defun org-property-action ()
15430 "Do an action on properties."
15431 (interactive)
15432 (unless (org-at-property-p) (user-error "Not at a property"))
15433 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15434 (let ((c (read-char-exclusive)))
15435 (case c
15436 (?s (call-interactively #'org-set-property))
15437 (?d (call-interactively #'org-delete-property))
15438 (?D (call-interactively #'org-delete-property-globally))
15439 (?c (call-interactively #'org-compute-property-at-point))
15440 (otherwise (user-error "No such property action %c" c)))))
15442 (defun org-inc-effort ()
15443 "Increment the value of the effort property in the current entry."
15444 (interactive)
15445 (org-set-effort nil t))
15447 (defvar org-clock-effort) ; Defined in org-clock.el.
15448 (defvar org-clock-current-task) ; Defined in org-clock.el.
15449 (defun org-set-effort (&optional value increment)
15450 "Set the effort property of the current entry.
15451 With numerical prefix arg, use the nth allowed value, 0 stands for the
15452 10th allowed value.
15454 When INCREMENT is non-nil, set the property to the next allowed value."
15455 (interactive "P")
15456 (if (equal value 0) (setq value 10))
15457 (let* ((completion-ignore-case t)
15458 (prop org-effort-property)
15459 (cur (org-entry-get nil prop))
15460 (allowed (org-property-get-allowed-values nil prop 'table))
15461 (existing (mapcar 'list (org-property-values prop)))
15462 (heading (nth 4 (org-heading-components)))
15464 (val (cond
15465 ((stringp value) value)
15466 ((and allowed (integerp value))
15467 (or (car (nth (1- value) allowed))
15468 (car (org-last allowed))))
15469 ((and allowed increment)
15470 (or (caadr (member (list cur) allowed))
15471 (user-error "Allowed effort values are not set")))
15472 (allowed
15473 (message "Select 1-9,0, [RET%s]: %s"
15474 (if cur (concat "=" cur) "")
15475 (mapconcat 'car allowed " "))
15476 (setq rpl (read-char-exclusive))
15477 (if (equal rpl ?\r)
15479 (setq rpl (- rpl ?0))
15480 (if (equal rpl 0) (setq rpl 10))
15481 (if (and (> rpl 0) (<= rpl (length allowed)))
15482 (car (nth (1- rpl) allowed))
15483 (org-completing-read "Effort: " allowed nil))))
15485 (let (org-completion-use-ido org-completion-use-iswitchb)
15486 (org-completing-read
15487 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15488 (concat "[" cur "]") "")
15489 ": ")
15490 existing nil nil "" nil cur))))))
15491 (unless (equal (org-entry-get nil prop) val)
15492 (org-entry-put nil prop val))
15493 (org-refresh-property
15494 '((effort . identity)
15495 (effort-minutes . org-duration-string-to-minutes))
15496 val)
15497 (when (string= heading org-clock-current-task)
15498 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15499 (org-clock-update-mode-line))
15500 (message "%s is now %s" prop val)))
15502 (defun org-entry-properties (&optional pom which)
15503 "Get all properties of the current entry.
15505 When POM is a buffer position, get all properties from the entry
15506 there instead.
15508 This includes the TODO keyword, the tags, time strings for
15509 deadline, scheduled, and clocking, and any additional properties
15510 defined in the entry.
15512 If WHICH is nil or `all', get all properties. If WHICH is
15513 `special' or `standard', only get that subclass. If WHICH is
15514 a string, only get that property.
15516 Return value is an alist. Keys are properties, as upcased
15517 strings."
15518 (org-with-point-at pom
15519 (when (and (derived-mode-p 'org-mode)
15520 (ignore-errors (org-back-to-heading t)))
15521 (catch 'exit
15522 (let* ((beg (point))
15523 (specific (and (stringp which) (upcase which)))
15524 (which (cond ((not specific) which)
15525 ((member specific org-special-properties) 'special)
15526 (t 'standard)))
15527 props)
15528 ;; Get the special properties, like TODO and TAGS.
15529 (when (memq which '(nil all special))
15530 (when (or (not specific) (string= specific "CLOCKSUM"))
15531 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15532 (when clocksum
15533 (push (cons "CLOCKSUM"
15534 (org-columns-number-to-string
15535 (/ (float clocksum) 60.) 'add_times))
15536 props)))
15537 (when specific (throw 'exit props)))
15538 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15539 (let ((clocksumt (get-text-property (point)
15540 :org-clock-minutes-today)))
15541 (when clocksumt
15542 (push (cons "CLOCKSUM_T"
15543 (org-columns-number-to-string
15544 (/ (float clocksumt) 60.) 'add_times))
15545 props)))
15546 (when specific (throw 'exit props)))
15547 (when (or (not specific) (string= specific "ITEM"))
15548 (when (looking-at org-complex-heading-regexp)
15549 (push (cons "ITEM"
15550 (concat
15551 (org-match-string-no-properties 1)
15552 (let ((title (org-match-string-no-properties 4)))
15553 (when (org-string-nw-p title)
15554 (concat " " (org-remove-tabs title))))))
15555 props))
15556 (when specific (throw 'exit props)))
15557 (when (or (not specific) (string= specific "TODO"))
15558 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15559 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15560 (when specific (throw 'exit props)))
15561 (when (or (not specific) (string= specific "PRIORITY"))
15562 (when (looking-at org-priority-regexp)
15563 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15564 (when specific (throw 'exit props)))
15565 (when (or (not specific) (string= specific "FILE"))
15566 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15567 props)
15568 (when specific (throw 'exit props)))
15569 (when (or (not specific) (string= specific "TAGS"))
15570 (let ((value (org-string-nw-p (org-get-tags-string))))
15571 (when value (push (cons "TAGS" value) props)))
15572 (when specific (throw 'exit props)))
15573 (when (or (not specific) (string= specific "ALLTAGS"))
15574 (let ((value (org-get-tags-at)))
15575 (when value
15576 (push (cons "ALLTAGS"
15577 (format ":%s:" (mapconcat #'identity value ":")))
15578 props)))
15579 (when specific (throw 'exit props)))
15580 (when (or (not specific) (string= specific "BLOCKED"))
15581 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15582 (when specific (throw 'exit props)))
15583 (when (or (not specific)
15584 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15585 (forward-line)
15586 (when (org-looking-at-p org-planning-line-re)
15587 (end-of-line)
15588 (let ((bol (line-beginning-position))
15589 ;; Backward compatibility: time keywords used to
15590 ;; be configurable (before 8.3). Make sure we
15591 ;; get the correct keyword.
15592 (key-assoc `(("CLOSED" . ,org-closed-string)
15593 ("DEADLINE" . ,org-deadline-string)
15594 ("SCHEDULED" . ,org-scheduled-string))))
15595 (dolist (pair (if specific (list (assoc specific key-assoc))
15596 key-assoc))
15597 (save-excursion
15598 (when (search-backward (cdr pair) bol t)
15599 (goto-char (match-end 0))
15600 (skip-chars-forward " \t")
15601 (and (looking-at org-ts-regexp-both)
15602 (push (cons (car pair)
15603 (org-match-string-no-properties 0))
15604 props)))))))
15605 (when specific (throw 'exit props)))
15606 (when (or (not specific)
15607 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15608 (let ((find-ts
15609 (lambda (end ts)
15610 (let ((regexp (if (or (string= specific "TIMESTAMP")
15611 (assoc "TIMESTAMP_IA" ts))
15612 org-ts-regexp
15613 org-ts-regexp-both)))
15614 (catch 'next
15615 (while (re-search-forward regexp end t)
15616 (backward-char)
15617 (let ((object (org-element-context)))
15618 ;; Accept to match timestamps in node
15619 ;; properties, too.
15620 (when (memq (org-element-type object)
15621 '(node-property timestamp))
15622 (let ((type
15623 (org-element-property :type object)))
15624 (cond
15625 ((and (memq type '(active active-range))
15626 (not (equal specific "TIMESTAMP_IA")))
15627 (unless (assoc "TIMESTAMP" ts)
15628 (push (cons "TIMESTAMP"
15629 (org-element-property
15630 :raw-value object))
15632 (when specific (throw 'exit ts))))
15633 ((and (memq type '(inactive inactive-range))
15634 (not (string= specific "TIMESTAMP")))
15635 (unless (assoc "TIMESTAMP_IA" ts)
15636 (push (cons "TIMESTAMP_IA"
15637 (org-element-property
15638 :raw-value object))
15640 (when specific (throw 'exit ts))))))
15641 ;; Both timestamp types are found,
15642 ;; move to next part.
15643 (when (= (length ts) 2) (throw 'next ts)))))
15644 ts)))))
15645 (goto-char beg)
15646 ;; First look for timestamps within headline.
15647 (let ((ts (funcall find-ts (line-end-position) nil)))
15648 (if (= (length ts) 2) (setq props (nconc ts props))
15649 (forward-line)
15650 ;; Then find timestamps in the section, skipping
15651 ;; planning line.
15652 (when (org-looking-at-p org-planning-line-re)
15653 (forward-line))
15654 (let ((end (save-excursion (outline-next-heading))))
15655 (setq props (nconc (funcall find-ts end ts) props))))))))
15656 ;; Get the standard properties, like :PROP:.
15657 (when (memq which '(nil all standard))
15658 ;; If we are looking after a specific property, delegate
15659 ;; to `org-entry-get', which is faster. However, make an
15660 ;; exception for "CATEGORY", since it can be also set
15661 ;; through keywords (i.e. #+CATEGORY).
15662 (if (and specific (not (equal specific "CATEGORY")))
15663 (let ((value (org-entry-get beg specific nil t)))
15664 (throw 'exit (and value (list (cons specific value)))))
15665 (let ((range (org-get-property-block beg)))
15666 (when range
15667 (let ((end (cdr range)) seen-base)
15668 (goto-char (car range))
15669 ;; Unlike to `org--update-property-plist', we
15670 ;; handle the case where base values is found
15671 ;; after its extension. We also forbid standard
15672 ;; properties to be named as special properties.
15673 (while (re-search-forward org-property-re end t)
15674 (let* ((key (upcase (org-match-string-no-properties 2)))
15675 (extendp (org-string-match-p "\\+\\'" key))
15676 (key-base (if extendp (substring key 0 -1) key))
15677 (value (org-match-string-no-properties 3)))
15678 (cond
15679 ((member-ignore-case key-base org-special-properties))
15680 (extendp
15681 (setq props
15682 (org--update-property-plist key value props)))
15683 ((member key seen-base))
15684 (t (push key seen-base)
15685 (let ((p (assoc-string key props t)))
15686 (if p (setcdr p (concat value " " (cdr p)))
15687 (push (cons key value) props))))))))))))
15688 (unless (assoc "CATEGORY" props)
15689 (push (cons "CATEGORY" (org-get-category beg)) props)
15690 (when (string= specific "CATEGORY") (throw 'exit props)))
15691 ;; Return value.
15692 (append (get-text-property beg 'org-summaries) props))))))
15694 (defun org-entry-get (pom property &optional inherit literal-nil)
15695 "Get value of PROPERTY for entry or content at point-or-marker POM.
15697 If INHERIT is non-nil and the entry does not have the property,
15698 then also check higher levels of the hierarchy. If INHERIT is
15699 the symbol `selective', use inheritance only if the setting in
15700 `org-use-property-inheritance' selects PROPERTY for inheritance.
15702 If the property is present but empty, the return value is the
15703 empty string. If the property is not present at all, nil is
15704 returned. In any other case, return the value as a string.
15705 Search is case-insensitive.
15707 If LITERAL-NIL is set, return the string value \"nil\" as
15708 a string, do not interpret it as the list atom nil. This is used
15709 for inheritance when a \"nil\" value can supersede a non-nil
15710 value higher up the hierarchy."
15711 (org-with-point-at pom
15712 (cond
15713 ((and inherit
15714 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15715 (org-entry-get-with-inheritance property literal-nil))
15716 ((member-ignore-case property org-special-properties)
15717 ;; We need a special property. Use `org-entry-properties' to
15718 ;; retrieve it, but specify the wanted property.
15719 (cdr (assoc-string property (org-entry-properties nil property))))
15721 (let ((range (org-get-property-block)))
15722 (when range
15723 (let* ((case-fold-search t)
15724 (end (cdr range))
15725 (props
15726 (let ((global
15727 (or (assoc-string property org-file-properties t)
15728 (assoc-string property org-global-properties t)
15729 (assoc-string
15730 property org-global-properties-fixed t))))
15731 ;; Make sure to not re-use GLOBAL as
15732 ;; `org--update-property-plist' would alter it by
15733 ;; side-effect.
15734 (and global (list (cons property (cdr global))))))
15735 (find-value
15736 (lambda (key)
15737 (when (re-search-forward (org-re-property key nil t) end t)
15738 (setq props
15739 (org--update-property-plist
15740 key (org-match-string-no-properties 3) props))))))
15741 (goto-char (car range))
15742 ;; Find base value.
15743 (save-excursion (funcall find-value property))
15744 ;; Find additional values.
15745 (let ((property+ (concat property "+")))
15746 (while (funcall find-value property+)))
15747 ;; Return final value.
15748 (let ((val (cdr (assoc-string property props t))))
15749 (if literal-nil val (org-not-nil val))))))))))
15751 (defun org-property-or-variable-value (var &optional inherit)
15752 "Check if there is a property fixing the value of VAR.
15753 If yes, return this value. If not, return the current value of the variable."
15754 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15755 (if (and prop (stringp prop) (string-match "\\S-" prop))
15756 (read prop)
15757 (symbol-value var))))
15759 (defun org-entry-delete (pom property)
15760 "Delete the property PROPERTY from entry at point-or-marker POM."
15761 (unless (member property org-special-properties)
15762 (org-with-point-at pom
15763 (let ((range (org-get-property-block)))
15764 (when range
15765 (let ((begin (car range))
15766 (end (copy-marker (cdr range))))
15767 (goto-char begin)
15768 (when (re-search-forward (org-re-property property nil t) end t)
15769 (delete-region (match-beginning 0) (line-beginning-position 2))
15770 ;; If drawer is empty, remove it altogether.
15771 (when (= begin end)
15772 (delete-region (line-beginning-position 0)
15773 (line-beginning-position 2)))
15774 (set-marker end nil))))))))
15776 ;; Multi-values properties are properties that contain multiple values
15777 ;; These values are assumed to be single words, separated by whitespace.
15778 (defun org-entry-add-to-multivalued-property (pom property value)
15779 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15780 (let* ((old (org-entry-get pom property))
15781 (values (and old (org-split-string old "[ \t]"))))
15782 (setq value (org-entry-protect-space value))
15783 (unless (member value values)
15784 (setq values (append values (list value)))
15785 (org-entry-put pom property
15786 (mapconcat 'identity values " ")))))
15788 (defun org-entry-remove-from-multivalued-property (pom property value)
15789 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15790 (let* ((old (org-entry-get pom property))
15791 (values (and old (org-split-string old "[ \t]"))))
15792 (setq value (org-entry-protect-space value))
15793 (when (member value values)
15794 (setq values (delete value values))
15795 (org-entry-put pom property
15796 (mapconcat 'identity values " ")))))
15798 (defun org-entry-member-in-multivalued-property (pom property value)
15799 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15800 (let* ((old (org-entry-get pom property))
15801 (values (and old (org-split-string old "[ \t]"))))
15802 (setq value (org-entry-protect-space value))
15803 (member value values)))
15805 (defun org-entry-get-multivalued-property (pom property)
15806 "Return a list of values in a multivalued property."
15807 (let* ((value (org-entry-get pom property))
15808 (values (and value (org-split-string value "[ \t]"))))
15809 (mapcar 'org-entry-restore-space values)))
15811 (defun org-entry-put-multivalued-property (pom property &rest values)
15812 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15813 VALUES should be a list of strings. Spaces will be protected."
15814 (org-entry-put pom property
15815 (mapconcat 'org-entry-protect-space values " "))
15816 (let* ((value (org-entry-get pom property))
15817 (values (and value (org-split-string value "[ \t]"))))
15818 (mapcar 'org-entry-restore-space values)))
15820 (defun org-entry-protect-space (s)
15821 "Protect spaces and newline in string S."
15822 (while (string-match " " s)
15823 (setq s (replace-match "%20" t t s)))
15824 (while (string-match "\n" s)
15825 (setq s (replace-match "%0A" t t s)))
15828 (defun org-entry-restore-space (s)
15829 "Restore spaces and newline in string S."
15830 (while (string-match "%20" s)
15831 (setq s (replace-match " " t t s)))
15832 (while (string-match "%0A" s)
15833 (setq s (replace-match "\n" t t s)))
15836 (defvar org-entry-property-inherited-from (make-marker)
15837 "Marker pointing to the entry from where a property was inherited.
15838 Each call to `org-entry-get-with-inheritance' will set this marker to the
15839 location of the entry where the inheritance search matched. If there was
15840 no match, the marker will point nowhere.
15841 Note that also `org-entry-get' calls this function, if the INHERIT flag
15842 is set.")
15844 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15845 "Get PROPERTY of entry or content at point, search higher levels if needed.
15846 The search will stop at the first ancestor which has the property defined.
15847 If the value found is \"nil\", return nil to show that the property
15848 should be considered as undefined (this is the meaning of nil here).
15849 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15850 (move-marker org-entry-property-inherited-from nil)
15851 (let (value)
15852 (org-with-wide-buffer
15853 (catch 'exit
15854 (while t
15855 (when (setq value (org-entry-get nil property nil literal-nil))
15856 (org-back-to-heading t)
15857 (move-marker org-entry-property-inherited-from (point))
15858 (throw 'exit nil))
15859 (or (org-up-heading-safe) (throw 'exit nil)))))
15860 (unless value
15861 (setq value
15862 (cdr (or (assoc-string property org-file-properties t)
15863 (assoc-string property org-global-properties t)
15864 (assoc-string property org-global-properties-fixed t)))))
15865 (if literal-nil value (org-not-nil value))))
15867 (defvar org-property-changed-functions nil
15868 "Hook called when the value of a property has changed.
15869 Each hook function should accept two arguments, the name of the property
15870 and the new value.")
15872 (defun org-entry-put (pom property value)
15873 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15875 If the value is `nil', it is converted to the empty string. If
15876 it is not a string, an error is raised.
15878 PROPERTY can be any regular property (see
15879 `org-special-properties'). It can also be \"TODO\",
15880 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15882 For the last two properties, VALUE may have any of the special
15883 values \"earlier\" and \"later\". The function then increases or
15884 decreases scheduled or deadline date by one day."
15885 (cond ((null value) (setq value ""))
15886 ((not (stringp value)) (error "Properties values should be strings")))
15887 (org-with-point-at pom
15888 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15889 (org-back-to-heading t)
15890 (org-with-limited-levels (org-back-to-heading t)))
15891 (let ((beg (point)))
15892 (cond
15893 ((equal property "TODO")
15894 (cond ((not (org-string-nw-p value)) (setq value 'none))
15895 ((not (member value org-todo-keywords-1))
15896 (user-error "\"%s\" is not a valid TODO state" value)))
15897 (org-todo value)
15898 (org-set-tags nil 'align))
15899 ((equal property "PRIORITY")
15900 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15901 (org-set-tags nil 'align))
15902 ((equal property "SCHEDULED")
15903 (forward-line)
15904 (if (and (org-looking-at-p org-planning-line-re)
15905 (re-search-forward
15906 org-scheduled-time-regexp (line-end-position) t))
15907 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15908 ((string= value "later") (org-timestamp-change 1 'day))
15909 ((string= value "") (org-schedule '(4)))
15910 (t (org-schedule nil value)))
15911 (if (member value '("earlier" "later" ""))
15912 (call-interactively #'org-schedule)
15913 (org-schedule nil value))))
15914 ((equal property "DEADLINE")
15915 (forward-line)
15916 (if (and (org-looking-at-p org-planning-line-re)
15917 (re-search-forward
15918 org-deadline-time-regexp (line-end-position) t))
15919 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15920 ((string= value "later") (org-timestamp-change 1 'day))
15921 ((string= value "") (org-deadline '(4)))
15922 (t (org-deadline nil value)))
15923 (if (member value '("earlier" "later" ""))
15924 (call-interactively #'org-deadline)
15925 (org-deadline nil value))))
15926 ((member property org-special-properties)
15927 (error "The %s property cannot be set with `org-entry-put'" property))
15929 (let* ((range (org-get-property-block beg 'force))
15930 (end (cdr range))
15931 (case-fold-search t))
15932 (goto-char (car range))
15933 (if (re-search-forward (org-re-property property nil t) end t)
15934 (progn (delete-region (match-beginning 0) (match-end 0))
15935 (goto-char (match-beginning 0)))
15936 (goto-char end)
15937 (insert "\n")
15938 (backward-char))
15939 (insert ":" property ":")
15940 (when value (insert " " value))
15941 (org-indent-line)))))
15942 (run-hook-with-args 'org-property-changed-functions property value)))
15944 (defun org-buffer-property-keys (&optional specials defaults columns)
15945 "Get all property keys in the current buffer.
15947 When SPECIALS is non-nil, also list the special properties that
15948 reflect things like tags and TODO state.
15950 When DEFAULTS is non-nil, also include properties that has
15951 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15952 DESCRIPTION, LOCATION, and LOGGING and others.
15954 When COLUMNS in non-nil, also include property names given in
15955 COLUMN formats in the current buffer."
15956 (let ((case-fold-search t)
15957 (props (append
15958 (and specials org-special-properties)
15959 (and defaults (cons org-effort-property org-default-properties))
15960 nil)))
15961 (org-with-wide-buffer
15962 (goto-char (point-min))
15963 (while (re-search-forward org-property-start-re nil t)
15964 (let ((range (org-get-property-block)))
15965 (catch 'skip
15966 (unless range
15967 (when (and (not (org-before-first-heading-p))
15968 (y-or-n-p (format "Malformed drawer at %d, repair?"
15969 (line-beginning-position))))
15970 (org-get-property-block nil t))
15971 (throw 'skip nil))
15972 (goto-char (car range))
15973 (let ((begin (car range))
15974 (end (cdr range)))
15975 ;; Make sure that found property block is not located
15976 ;; before current point, as it would generate an infloop.
15977 ;; It can happen, for example, in the following
15978 ;; situation:
15980 ;; * Headline
15981 ;; :PROPERTIES:
15982 ;; ...
15983 ;; :END:
15984 ;; *************** Inlinetask
15985 ;; #+BEGIN_EXAMPLE
15986 ;; :PROPERTIES:
15987 ;; #+END_EXAMPLE
15989 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
15990 (while (< (point) end)
15991 (let ((p (progn (looking-at org-property-re)
15992 (org-match-string-no-properties 2))))
15993 ;; Only add true property name, not extension symbol.
15994 (add-to-list 'props
15995 (if (not (org-string-match-p "\\+\\'" p)) p
15996 (substring p 0 -1))))
15997 (forward-line))))
15998 (outline-next-heading)))
15999 (when columns
16000 (goto-char (point-min))
16001 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16002 (let ((element (org-element-at-point)))
16003 (when (memq (org-element-type element) '(keyword node-property))
16004 (let ((value (org-element-property :value element))
16005 (start 0))
16006 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16007 (setq start (match-end 0))
16008 (let ((p (org-match-string-no-properties 1 value)))
16009 (unless (member-ignore-case p org-special-properties)
16010 (add-to-list 'props p))))))))))
16011 (sort props (lambda (a b) (string< (upcase a) (upcase b))))))
16013 (defun org-property-values (key)
16014 "List all non-nil values of property KEY in current buffer."
16015 (org-with-wide-buffer
16016 (goto-char (point-min))
16017 (let ((case-fold-search t)
16018 (re (org-re-property key))
16019 values)
16020 (while (re-search-forward re nil t)
16021 (add-to-list 'values (org-entry-get (point) key)))
16022 values)))
16024 (defun org-insert-property-drawer ()
16025 "Insert a property drawer into the current entry."
16026 (org-with-wide-buffer
16027 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16028 (org-back-to-heading t)
16029 (org-with-limited-levels (org-back-to-heading t)))
16030 (forward-line)
16031 (when (org-looking-at-p org-planning-line-re) (forward-line))
16032 (unless (org-looking-at-p org-property-drawer-re)
16033 (let ((inhibit-read-only t))
16034 (unless (bolp) (insert "\n"))
16035 (let ((begin (point)))
16036 (insert ":PROPERTIES:\n:END:\n")
16037 (org-indent-region begin (point)))))))
16039 (defun org-insert-drawer (&optional arg drawer)
16040 "Insert a drawer at point.
16042 When optional argument ARG is non-nil, insert a property drawer.
16044 Optional argument DRAWER, when non-nil, is a string representing
16045 drawer's name. Otherwise, the user is prompted for a name.
16047 If a region is active, insert the drawer around that region
16048 instead.
16050 Point is left between drawer's boundaries."
16051 (interactive "P")
16052 (let* ((drawer (if arg "PROPERTIES"
16053 (or drawer (read-from-minibuffer "Drawer: ")))))
16054 (cond
16055 ;; With C-u, fall back on `org-insert-property-drawer'
16056 (arg (org-insert-property-drawer))
16057 ;; Check validity of suggested drawer's name.
16058 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
16059 (user-error "Invalid drawer name"))
16060 ;; With an active region, insert a drawer at point.
16061 ((not (org-region-active-p))
16062 (progn
16063 (unless (bolp) (insert "\n"))
16064 (insert (format ":%s:\n\n:END:\n" drawer))
16065 (forward-line -2)))
16066 ;; Otherwise, insert the drawer at point
16068 (let ((rbeg (region-beginning))
16069 (rend (copy-marker (region-end))))
16070 (unwind-protect
16071 (progn
16072 (goto-char rbeg)
16073 (beginning-of-line)
16074 (when (save-excursion
16075 (re-search-forward org-outline-regexp-bol rend t))
16076 (user-error "Drawers cannot contain headlines"))
16077 ;; Position point at the beginning of the first
16078 ;; non-blank line in region. Insert drawer's opening
16079 ;; there, then indent it.
16080 (org-skip-whitespace)
16081 (beginning-of-line)
16082 (insert ":" drawer ":\n")
16083 (forward-line -1)
16084 (indent-for-tab-command)
16085 ;; Move point to the beginning of the first blank line
16086 ;; after the last non-blank line in region. Insert
16087 ;; drawer's closing, then indent it.
16088 (goto-char rend)
16089 (skip-chars-backward " \r\t\n")
16090 (insert "\n:END:")
16091 (deactivate-mark t)
16092 (indent-for-tab-command)
16093 (unless (eolp) (insert "\n")))
16094 ;; Clear marker, whatever the outcome of insertion is.
16095 (set-marker rend nil)))))))
16097 (defvar org-property-set-functions-alist nil
16098 "Property set function alist.
16099 Each entry should have the following format:
16101 (PROPERTY . READ-FUNCTION)
16103 The read function will be called with the same argument as
16104 `org-completing-read'.")
16106 (defun org-set-property-function (property)
16107 "Get the function that should be used to set PROPERTY.
16108 This is computed according to `org-property-set-functions-alist'."
16109 (or (cdr (assoc property org-property-set-functions-alist))
16110 'org-completing-read))
16112 (defun org-read-property-value (property)
16113 "Read PROPERTY value from user."
16114 (let* ((completion-ignore-case t)
16115 (allowed (org-property-get-allowed-values nil property 'table))
16116 (cur (org-entry-get nil property))
16117 (prompt (concat property " value"
16118 (if (and cur (string-match "\\S-" cur))
16119 (concat " [" cur "]") "") ": "))
16120 (set-function (org-set-property-function property))
16121 (val (if allowed
16122 (funcall set-function prompt allowed nil
16123 (not (get-text-property 0 'org-unrestricted
16124 (caar allowed))))
16125 (let (org-completion-use-ido org-completion-use-iswitchb)
16126 (funcall set-function prompt
16127 (mapcar 'list (org-property-values property))
16128 nil nil "" nil cur)))))
16129 (org-trim val)))
16131 (defvar org-last-set-property nil)
16132 (defvar org-last-set-property-value nil)
16133 (defun org-read-property-name ()
16134 "Read a property name."
16135 (let* ((completion-ignore-case t)
16136 (keys (org-buffer-property-keys nil t t))
16137 (default-prop (or (save-excursion
16138 (save-match-data
16139 (beginning-of-line)
16140 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
16141 (null (string= (match-string 1) "END"))
16142 (match-string 1))))
16143 org-last-set-property))
16144 (property (org-icompleting-read
16145 (concat "Property"
16146 (if default-prop (concat " [" default-prop "]") "")
16147 ": ")
16148 (mapcar 'list keys)
16149 nil nil nil nil
16150 default-prop)))
16151 (if (member property keys)
16152 property
16153 (or (cdr (assoc (downcase property)
16154 (mapcar (lambda (x) (cons (downcase x) x))
16155 keys)))
16156 property))))
16158 (defun org-set-property-and-value (use-last)
16159 "Allow to set [PROPERTY]: [value] direction from prompt.
16160 When use-default, don't even ask, just use the last
16161 \"[PROPERTY]: [value]\" string from the history."
16162 (interactive "P")
16163 (let* ((completion-ignore-case t)
16164 (pv (or (and use-last org-last-set-property-value)
16165 (org-completing-read
16166 "Enter a \"[Property]: [value]\" pair: "
16167 nil nil nil nil nil
16168 org-last-set-property-value)))
16169 prop val)
16170 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16171 (setq prop (match-string 1 pv)
16172 val (match-string 2 pv))
16173 (org-set-property prop val))))
16175 (defun org-set-property (property value)
16176 "In the current entry, set PROPERTY to VALUE.
16177 When called interactively, this will prompt for a property name, offering
16178 completion on existing and default properties. And then it will prompt
16179 for a value, offering completion either on allowed values (via an inherited
16180 xxx_ALL property) or on existing values in other instances of this property
16181 in the current file."
16182 (interactive (list nil nil))
16183 (let* ((property (or property (org-read-property-name)))
16184 (value (or value (org-read-property-value property)))
16185 (fn (cdr (assoc property org-properties-postprocess-alist))))
16186 (setq org-last-set-property property)
16187 (setq org-last-set-property-value (concat property ": " value))
16188 ;; Possibly postprocess the inserted value:
16189 (when fn (setq value (funcall fn value)))
16190 (unless (equal (org-entry-get nil property) value)
16191 (org-entry-put nil property value))))
16193 (defun org-delete-property (property)
16194 "In the current entry, delete PROPERTY."
16195 (interactive
16196 (let* ((completion-ignore-case t)
16197 (cat (org-entry-get (point) "CATEGORY"))
16198 (props0 (org-entry-properties nil 'standard))
16199 (props (if cat props0
16200 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16201 (prop (if (< 1 (length props))
16202 (org-icompleting-read "Property: " props nil t)
16203 (caar props))))
16204 (list prop)))
16205 (if (not property)
16206 (message "No property to delete in this entry")
16207 (org-entry-delete nil property)
16208 (message "Property \"%s\" deleted" property)))
16210 (defun org-delete-property-globally (property)
16211 "Remove PROPERTY globally, from all entries."
16212 (interactive
16213 (let* ((completion-ignore-case t)
16214 (prop (org-icompleting-read
16215 "Globally remove property: "
16216 (mapcar 'list (org-buffer-property-keys)))))
16217 (list prop)))
16218 (save-excursion
16219 (save-restriction
16220 (widen)
16221 (goto-char (point-min))
16222 (let ((cnt 0))
16223 (while (re-search-forward
16224 (org-re-property property)
16225 nil t)
16226 (setq cnt (1+ cnt))
16227 (delete-region (match-beginning 0) (1+ (point-at-eol))))
16228 (message "Property \"%s\" removed from %d entries" property cnt)))))
16230 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16232 (defun org-compute-property-at-point ()
16233 "Compute the property at point.
16234 This looks for an enclosing column format, extracts the operator and
16235 then applies it to the property in the column format's scope."
16236 (interactive)
16237 (unless (org-at-property-p)
16238 (user-error "Not at a property"))
16239 (let ((prop (org-match-string-no-properties 2)))
16240 (org-columns-get-format-and-top-level)
16241 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16242 (user-error "No operator defined for property %s" prop))
16243 (org-columns-compute prop)))
16245 (defvar org-property-allowed-value-functions nil
16246 "Hook for functions supplying allowed values for a specific property.
16247 The functions must take a single argument, the name of the property, and
16248 return a flat list of allowed values. If \":ETC\" is one of
16249 the values, this means that these values are intended as defaults for
16250 completion, but that other values should be allowed too.
16251 The functions must return nil if they are not responsible for this
16252 property.")
16254 (defun org-property-get-allowed-values (pom property &optional table)
16255 "Get allowed values for the property PROPERTY.
16256 When TABLE is non-nil, return an alist that can directly be used for
16257 completion."
16258 (let (vals)
16259 (cond
16260 ((equal property "TODO")
16261 (setq vals (org-with-point-at pom
16262 (append org-todo-keywords-1 '("")))))
16263 ((equal property "PRIORITY")
16264 (let ((n org-lowest-priority))
16265 (while (>= n org-highest-priority)
16266 (push (char-to-string n) vals)
16267 (setq n (1- n)))))
16268 ((member property org-special-properties))
16269 ((setq vals (run-hook-with-args-until-success
16270 'org-property-allowed-value-functions property)))
16272 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16273 (when (and vals (string-match "\\S-" vals))
16274 (setq vals (car (read-from-string (concat "(" vals ")"))))
16275 (setq vals (mapcar (lambda (x)
16276 (cond ((stringp x) x)
16277 ((numberp x) (number-to-string x))
16278 ((symbolp x) (symbol-name x))
16279 (t "???")))
16280 vals)))))
16281 (when (member ":ETC" vals)
16282 (setq vals (remove ":ETC" vals))
16283 (org-add-props (car vals) '(org-unrestricted t)))
16284 (if table (mapcar 'list vals) vals)))
16286 (defun org-property-previous-allowed-value (&optional previous)
16287 "Switch to the next allowed value for this property."
16288 (interactive)
16289 (org-property-next-allowed-value t))
16291 (defun org-property-next-allowed-value (&optional previous)
16292 "Switch to the next allowed value for this property."
16293 (interactive)
16294 (unless (org-at-property-p)
16295 (user-error "Not at a property"))
16296 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16297 (key (match-string 2))
16298 (value (match-string 3))
16299 (allowed (or (org-property-get-allowed-values (point) key)
16300 (and (member value '("[ ]" "[-]" "[X]"))
16301 '("[ ]" "[X]"))))
16302 (heading (save-match-data (nth 4 (org-heading-components))))
16303 nval)
16304 (unless allowed
16305 (user-error "Allowed values for this property have not been defined"))
16306 (if previous (setq allowed (reverse allowed)))
16307 (if (member value allowed)
16308 (setq nval (car (cdr (member value allowed)))))
16309 (setq nval (or nval (car allowed)))
16310 (if (equal nval value)
16311 (user-error "Only one allowed value for this property"))
16312 (org-at-property-p)
16313 (replace-match (concat " :" key ": " nval) t t)
16314 (org-indent-line)
16315 (beginning-of-line 1)
16316 (skip-chars-forward " \t")
16317 (when (equal prop org-effort-property)
16318 (org-refresh-property
16319 '((effort . identity)
16320 (effort-minutes . org-duration-string-to-minutes))
16321 nval)
16322 (when (string= org-clock-current-task heading)
16323 (setq org-clock-effort nval)
16324 (org-clock-update-mode-line)))
16325 (run-hook-with-args 'org-property-changed-functions key nval)))
16327 (defun org-find-olp (path &optional this-buffer)
16328 "Return a marker pointing to the entry at outline path OLP.
16329 If anything goes wrong, throw an error.
16330 You can wrap this call to catch the error like this:
16332 (condition-case msg
16333 (org-mobile-locate-entry (match-string 4))
16334 (error (nth 1 msg)))
16336 The return value will then be either a string with the error message,
16337 or a marker if everything is OK.
16339 If THIS-BUFFER is set, the outline path does not contain a file,
16340 only headings."
16341 (let* ((file (if this-buffer buffer-file-name (pop path)))
16342 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16343 (level 1)
16344 (lmin 1)
16345 (lmax 1)
16346 limit re end found pos heading cnt flevel)
16347 (unless buffer (error "File not found :%s" file))
16348 (with-current-buffer buffer
16349 (save-excursion
16350 (save-restriction
16351 (widen)
16352 (setq limit (point-max))
16353 (goto-char (point-min))
16354 (while (setq heading (pop path))
16355 (setq re (format org-complex-heading-regexp-format
16356 (regexp-quote heading)))
16357 (setq cnt 0 pos (point))
16358 (while (re-search-forward re end t)
16359 (setq level (- (match-end 1) (match-beginning 1)))
16360 (if (and (>= level lmin) (<= level lmax))
16361 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16362 (when (= cnt 0) (error "Heading not found on level %d: %s"
16363 lmax heading))
16364 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16365 lmax heading))
16366 (goto-char found)
16367 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16368 (setq end (save-excursion (org-end-of-subtree t t))))
16369 (when (org-at-heading-p)
16370 (point-marker)))))))
16372 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16373 "Find node HEADING in BUFFER.
16374 Return a marker to the heading if it was found, or nil if not.
16375 If POS-ONLY is set, return just the position instead of a marker.
16377 The heading text must match exact, but it may have a TODO keyword,
16378 a priority cookie and tags in the standard locations."
16379 (with-current-buffer (or buffer (current-buffer))
16380 (save-excursion
16381 (save-restriction
16382 (widen)
16383 (goto-char (point-min))
16384 (let (case-fold-search)
16385 (if (re-search-forward
16386 (format org-complex-heading-regexp-format
16387 (regexp-quote heading)) nil t)
16388 (if pos-only
16389 (match-beginning 0)
16390 (move-marker (make-marker) (match-beginning 0)))))))))
16392 (defun org-find-exact-heading-in-directory (heading &optional dir)
16393 "Find Org node headline HEADING in all .org files in directory DIR.
16394 When the target headline is found, return a marker to this location."
16395 (let ((files (directory-files (or dir default-directory)
16396 t "\\`[^.#].*\\.org\\'"))
16397 file visiting m buffer)
16398 (catch 'found
16399 (while (setq file (pop files))
16400 (message "trying %s" file)
16401 (setq visiting (org-find-base-buffer-visiting file))
16402 (setq buffer (or visiting (find-file-noselect file)))
16403 (setq m (org-find-exact-headline-in-buffer
16404 heading buffer))
16405 (when (and (not m) (not visiting)) (kill-buffer buffer))
16406 (and m (throw 'found m))))))
16408 (defun org-find-entry-with-id (ident)
16409 "Locate the entry that contains the ID property with exact value IDENT.
16410 IDENT can be a string, a symbol or a number, this function will search for
16411 the string representation of it.
16412 Return the position where this entry starts, or nil if there is no such entry."
16413 (interactive "sID: ")
16414 (let ((id (cond
16415 ((stringp ident) ident)
16416 ((symbol-name ident) (symbol-name ident))
16417 ((numberp ident) (number-to-string ident))
16418 (t (error "IDENT %s must be a string, symbol or number" ident))))
16419 (case-fold-search nil))
16420 (save-excursion
16421 (save-restriction
16422 (widen)
16423 (goto-char (point-min))
16424 (when (re-search-forward
16425 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16426 nil t)
16427 (org-back-to-heading t)
16428 (point))))))
16430 ;;;; Timestamps
16432 (defvar org-last-changed-timestamp nil)
16433 (defvar org-last-inserted-timestamp nil
16434 "The last time stamp inserted with `org-insert-time-stamp'.")
16435 (defvar org-ts-what) ; dynamically scoped parameter
16437 (defun org-time-stamp (arg &optional inactive)
16438 "Prompt for a date/time and insert a time stamp.
16439 If the user specifies a time like HH:MM or if this command is
16440 called with at least one prefix argument, the time stamp contains
16441 the date and the time. Otherwise, only the date is be included.
16443 All parts of a date not specified by the user is filled in from
16444 the current date/time. So if you just press return without
16445 typing anything, the time stamp will represent the current
16446 date/time.
16448 If there is already a timestamp at the cursor, it will be
16449 modified.
16451 With two universal prefix arguments, insert an active timestamp
16452 with the current time without prompting the user.
16454 When called from lisp, the timestamp is inactive if INACTIVE is
16455 non-nil."
16456 (interactive "P")
16457 (let* ((ts nil)
16458 (default-time
16459 ;; Default time is either today, or, when entering a range,
16460 ;; the range start.
16461 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16462 (save-excursion
16463 (re-search-backward
16464 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16465 (- (point) 20) t)))
16466 (apply 'encode-time (org-parse-time-string (match-string 1)))
16467 (current-time)))
16468 (default-input (and ts (org-get-compact-tod ts)))
16469 (repeater (save-excursion
16470 (save-match-data
16471 (beginning-of-line)
16472 (when (re-search-forward
16473 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16474 (save-excursion (progn (end-of-line) (point))) t)
16475 (match-string 0)))))
16476 org-time-was-given org-end-time-was-given time)
16477 (cond
16478 ((and (org-at-timestamp-p t)
16479 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16480 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16481 (insert "--")
16482 (setq time (let ((this-command this-command))
16483 (org-read-date arg 'totime nil nil
16484 default-time default-input inactive)))
16485 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16486 ((org-at-timestamp-p t)
16487 (setq time (let ((this-command this-command))
16488 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16489 (when (org-at-timestamp-p t) ; just to get the match data
16490 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16491 (replace-match "")
16492 (setq org-last-changed-timestamp
16493 (org-insert-time-stamp
16494 time (or org-time-was-given arg)
16495 inactive nil nil (list org-end-time-was-given)))
16496 (when repeater (goto-char (1- (point))) (insert " " repeater)
16497 (setq org-last-changed-timestamp
16498 (concat (substring org-last-inserted-timestamp 0 -1)
16499 " " repeater ">"))))
16500 (message "Timestamp updated"))
16501 ((equal arg '(16))
16502 (org-insert-time-stamp (current-time) t inactive))
16504 (setq time (let ((this-command this-command))
16505 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16506 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16507 nil nil (list org-end-time-was-given))))))
16509 ;; FIXME: can we use this for something else, like computing time differences?
16510 (defun org-get-compact-tod (s)
16511 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16512 (let* ((t1 (match-string 1 s))
16513 (h1 (string-to-number (match-string 2 s)))
16514 (m1 (string-to-number (match-string 3 s)))
16515 (t2 (and (match-end 4) (match-string 5 s)))
16516 (h2 (and t2 (string-to-number (match-string 6 s))))
16517 (m2 (and t2 (string-to-number (match-string 7 s))))
16518 dh dm)
16519 (if (not t2)
16521 (setq dh (- h2 h1) dm (- m2 m1))
16522 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16523 (concat t1 "+" (number-to-string dh)
16524 (and (/= 0 dm) (format ":%02d" dm)))))))
16526 (defun org-time-stamp-inactive (&optional arg)
16527 "Insert an inactive time stamp.
16528 An inactive time stamp is enclosed in square brackets instead of angle
16529 brackets. It is inactive in the sense that it does not trigger agenda entries,
16530 does not link to the calendar and cannot be changed with the S-cursor keys.
16531 So these are more for recording a certain time/date."
16532 (interactive "P")
16533 (org-time-stamp arg 'inactive))
16535 (defvar org-date-ovl (make-overlay 1 1))
16536 (overlay-put org-date-ovl 'face 'org-date-selected)
16537 (org-detach-overlay org-date-ovl)
16539 (defvar org-ans1) ; dynamically scoped parameter
16540 (defvar org-ans2) ; dynamically scoped parameter
16542 (defvar org-plain-time-of-day-regexp) ; defined below
16544 (defvar org-overriding-default-time nil) ; dynamically scoped
16545 (defvar org-read-date-overlay nil)
16546 (defvar org-dcst nil) ; dynamically scoped
16547 (defvar org-read-date-history nil)
16548 (defvar org-read-date-final-answer nil)
16549 (defvar org-read-date-analyze-futurep nil)
16550 (defvar org-read-date-analyze-forced-year nil)
16551 (defvar org-read-date-inactive)
16553 (defvar org-read-date-minibuffer-local-map
16554 (let* ((map (make-sparse-keymap)))
16555 (set-keymap-parent map minibuffer-local-map)
16556 (org-defkey map (kbd ".")
16557 (lambda () (interactive)
16558 ;; Are we at the beginning of the prompt?
16559 (if (looking-back "^[^:]+: ")
16560 (org-eval-in-calendar '(calendar-goto-today))
16561 (insert "."))))
16562 (org-defkey map (kbd "C-.")
16563 (lambda () (interactive)
16564 (org-eval-in-calendar '(calendar-goto-today))))
16565 (org-defkey map [(meta shift left)]
16566 (lambda () (interactive)
16567 (org-eval-in-calendar '(calendar-backward-month 1))))
16568 (org-defkey map [(meta shift right)]
16569 (lambda () (interactive)
16570 (org-eval-in-calendar '(calendar-forward-month 1))))
16571 (org-defkey map [(meta shift up)]
16572 (lambda () (interactive)
16573 (org-eval-in-calendar '(calendar-backward-year 1))))
16574 (org-defkey map [(meta shift down)]
16575 (lambda () (interactive)
16576 (org-eval-in-calendar '(calendar-forward-year 1))))
16577 (org-defkey map [?\e (shift left)]
16578 (lambda () (interactive)
16579 (org-eval-in-calendar '(calendar-backward-month 1))))
16580 (org-defkey map [?\e (shift right)]
16581 (lambda () (interactive)
16582 (org-eval-in-calendar '(calendar-forward-month 1))))
16583 (org-defkey map [?\e (shift up)]
16584 (lambda () (interactive)
16585 (org-eval-in-calendar '(calendar-backward-year 1))))
16586 (org-defkey map [?\e (shift down)]
16587 (lambda () (interactive)
16588 (org-eval-in-calendar '(calendar-forward-year 1))))
16589 (org-defkey map [(shift up)]
16590 (lambda () (interactive)
16591 (org-eval-in-calendar '(calendar-backward-week 1))))
16592 (org-defkey map [(shift down)]
16593 (lambda () (interactive)
16594 (org-eval-in-calendar '(calendar-forward-week 1))))
16595 (org-defkey map [(shift left)]
16596 (lambda () (interactive)
16597 (org-eval-in-calendar '(calendar-backward-day 1))))
16598 (org-defkey map [(shift right)]
16599 (lambda () (interactive)
16600 (org-eval-in-calendar '(calendar-forward-day 1))))
16601 (org-defkey map "!"
16602 (lambda () (interactive)
16603 (org-eval-in-calendar '(diary-view-entries))
16604 (message "")))
16605 (org-defkey map ">"
16606 (lambda () (interactive)
16607 (org-eval-in-calendar '(calendar-scroll-left 1))))
16608 (org-defkey map "<"
16609 (lambda () (interactive)
16610 (org-eval-in-calendar '(calendar-scroll-right 1))))
16611 (org-defkey map "\C-v"
16612 (lambda () (interactive)
16613 (org-eval-in-calendar
16614 '(calendar-scroll-left-three-months 1))))
16615 (org-defkey map "\M-v"
16616 (lambda () (interactive)
16617 (org-eval-in-calendar
16618 '(calendar-scroll-right-three-months 1))))
16619 map)
16620 "Keymap for minibuffer commands when using `org-read-date'.")
16622 (defvar org-def)
16623 (defvar org-defdecode)
16624 (defvar org-with-time)
16626 (defun org-read-date (&optional org-with-time to-time from-string prompt
16627 default-time default-input inactive)
16628 "Read a date, possibly a time, and make things smooth for the user.
16629 The prompt will suggest to enter an ISO date, but you can also enter anything
16630 which will at least partially be understood by `parse-time-string'.
16631 Unrecognized parts of the date will default to the current day, month, year,
16632 hour and minute. If this command is called to replace a timestamp at point,
16633 or to enter the second timestamp of a range, the default time is taken
16634 from the existing stamp. Furthermore, the command prefers the future,
16635 so if you are giving a date where the year is not given, and the day-month
16636 combination is already past in the current year, it will assume you
16637 mean next year. For details, see the manual. A few examples:
16639 3-2-5 --> 2003-02-05
16640 feb 15 --> currentyear-02-15
16641 2/15 --> currentyear-02-15
16642 sep 12 9 --> 2009-09-12
16643 12:45 --> today 12:45
16644 22 sept 0:34 --> currentyear-09-22 0:34
16645 12 --> currentyear-currentmonth-12
16646 Fri --> nearest Friday after today
16647 -Tue --> last Tuesday
16648 etc.
16650 Furthermore you can specify a relative date by giving, as the *first* thing
16651 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16652 change in days weeks, months, years.
16653 With a single plus or minus, the date is relative to today. With a double
16654 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16655 +4d --> four days from today
16656 +4 --> same as above
16657 +2w --> two weeks from today
16658 ++5 --> five days from default date
16660 The function understands only English month and weekday abbreviations.
16662 While prompting, a calendar is popped up - you can also select the
16663 date with the mouse (button 1). The calendar shows a period of three
16664 months. To scroll it to other months, use the keys `>' and `<'.
16665 If you don't like the calendar, turn it off with
16666 \(setq org-read-date-popup-calendar nil)
16668 With optional argument TO-TIME, the date will immediately be converted
16669 to an internal time.
16670 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16671 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16672 still enter a time, and this function will inform the calling routine
16673 about this change. The calling routine may then choose to change the
16674 format used to insert the time stamp into the buffer to include the time.
16675 With optional argument FROM-STRING, read from this string instead from
16676 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16677 the time/date that is used for everything that is not specified by the
16678 user."
16679 (require 'parse-time)
16680 (let* ((org-time-stamp-rounding-minutes
16681 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16682 (org-dcst org-display-custom-times)
16683 (ct (org-current-time))
16684 (org-def (or org-overriding-default-time default-time ct))
16685 (org-defdecode (decode-time org-def))
16686 (dummy (progn
16687 (when (< (nth 2 org-defdecode) org-extend-today-until)
16688 (setcar (nthcdr 2 org-defdecode) -1)
16689 (setcar (nthcdr 1 org-defdecode) 59)
16690 (setq org-def (apply 'encode-time org-defdecode)
16691 org-defdecode (decode-time org-def)))))
16692 (cur-frame (selected-frame))
16693 (mouse-autoselect-window nil) ; Don't let the mouse jump
16694 (calendar-frame-setup nil)
16695 (calendar-setup (when (eq calendar-setup 'calendar-only) 'calendar-only))
16696 (calendar-move-hook nil)
16697 (calendar-view-diary-initially-flag nil)
16698 (calendar-view-holidays-initially-flag nil)
16699 (timestr (format-time-string
16700 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16701 (prompt (concat (if prompt (concat prompt " ") "")
16702 (format "Date+time [%s]: " timestr)))
16703 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16705 (cond
16706 (from-string (setq ans from-string))
16707 (org-read-date-popup-calendar
16708 (save-excursion
16709 (save-window-excursion
16710 (calendar)
16711 (when (eq calendar-setup 'calendar-only)
16712 (setq cal-frame
16713 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16714 (select-frame cal-frame))
16715 (org-eval-in-calendar '(setq cursor-type nil) t)
16716 (unwind-protect
16717 (progn
16718 (calendar-forward-day (- (time-to-days org-def)
16719 (calendar-absolute-from-gregorian
16720 (calendar-current-date))))
16721 (org-eval-in-calendar nil t)
16722 (let* ((old-map (current-local-map))
16723 (map (copy-keymap calendar-mode-map))
16724 (minibuffer-local-map
16725 (copy-keymap org-read-date-minibuffer-local-map)))
16726 (org-defkey map (kbd "RET") 'org-calendar-select)
16727 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16728 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16729 (unwind-protect
16730 (progn
16731 (use-local-map map)
16732 (setq org-read-date-inactive inactive)
16733 (add-hook 'post-command-hook 'org-read-date-display)
16734 (setq org-ans0 (read-string prompt default-input
16735 'org-read-date-history nil))
16736 ;; org-ans0: from prompt
16737 ;; org-ans1: from mouse click
16738 ;; org-ans2: from calendar motion
16739 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16740 (remove-hook 'post-command-hook 'org-read-date-display)
16741 (use-local-map old-map)
16742 (when org-read-date-overlay
16743 (delete-overlay org-read-date-overlay)
16744 (setq org-read-date-overlay nil)))))
16745 (bury-buffer "*Calendar*")
16746 (when cal-frame
16747 (delete-frame cal-frame)
16748 (select-frame-set-input-focus cur-frame))))))
16750 (t ; Naked prompt only
16751 (unwind-protect
16752 (setq ans (read-string prompt default-input
16753 'org-read-date-history timestr))
16754 (when org-read-date-overlay
16755 (delete-overlay org-read-date-overlay)
16756 (setq org-read-date-overlay nil)))))
16758 (setq final (org-read-date-analyze ans org-def org-defdecode))
16760 (when org-read-date-analyze-forced-year
16761 (message "Year was forced into %s"
16762 (if org-read-date-force-compatible-dates
16763 "compatible range (1970-2037)"
16764 "range representable on this machine"))
16765 (ding))
16767 ;; One round trip to get rid of 34th of August and stuff like that....
16768 (setq final (decode-time (apply 'encode-time final)))
16770 (setq org-read-date-final-answer ans)
16772 (if to-time
16773 (apply 'encode-time final)
16774 (if (and (boundp 'org-time-was-given) org-time-was-given)
16775 (format "%04d-%02d-%02d %02d:%02d"
16776 (nth 5 final) (nth 4 final) (nth 3 final)
16777 (nth 2 final) (nth 1 final))
16778 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16780 (defun org-read-date-display ()
16781 "Display the current date prompt interpretation in the minibuffer."
16782 (when org-read-date-display-live
16783 (when org-read-date-overlay
16784 (delete-overlay org-read-date-overlay))
16785 (when (minibufferp (current-buffer))
16786 (save-excursion
16787 (end-of-line 1)
16788 (while (not (equal (buffer-substring
16789 (max (point-min) (- (point) 4)) (point))
16790 " "))
16791 (insert " ")))
16792 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16793 " " (or org-ans1 org-ans2)))
16794 (org-end-time-was-given nil)
16795 (f (org-read-date-analyze ans org-def org-defdecode))
16796 (fmts (if org-dcst
16797 org-time-stamp-custom-formats
16798 org-time-stamp-formats))
16799 (fmt (if (or org-with-time
16800 (and (boundp 'org-time-was-given) org-time-was-given))
16801 (cdr fmts)
16802 (car fmts)))
16803 (txt (format-time-string fmt (apply 'encode-time f)))
16804 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16805 (txt (concat "=> " txt)))
16806 (when (and org-end-time-was-given
16807 (string-match org-plain-time-of-day-regexp txt))
16808 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16809 org-end-time-was-given
16810 (substring txt (match-end 0)))))
16811 (when org-read-date-analyze-futurep
16812 (setq txt (concat txt " (=>F)")))
16813 (setq org-read-date-overlay
16814 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16815 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16817 (defun org-read-date-analyze (ans org-def org-defdecode)
16818 "Analyze the combined answer of the date prompt."
16819 ;; FIXME: cleanup and comment
16820 (let ((nowdecode (decode-time (current-time)))
16821 delta deltan deltaw deltadef year month day
16822 hour minute second wday pm h2 m2 tl wday1
16823 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16824 (setq org-read-date-analyze-futurep nil
16825 org-read-date-analyze-forced-year nil)
16826 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16827 (setq ans "+0"))
16829 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16830 (setq ans (replace-match "" t t ans)
16831 deltan (car delta)
16832 deltaw (nth 1 delta)
16833 deltadef (nth 2 delta)))
16835 ;; Check if there is an iso week date in there. If yes, store the
16836 ;; info and postpone interpreting it until the rest of the parsing
16837 ;; is done.
16838 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16839 (setq iso-year (if (match-end 1)
16840 (org-small-year-to-year
16841 (string-to-number (match-string 1 ans))))
16842 iso-weekday (if (match-end 3)
16843 (string-to-number (match-string 3 ans)))
16844 iso-week (string-to-number (match-string 2 ans)))
16845 (setq ans (replace-match "" t t ans)))
16847 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16848 (when (string-match
16849 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16850 (setq year (if (match-end 2)
16851 (string-to-number (match-string 2 ans))
16852 (progn (setq kill-year t)
16853 (string-to-number (format-time-string "%Y"))))
16854 month (string-to-number (match-string 3 ans))
16855 day (string-to-number (match-string 4 ans)))
16856 (if (< year 100) (setq year (+ 2000 year)))
16857 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16858 t nil ans)))
16860 ;; Help matching dotted european dates
16861 (when (string-match
16862 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16863 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16864 (setq kill-year t)
16865 (string-to-number (format-time-string "%Y")))
16866 day (string-to-number (match-string 1 ans))
16867 month (string-to-number (match-string 2 ans))
16868 ans (replace-match (format "%04d-%02d-%02d" year month day)
16869 t nil ans)))
16871 ;; Help matching american dates, like 5/30 or 5/30/7
16872 (when (string-match
16873 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16874 (setq year (if (match-end 4)
16875 (string-to-number (match-string 4 ans))
16876 (progn (setq kill-year t)
16877 (string-to-number (format-time-string "%Y"))))
16878 month (string-to-number (match-string 1 ans))
16879 day (string-to-number (match-string 2 ans)))
16880 (if (< year 100) (setq year (+ 2000 year)))
16881 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16882 t nil ans)))
16883 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16884 ;; If there is a time with am/pm, and *no* time without it, we convert
16885 ;; so that matching will be successful.
16886 (loop for i from 1 to 2 do ; twice, for end time as well
16887 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16888 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16889 (setq hour (string-to-number (match-string 1 ans))
16890 minute (if (match-end 3)
16891 (string-to-number (match-string 3 ans))
16893 pm (equal ?p
16894 (string-to-char (downcase (match-string 4 ans)))))
16895 (if (and (= hour 12) (not pm))
16896 (setq hour 0)
16897 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16898 (setq ans (replace-match (format "%02d:%02d" hour minute)
16899 t t ans))))
16901 ;; Check if a time range is given as a duration
16902 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16903 (setq hour (string-to-number (match-string 1 ans))
16904 h2 (+ hour (string-to-number (match-string 3 ans)))
16905 minute (string-to-number (match-string 2 ans))
16906 m2 (+ minute (if (match-end 5) (string-to-number
16907 (match-string 5 ans))0)))
16908 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16909 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16910 t t ans)))
16912 ;; Check if there is a time range
16913 (when (boundp 'org-end-time-was-given)
16914 (setq org-time-was-given nil)
16915 (when (and (string-match org-plain-time-of-day-regexp ans)
16916 (match-end 8))
16917 (setq org-end-time-was-given (match-string 8 ans))
16918 (setq ans (concat (substring ans 0 (match-beginning 7))
16919 (substring ans (match-end 7))))))
16921 (setq tl (parse-time-string ans)
16922 day (or (nth 3 tl) (nth 3 org-defdecode))
16923 month
16924 (cond ((nth 4 tl))
16925 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16926 ;; Day was specified. Make sure DAY+MONTH
16927 ;; combination happens in the future.
16928 ((nth 3 tl)
16929 (setq futurep t)
16930 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16931 (nth 4 nowdecode)))
16932 (t (nth 4 org-defdecode)))
16933 year
16934 (cond ((and (not kill-year) (nth 5 tl)))
16935 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16936 ;; Month was guessed in the future and is at least
16937 ;; equal to NOWDECODE's. Fix year accordingly.
16938 (futurep
16939 (if (or (> month (nth 4 nowdecode))
16940 (>= day (nth 3 nowdecode)))
16941 (nth 5 nowdecode)
16942 (1+ (nth 5 nowdecode))))
16943 ;; Month was specified. Make sure MONTH+YEAR
16944 ;; combination happens in the future.
16945 ((nth 4 tl)
16946 (setq futurep t)
16947 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16948 ((< month (nth 5 nowdecode)) (1+ (nth 5 nowdecode)))
16949 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16950 (t (nth 5 nowdecode))))
16951 (t (nth 5 org-defdecode)))
16952 hour (or (nth 2 tl) (nth 2 org-defdecode))
16953 minute (or (nth 1 tl) (nth 1 org-defdecode))
16954 second (or (nth 0 tl) 0)
16955 wday (nth 6 tl))
16957 (when (and (eq org-read-date-prefer-future 'time)
16958 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16959 (equal day (nth 3 nowdecode))
16960 (equal month (nth 4 nowdecode))
16961 (equal year (nth 5 nowdecode))
16962 (nth 2 tl)
16963 (or (< (nth 2 tl) (nth 2 nowdecode))
16964 (and (= (nth 2 tl) (nth 2 nowdecode))
16965 (nth 1 tl)
16966 (< (nth 1 tl) (nth 1 nowdecode)))))
16967 (setq day (1+ day)
16968 futurep t))
16970 ;; Special date definitions below
16971 (cond
16972 (iso-week
16973 ;; There was an iso week
16974 (require 'cal-iso)
16975 (setq futurep nil)
16976 (setq year (or iso-year year)
16977 day (or iso-weekday wday 1)
16978 wday nil ; to make sure that the trigger below does not match
16979 iso-date (calendar-gregorian-from-absolute
16980 (calendar-iso-to-absolute
16981 (list iso-week day year))))
16982 ; FIXME: Should we also push ISO weeks into the future?
16983 ; (when (and org-read-date-prefer-future
16984 ; (not iso-year)
16985 ; (< (calendar-absolute-from-gregorian iso-date)
16986 ; (time-to-days (current-time))))
16987 ; (setq year (1+ year)
16988 ; iso-date (calendar-gregorian-from-absolute
16989 ; (calendar-iso-to-absolute
16990 ; (list iso-week day year)))))
16991 (setq month (car iso-date)
16992 year (nth 2 iso-date)
16993 day (nth 1 iso-date)))
16994 (deltan
16995 (setq futurep nil)
16996 (unless deltadef
16997 (let ((now (decode-time (current-time))))
16998 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16999 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17000 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17001 ((equal deltaw "m") (setq month (+ month deltan)))
17002 ((equal deltaw "y") (setq year (+ year deltan)))))
17003 ((and wday (not (nth 3 tl)))
17004 ;; Weekday was given, but no day, so pick that day in the week
17005 ;; on or after the derived date.
17006 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17007 (unless (equal wday wday1)
17008 (setq day (+ day (% (- wday wday1 -7) 7))))))
17009 (if (and (boundp 'org-time-was-given)
17010 (nth 2 tl))
17011 (setq org-time-was-given t))
17012 (if (< year 100) (setq year (+ 2000 year)))
17013 ;; Check of the date is representable
17014 (if org-read-date-force-compatible-dates
17015 (progn
17016 (if (< year 1970)
17017 (setq year 1970 org-read-date-analyze-forced-year t))
17018 (if (> year 2037)
17019 (setq year 2037 org-read-date-analyze-forced-year t)))
17020 (condition-case nil
17021 (ignore (encode-time second minute hour day month year))
17022 (error
17023 (setq year (nth 5 org-defdecode))
17024 (setq org-read-date-analyze-forced-year t))))
17025 (setq org-read-date-analyze-futurep futurep)
17026 (list second minute hour day month year)))
17028 (defvar parse-time-weekdays)
17029 (defun org-read-date-get-relative (s today default)
17030 "Check string S for special relative date string.
17031 TODAY and DEFAULT are internal times, for today and for a default.
17032 Return shift list (N what def-flag)
17033 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17034 N is the number of WHATs to shift.
17035 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17036 the DEFAULT date rather than TODAY."
17037 (require 'parse-time)
17038 (when (and
17039 (string-match
17040 (concat
17041 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17042 "\\([0-9]+\\)?"
17043 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17044 "\\([ \t]\\|$\\)") s)
17045 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17046 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17047 (string-to-char (substring (match-string 1 s) -1))
17048 ?+))
17049 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17050 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17051 (what (if (match-end 3) (match-string 3 s) "d"))
17052 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17053 (date (if rel default today))
17054 (wday (nth 6 (decode-time date)))
17055 delta)
17056 (if wday1
17057 (progn
17058 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17059 (if (= delta 0) (setq delta 7))
17060 (if (= dir ?-)
17061 (progn
17062 (setq delta (- delta 7))
17063 (if (= delta 0) (setq delta -7))))
17064 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17065 (list delta "d" rel))
17066 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17068 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17069 "Turn a user-specified date into the internal representation.
17070 The internal representation needed by the calendar is (month day year).
17071 This is a wrapper to handle the brain-dead convention in calendar that
17072 user function argument order change dependent on argument order."
17073 (if (boundp 'calendar-date-style)
17074 (cond
17075 ((eq calendar-date-style 'american)
17076 (list arg1 arg2 arg3))
17077 ((eq calendar-date-style 'european)
17078 (list arg2 arg1 arg3))
17079 ((eq calendar-date-style 'iso)
17080 (list arg2 arg3 arg1)))
17081 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
17082 (if (org-bound-and-true-p european-calendar-style)
17083 (list arg2 arg1 arg3)
17084 (list arg1 arg2 arg3)))))
17086 (defun org-eval-in-calendar (form &optional keepdate)
17087 "Eval FORM in the calendar window and return to current window.
17088 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
17089 otherwise stick to the current value of `org-ans2'."
17090 (let ((sf (selected-frame))
17091 (sw (selected-window)))
17092 (select-window (get-buffer-window "*Calendar*" t))
17093 (eval form)
17094 (when (and (not keepdate) (calendar-cursor-to-date))
17095 (let* ((date (calendar-cursor-to-date))
17096 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17097 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17098 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17099 (select-window sw)
17100 (org-select-frame-set-input-focus sf)))
17102 (defun org-calendar-select ()
17103 "Return to `org-read-date' with the date currently selected.
17104 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17105 (interactive)
17106 (when (calendar-cursor-to-date)
17107 (let* ((date (calendar-cursor-to-date))
17108 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17109 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17110 (if (active-minibuffer-window) (exit-minibuffer))))
17112 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17113 "Insert a date stamp for the date given by the internal TIME.
17114 See `format-time-string' for the format of TIME.
17115 WITH-HM means use the stamp format that includes the time of the day.
17116 INACTIVE means use square brackets instead of angular ones, so that the
17117 stamp will not contribute to the agenda.
17118 PRE and POST are optional strings to be inserted before and after the
17119 stamp.
17120 The command returns the inserted time stamp."
17121 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17122 stamp)
17123 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17124 (insert-before-markers (or pre ""))
17125 (when (listp extra)
17126 (setq extra (car extra))
17127 (if (and (stringp extra)
17128 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17129 (setq extra (format "-%02d:%02d"
17130 (string-to-number (match-string 1 extra))
17131 (string-to-number (match-string 2 extra))))
17132 (setq extra nil)))
17133 (when extra
17134 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17135 (insert-before-markers (setq stamp (format-time-string fmt time)))
17136 (insert-before-markers (or post ""))
17137 (setq org-last-inserted-timestamp stamp)))
17139 (defun org-toggle-time-stamp-overlays ()
17140 "Toggle the use of custom time stamp formats."
17141 (interactive)
17142 (setq org-display-custom-times (not org-display-custom-times))
17143 (unless org-display-custom-times
17144 (let ((p (point-min)) (bmp (buffer-modified-p)))
17145 (while (setq p (next-single-property-change p 'display))
17146 (if (and (get-text-property p 'display)
17147 (eq (get-text-property p 'face) 'org-date))
17148 (remove-text-properties
17149 p (setq p (next-single-property-change p 'display))
17150 '(display t))))
17151 (set-buffer-modified-p bmp)))
17152 (if (featurep 'xemacs)
17153 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17154 (org-restart-font-lock)
17155 (setq org-table-may-need-update t)
17156 (if org-display-custom-times
17157 (message "Time stamps are overlaid with custom format")
17158 (message "Time stamp overlays removed")))
17160 (defun org-display-custom-time (beg end)
17161 "Overlay modified time stamp format over timestamp between BEG and END."
17162 (let* ((ts (buffer-substring beg end))
17163 t1 w1 with-hm tf time str w2 (off 0))
17164 (save-match-data
17165 (setq t1 (org-parse-time-string ts t))
17166 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17167 (setq off (- (match-end 0) (match-beginning 0)))))
17168 (setq end (- end off))
17169 (setq w1 (- end beg)
17170 with-hm (and (nth 1 t1) (nth 2 t1))
17171 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17172 time (org-fix-decoded-time t1)
17173 str (org-add-props
17174 (format-time-string
17175 (substring tf 1 -1) (apply 'encode-time time))
17176 nil 'mouse-face 'highlight)
17177 w2 (length str))
17178 (if (not (= w2 w1))
17179 (add-text-properties (1+ beg) (+ 2 beg)
17180 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17181 (if (featurep 'xemacs)
17182 (progn
17183 (put-text-property beg end 'invisible t)
17184 (put-text-property beg end 'end-glyph (make-glyph str)))
17185 (put-text-property beg end 'display str))))
17187 (defun org-fix-decoded-time (time)
17188 "Set 0 instead of nil for the first 6 elements of time.
17189 Don't touch the rest."
17190 (let ((n 0))
17191 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17193 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17195 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17196 "Difference between TIMESTAMP-STRING and now in days.
17197 If SECONDS is non-nil, return the difference in seconds."
17198 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17199 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17200 (funcall fdiff (current-time)))))
17202 (defun org-deadline-close (timestamp-string &optional ndays)
17203 "Is the time in TIMESTAMP-STRING close to the current date?"
17204 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17205 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17206 (not (org-entry-is-done-p))))
17208 (defun org-get-wdays (ts &optional delay zero-delay)
17209 "Get the deadline lead time appropriate for timestring TS.
17210 When DELAY is non-nil, get the delay time for scheduled items
17211 instead of the deadline lead time. When ZERO-DELAY is non-nil
17212 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17213 don't try to find the delay cookie in the scheduled timestamp."
17214 (let ((tv (if delay org-scheduled-delay-days
17215 org-deadline-warning-days)))
17216 (cond
17217 ((or (and delay (< tv 0))
17218 (and delay zero-delay (<= tv 0))
17219 (and (not delay) (<= tv 0)))
17220 ;; Enforce this value no matter what
17221 (- tv))
17222 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17223 ;; lead time is specified.
17224 (floor (* (string-to-number (match-string 1 ts))
17225 (cdr (assoc (match-string 2 ts)
17226 '(("d" . 1) ("w" . 7)
17227 ("m" . 30.4) ("y" . 365.25)
17228 ("h" . 0.041667)))))))
17229 ;; go for the default.
17230 (t tv))))
17232 (defun org-calendar-select-mouse (ev)
17233 "Return to `org-read-date' with the date currently selected.
17234 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17235 (interactive "e")
17236 (mouse-set-point ev)
17237 (when (calendar-cursor-to-date)
17238 (let* ((date (calendar-cursor-to-date))
17239 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17240 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17241 (if (active-minibuffer-window) (exit-minibuffer))))
17243 (defun org-check-deadlines (ndays)
17244 "Check if there are any deadlines due or past due.
17245 A deadline is considered due if it happens within `org-deadline-warning-days'
17246 days from today's date. If the deadline appears in an entry marked DONE,
17247 it is not shown. The prefix arg NDAYS can be used to test that many
17248 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17249 (interactive "P")
17250 (let* ((org-warn-days
17251 (cond
17252 ((equal ndays '(4)) 100000)
17253 (ndays (prefix-numeric-value ndays))
17254 (t (abs org-deadline-warning-days))))
17255 (case-fold-search nil)
17256 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17257 (callback
17258 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17260 (message "%d deadlines past-due or due within %d days"
17261 (org-occur regexp nil callback)
17262 org-warn-days)))
17264 (defsubst org-re-timestamp (type)
17265 "Return a regexp for timestamp TYPE.
17266 Allowed values for TYPE are:
17268 all: all timestamps
17269 active: only active timestamps (<...>)
17270 inactive: only inactive timestamps ([...])
17271 scheduled: only scheduled timestamps
17272 deadline: only deadline timestamps
17273 closed: only closed time-stamps
17275 When TYPE is nil, fall back on returning a regexp that matches
17276 both scheduled and deadline timestamps."
17277 (case type
17278 (all org-ts-regexp-both)
17279 (active org-ts-regexp)
17280 (inactive org-ts-regexp-inactive)
17281 (scheduled org-scheduled-time-regexp)
17282 (deadline org-deadline-time-regexp)
17283 (closed org-closed-time-regexp)
17284 (otherwise
17285 (concat "\\<"
17286 (regexp-opt (list org-deadline-string org-scheduled-string))
17287 " *<\\([^>]+\\)>"))))
17289 (defun org-check-before-date (date)
17290 "Check if there are deadlines or scheduled entries before DATE."
17291 (interactive (list (org-read-date)))
17292 (let ((case-fold-search nil)
17293 (regexp (org-re-timestamp org-ts-type))
17294 (callback
17295 `(lambda ()
17296 (and ,(if (memq org-ts-type '(active inactive all))
17297 '(eq (org-element-type (org-element-context) 'timestamp))
17298 '(org-at-planning-p))
17299 (time-less-p
17300 (org-time-string-to-time (match-string 1))
17301 (org-time-string-to-time date))))))
17302 (message "%d entries before %s"
17303 (org-occur regexp nil callback) date)))
17305 (defun org-check-after-date (date)
17306 "Check if there are deadlines or scheduled entries after DATE."
17307 (interactive (list (org-read-date)))
17308 (let ((case-fold-search nil)
17309 (regexp (org-re-timestamp org-ts-type))
17310 (callback
17311 `(lambda ()
17312 (and ,(if (memq org-ts-type '(active inactive all))
17313 '(eq (org-element-type (org-element-context) 'timestamp))
17314 '(org-at-planning-p))
17315 (not (time-less-p
17316 (org-time-string-to-time (match-string 1))
17317 (org-time-string-to-time date)))))))
17318 (message "%d entries after %s"
17319 (org-occur regexp nil callback) date)))
17321 (defun org-check-dates-range (start-date end-date)
17322 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17323 (interactive (list (org-read-date nil nil nil "Range starts")
17324 (org-read-date nil nil nil "Range end")))
17325 (let ((case-fold-search nil)
17326 (regexp (org-re-timestamp org-ts-type))
17327 (callback
17328 `(lambda ()
17329 (let ((match (match-string 1)))
17330 (and
17331 ,(if (memq org-ts-type '(active inactive all))
17332 '(eq (org-element-type (org-element-context) 'timestamp))
17333 '(org-at-planning-p))
17334 (not (time-less-p
17335 (org-time-string-to-time match)
17336 (org-time-string-to-time start-date)))
17337 (time-less-p
17338 (org-time-string-to-time match)
17339 (org-time-string-to-time end-date)))))))
17340 (message "%d entries between %s and %s"
17341 (org-occur regexp nil callback) start-date end-date)))
17343 (defun org-evaluate-time-range (&optional to-buffer)
17344 "Evaluate a time range by computing the difference between start and end.
17345 Normally the result is just printed in the echo area, but with prefix arg
17346 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17347 If the time range is actually in a table, the result is inserted into the
17348 next column.
17349 For time difference computation, a year is assumed to be exactly 365
17350 days in order to avoid rounding problems."
17351 (interactive "P")
17353 (org-clock-update-time-maybe)
17354 (save-excursion
17355 (unless (org-at-date-range-p t)
17356 (goto-char (point-at-bol))
17357 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17358 (if (not (org-at-date-range-p t))
17359 (user-error "Not at a time-stamp range, and none found in current line")))
17360 (let* ((ts1 (match-string 1))
17361 (ts2 (match-string 2))
17362 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17363 (match-end (match-end 0))
17364 (time1 (org-time-string-to-time ts1))
17365 (time2 (org-time-string-to-time ts2))
17366 (t1 (org-float-time time1))
17367 (t2 (org-float-time time2))
17368 (diff (abs (- t2 t1)))
17369 (negative (< (- t2 t1) 0))
17370 ;; (ys (floor (* 365 24 60 60)))
17371 (ds (* 24 60 60))
17372 (hs (* 60 60))
17373 (fy "%dy %dd %02d:%02d")
17374 (fy1 "%dy %dd")
17375 (fd "%dd %02d:%02d")
17376 (fd1 "%dd")
17377 (fh "%02d:%02d")
17378 y d h m align)
17379 (if havetime
17380 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17382 d (floor (/ diff ds)) diff (mod diff ds)
17383 h (floor (/ diff hs)) diff (mod diff hs)
17384 m (floor (/ diff 60)))
17385 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17387 d (floor (+ (/ diff ds) 0.5))
17388 h 0 m 0))
17389 (if (not to-buffer)
17390 (message "%s" (org-make-tdiff-string y d h m))
17391 (if (org-at-table-p)
17392 (progn
17393 (goto-char match-end)
17394 (setq align t)
17395 (and (looking-at " *|") (goto-char (match-end 0))))
17396 (goto-char match-end))
17397 (if (looking-at
17398 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17399 (replace-match ""))
17400 (if negative (insert " -"))
17401 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17402 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17403 (insert " " (format fh h m))))
17404 (if align (org-table-align))
17405 (message "Time difference inserted")))))
17407 (defun org-make-tdiff-string (y d h m)
17408 (let ((fmt "")
17409 (l nil))
17410 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17411 l (push y l)))
17412 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17413 l (push d l)))
17414 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17415 l (push h l)))
17416 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17417 l (push m l)))
17418 (apply 'format fmt (nreverse l))))
17420 (defun org-time-string-to-time (s &optional buffer pos)
17421 "Convert a timestamp string into internal time."
17422 (condition-case errdata
17423 (apply 'encode-time (org-parse-time-string s))
17424 (error (error "Bad timestamp `%s'%s\nError was: %s"
17425 s (if (not (and buffer pos))
17427 (format " at %d in buffer `%s'" pos buffer))
17428 (cdr errdata)))))
17430 (defun org-time-string-to-seconds (s)
17431 "Convert a timestamp string to a number of seconds."
17432 (org-float-time (org-time-string-to-time s)))
17434 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17435 "Convert a time stamp to an absolute day number.
17436 If there is a specifier for a cyclic time stamp, get the closest
17437 date to DAYNR.
17438 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17439 The variable `date' is bound by the calendar when this is called."
17440 (cond
17441 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17442 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17443 daynr
17444 (+ daynr 1000)))
17445 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17446 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17447 (time-to-days (current-time))) (match-string 0 s)
17448 prefer show-all))
17449 (t (time-to-days
17450 (condition-case errdata
17451 (apply 'encode-time (org-parse-time-string s))
17452 (error (error "Bad timestamp `%s'%s\nError was: %s"
17453 s (if (not (and buffer pos))
17455 (format " at %d in buffer `%s'" pos buffer))
17456 (cdr errdata))))))))
17458 (defun org-days-to-iso-week (days)
17459 "Return the iso week number."
17460 (require 'cal-iso)
17461 (car (calendar-iso-from-absolute days)))
17463 (defun org-small-year-to-year (year)
17464 "Convert 2-digit years into 4-digit years.
17465 YEAR is expanded into one of the 30 next years, if possible, or
17466 into a past one. Any year larger than 99 is returned unchanged."
17467 (if (>= year 100) year
17468 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17469 (century (/ current 100))
17470 (offset (- year (% current 100))))
17471 (cond ((> offset 30) (+ (* (1- century) 100) year))
17472 ((> offset -70) (+ (* century 100) year))
17473 (t (+ (* (1+ century) 100) year))))))
17475 (defun org-time-from-absolute (d)
17476 "Return the time corresponding to date D.
17477 D may be an absolute day number, or a calendar-type list (month day year)."
17478 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17479 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17481 (defun org-calendar-holiday ()
17482 "List of holidays, for Diary display in Org-mode."
17483 (require 'holidays)
17484 (let ((hl (funcall
17485 (if (fboundp 'calendar-check-holidays)
17486 'calendar-check-holidays 'check-calendar-holidays) date)))
17487 (if hl (mapconcat 'identity hl "; "))))
17489 (defun org-diary-sexp-entry (sexp entry date)
17490 "Process a SEXP diary ENTRY for DATE."
17491 (require 'diary-lib)
17492 (let ((result (if calendar-debug-sexp
17493 (let ((stack-trace-on-error t))
17494 (eval (car (read-from-string sexp))))
17495 (condition-case nil
17496 (eval (car (read-from-string sexp)))
17497 (error
17498 (beep)
17499 (message "Bad sexp at line %d in %s: %s"
17500 (org-current-line)
17501 (buffer-file-name) sexp)
17502 (sleep-for 2))))))
17503 (cond ((stringp result) (split-string result "; "))
17504 ((and (consp result)
17505 (not (consp (cdr result)))
17506 (stringp (cdr result))) (cdr result))
17507 ((and (consp result)
17508 (stringp (car result))) result)
17509 (result entry))))
17511 (defun org-diary-to-ical-string (frombuf)
17512 "Get iCalendar entries from diary entries in buffer FROMBUF.
17513 This uses the icalendar.el library."
17514 (let* ((tmpdir (if (featurep 'xemacs)
17515 (temp-directory)
17516 temporary-file-directory))
17517 (tmpfile (make-temp-name
17518 (expand-file-name "orgics" tmpdir)))
17519 buf rtn b e)
17520 (with-current-buffer frombuf
17521 (icalendar-export-region (point-min) (point-max) tmpfile)
17522 (setq buf (find-buffer-visiting tmpfile))
17523 (set-buffer buf)
17524 (goto-char (point-min))
17525 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17526 (setq b (match-beginning 0)))
17527 (goto-char (point-max))
17528 (if (re-search-backward "^END:VEVENT" nil t)
17529 (setq e (match-end 0)))
17530 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17531 (kill-buffer buf)
17532 (delete-file tmpfile)
17533 rtn))
17535 (defun org-closest-date (start current change prefer show-all)
17536 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17537 When PREFER is `past', return a date that is either CURRENT or past.
17538 When PREFER is `future', return a date that is either CURRENT or future.
17539 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17540 ;; Make the proper lists from the dates
17541 (catch 'exit
17542 (let ((a1 '(("h" . hour)
17543 ("d" . day)
17544 ("w" . week)
17545 ("m" . month)
17546 ("y" . year)))
17547 (shour (nth 2 (org-parse-time-string start)))
17548 dn dw sday cday n1 n2 n0
17549 d m y y1 y2 date1 date2 nmonths nm ny m2)
17551 (setq start (org-date-to-gregorian start)
17552 current (org-date-to-gregorian
17553 (if show-all
17554 current
17555 (time-to-days (current-time))))
17556 sday (calendar-absolute-from-gregorian start)
17557 cday (calendar-absolute-from-gregorian current))
17559 (if (<= cday sday) (throw 'exit sday))
17561 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17562 (setq dn (string-to-number (match-string 1 change))
17563 dw (cdr (assoc (match-string 2 change) a1)))
17564 (user-error "Invalid change specifier: %s" change))
17565 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17566 (cond
17567 ((eq dw 'hour)
17568 (let ((missing-hours
17569 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17570 dn)))
17571 (setq n1 (if (zerop missing-hours) cday
17572 (- cday (1+ (floor (/ missing-hours 24)))))
17573 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17574 ((eq dw 'day)
17575 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17576 n2 (+ n1 dn)))
17577 ((eq dw 'year)
17578 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17579 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17580 (setq date1 (list m d y1)
17581 n1 (calendar-absolute-from-gregorian date1)
17582 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17583 n2 (calendar-absolute-from-gregorian date2)))
17584 ((eq dw 'month)
17585 ;; approx number of month between the two dates
17586 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17587 ;; How often does dn fit in there?
17588 (setq d (nth 1 start) m (car start) y (nth 2 start)
17589 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17590 m (+ m nm)
17591 ny (floor (/ m 12))
17592 y (+ y ny)
17593 m (- m (* ny 12)))
17594 (while (> m 12) (setq m (- m 12) y (1+ y)))
17595 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17596 (setq m2 (+ m dn) y2 y)
17597 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17598 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17599 (while (<= n2 cday)
17600 (setq n1 n2 m m2 y y2)
17601 (setq m2 (+ m dn) y2 y)
17602 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17603 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17604 ;; Make sure n1 is the earlier date
17605 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17606 (if show-all
17607 (cond
17608 ((eq prefer 'past) (if (= cday n2) n2 n1))
17609 ((eq prefer 'future) (if (= cday n1) n1 n2))
17610 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17611 (cond
17612 ((eq prefer 'past) (if (= cday n2) n2 n1))
17613 ((eq prefer 'future) (if (= cday n1) n1 n2))
17614 (t (if (= cday n1) n1 n2)))))))
17616 (defun org-date-to-gregorian (date)
17617 "Turn any specification of DATE into a Gregorian date for the calendar."
17618 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17619 ((and (listp date) (= (length date) 3)) date)
17620 ((stringp date)
17621 (setq date (org-parse-time-string date))
17622 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17623 ((listp date)
17624 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17626 (defun org-parse-time-string (s &optional nodefault)
17627 "Parse the standard Org-mode time string.
17628 This should be a lot faster than the normal `parse-time-string'.
17629 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17630 hour and minute fields will be nil if not given."
17631 (cond ((string-match org-ts-regexp0 s)
17632 (list 0
17633 (if (or (match-beginning 8) (not nodefault))
17634 (string-to-number (or (match-string 8 s) "0")))
17635 (if (or (match-beginning 7) (not nodefault))
17636 (string-to-number (or (match-string 7 s) "0")))
17637 (string-to-number (match-string 4 s))
17638 (string-to-number (match-string 3 s))
17639 (string-to-number (match-string 2 s))
17640 nil nil nil))
17641 ((string-match "^<[^>]+>$" s)
17642 (decode-time (seconds-to-time (org-matcher-time s))))
17643 (t (error "Not a standard Org-mode time string: %s" s))))
17645 (defun org-timestamp-up (&optional arg)
17646 "Increase the date item at the cursor by one.
17647 If the cursor is on the year, change the year. If it is on the month,
17648 the day or the time, change that.
17649 With prefix ARG, change by that many units."
17650 (interactive "p")
17651 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17653 (defun org-timestamp-down (&optional arg)
17654 "Decrease the date item at the cursor by one.
17655 If the cursor is on the year, change the year. If it is on the month,
17656 the day or the time, change that.
17657 With prefix ARG, change by that many units."
17658 (interactive "p")
17659 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17661 (defun org-timestamp-up-day (&optional arg)
17662 "Increase the date in the time stamp by one day.
17663 With prefix ARG, change that many days."
17664 (interactive "p")
17665 (if (and (not (org-at-timestamp-p t))
17666 (org-at-heading-p))
17667 (org-todo 'up)
17668 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17670 (defun org-timestamp-down-day (&optional arg)
17671 "Decrease the date in the time stamp by one day.
17672 With prefix ARG, change that many days."
17673 (interactive "p")
17674 (if (and (not (org-at-timestamp-p t))
17675 (org-at-heading-p))
17676 (org-todo 'down)
17677 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17679 (defun org-at-timestamp-p (&optional inactive-ok)
17680 "Determine if the cursor is in or at a timestamp."
17681 (interactive)
17682 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17683 (pos (point))
17684 (ans (or (looking-at tsr)
17685 (save-excursion
17686 (skip-chars-backward "^[<\n\r\t")
17687 (if (> (point) (point-min)) (backward-char 1))
17688 (and (looking-at tsr)
17689 (> (- (match-end 0) pos) -1))))))
17690 (and ans
17691 (boundp 'org-ts-what)
17692 (setq org-ts-what
17693 (cond
17694 ((= pos (match-beginning 0)) 'bracket)
17695 ;; Point is considered to be "on the bracket" whether
17696 ;; it's really on it or right after it.
17697 ((= pos (1- (match-end 0))) 'bracket)
17698 ((= pos (match-end 0)) 'after)
17699 ((org-pos-in-match-range pos 2) 'year)
17700 ((org-pos-in-match-range pos 3) 'month)
17701 ((org-pos-in-match-range pos 7) 'hour)
17702 ((org-pos-in-match-range pos 8) 'minute)
17703 ((or (org-pos-in-match-range pos 4)
17704 (org-pos-in-match-range pos 5)) 'day)
17705 ((and (> pos (or (match-end 8) (match-end 5)))
17706 (< pos (match-end 0)))
17707 (- pos (or (match-end 8) (match-end 5))))
17708 (t 'day))))
17709 ans))
17711 (defun org-toggle-timestamp-type ()
17712 "Toggle the type (<active> or [inactive]) of a time stamp."
17713 (interactive)
17714 (when (org-at-timestamp-p t)
17715 (let ((beg (match-beginning 0)) (end (match-end 0))
17716 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17717 (save-excursion
17718 (goto-char beg)
17719 (while (re-search-forward "[][<>]" end t)
17720 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17721 t t)))
17722 (message "Timestamp is now %sactive"
17723 (if (equal (char-after beg) ?<) "" "in")))))
17725 (defun org-at-clock-log-p nil
17726 "Is the cursor on the clock log line?"
17727 (save-excursion
17728 (move-beginning-of-line 1)
17729 (looking-at org-clock-line-re)))
17731 (defvar org-clock-history) ; defined in org-clock.el
17732 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17733 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17734 "Change the date in the time stamp at point.
17735 The date will be changed by N times WHAT. WHAT can be `day', `month',
17736 `year', `minute', `second'. If WHAT is not given, the cursor position
17737 in the timestamp determines what will be changed.
17738 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17739 (let ((origin (point)) origin-cat
17740 with-hm inactive
17741 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17742 org-ts-what
17743 extra rem
17744 ts time time0 fixnext clrgx)
17745 (if (not (org-at-timestamp-p t))
17746 (user-error "Not at a timestamp"))
17747 (if (and (not what) (eq org-ts-what 'bracket))
17748 (org-toggle-timestamp-type)
17749 ;; Point isn't on brackets. Remember the part of the time-stamp
17750 ;; the point was in. Indeed, size of time-stamps may change,
17751 ;; but point must be kept in the same category nonetheless.
17752 (setq origin-cat org-ts-what)
17753 (if (and (not what) (not (eq org-ts-what 'day))
17754 org-display-custom-times
17755 (get-text-property (point) 'display)
17756 (not (get-text-property (1- (point)) 'display)))
17757 (setq org-ts-what 'day))
17758 (setq org-ts-what (or what org-ts-what)
17759 inactive (= (char-after (match-beginning 0)) ?\[)
17760 ts (match-string 0))
17761 (replace-match "")
17762 (when (string-match
17763 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17765 (setq extra (match-string 1 ts))
17766 (if suppress-tmp-delay
17767 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17768 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17769 (setq with-hm t))
17770 (setq time0 (org-parse-time-string ts))
17771 (when (and updown
17772 (eq org-ts-what 'minute)
17773 (not current-prefix-arg))
17774 ;; This looks like s-up and s-down. Change by one rounding step.
17775 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17776 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17777 (setcar (cdr time0) (+ (nth 1 time0)
17778 (if (> n 0) (- rem) (- dm rem))))))
17779 (setq time
17780 (encode-time (or (car time0) 0)
17781 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17782 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17783 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17784 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17785 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17786 (nthcdr 6 time0)))
17787 (when (and (member org-ts-what '(hour minute))
17788 extra
17789 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17790 (setq extra (org-modify-ts-extra
17791 extra
17792 (if (eq org-ts-what 'hour) 2 5)
17793 n dm)))
17794 (when (integerp org-ts-what)
17795 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17796 (if (eq what 'calendar)
17797 (let ((cal-date (org-get-date-from-calendar)))
17798 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17799 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17800 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17801 (setcar time0 (or (car time0) 0))
17802 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17803 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17804 (setq time (apply 'encode-time time0))))
17805 ;; Insert the new time-stamp, and ensure point stays in the same
17806 ;; category as before (i.e. not after the last position in that
17807 ;; category).
17808 (let ((pos (point)))
17809 ;; Stay before inserted string. `save-excursion' is of no use.
17810 (setq org-last-changed-timestamp
17811 (org-insert-time-stamp time with-hm inactive nil nil extra))
17812 (goto-char pos))
17813 (save-match-data
17814 (looking-at org-ts-regexp3)
17815 (goto-char (cond
17816 ;; `day' category ends before `hour' if any, or at
17817 ;; the end of the day name.
17818 ((eq origin-cat 'day)
17819 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17820 ((eq origin-cat 'hour) (min (match-end 7) origin))
17821 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17822 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17823 ;; `year' and `month' have both fixed size: point
17824 ;; couldn't have moved into another part.
17825 (t origin))))
17826 ;; Update clock if on a CLOCK line.
17827 (org-clock-update-time-maybe)
17828 ;; Maybe adjust the closest clock in `org-clock-history'
17829 (when org-clock-adjust-closest
17830 (if (not (and (org-at-clock-log-p)
17831 (< 1 (length (delq nil (mapcar 'marker-position
17832 org-clock-history))))))
17833 (message "No clock to adjust")
17834 (cond ((save-excursion ; fix previous clock?
17835 (re-search-backward org-ts-regexp0 nil t)
17836 (org-looking-back (concat org-clock-string " \\[")))
17837 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17838 ((save-excursion ; fix next clock?
17839 (re-search-backward org-ts-regexp0 nil t)
17840 (looking-at (concat org-ts-regexp0 "\\] =>")))
17841 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17842 (save-window-excursion
17843 ;; Find closest clock to point, adjust the previous/next one in history
17844 (let* ((p (save-excursion (org-back-to-heading t)))
17845 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17846 (clfixnth
17847 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17848 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17849 (if (not clfixpos)
17850 (message "No clock to adjust")
17851 (save-excursion
17852 (org-goto-marker-or-bmk clfixpos)
17853 (org-show-subtree)
17854 (when (re-search-forward clrgx nil t)
17855 (goto-char (match-beginning 1))
17856 (let (org-clock-adjust-closest)
17857 (org-timestamp-change n org-ts-what updown))
17858 (message "Clock adjusted in %s for heading: %s"
17859 (file-name-nondirectory (buffer-file-name))
17860 (org-get-heading t t)))))))))
17861 ;; Try to recenter the calendar window, if any.
17862 (if (and org-calendar-follow-timestamp-change
17863 (get-buffer-window "*Calendar*" t)
17864 (memq org-ts-what '(day month year)))
17865 (org-recenter-calendar (time-to-days time))))))
17867 (defun org-modify-ts-extra (s pos n dm)
17868 "Change the different parts of the lead-time and repeat fields in timestamp."
17869 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17870 ng h m new rem)
17871 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17872 (cond
17873 ((or (org-pos-in-match-range pos 2)
17874 (org-pos-in-match-range pos 3))
17875 (setq m (string-to-number (match-string 3 s))
17876 h (string-to-number (match-string 2 s)))
17877 (if (org-pos-in-match-range pos 2)
17878 (setq h (+ h n))
17879 (setq n (* dm (org-no-warnings (signum n))))
17880 (when (not (= 0 (setq rem (% m dm))))
17881 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17882 (setq m (+ m n)))
17883 (if (< m 0) (setq m (+ m 60) h (1- h)))
17884 (if (> m 59) (setq m (- m 60) h (1+ h)))
17885 (setq h (min 24 (max 0 h)))
17886 (setq ng 1 new (format "-%02d:%02d" h m)))
17887 ((org-pos-in-match-range pos 6)
17888 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17889 ((org-pos-in-match-range pos 5)
17890 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17892 ((org-pos-in-match-range pos 9)
17893 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17894 ((org-pos-in-match-range pos 8)
17895 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17897 (when ng
17898 (setq s (concat
17899 (substring s 0 (match-beginning ng))
17901 (substring s (match-end ng))))))
17904 (defun org-recenter-calendar (date)
17905 "If the calendar is visible, recenter it to DATE."
17906 (let ((cwin (get-buffer-window "*Calendar*" t)))
17907 (when cwin
17908 (let ((calendar-move-hook nil))
17909 (with-selected-window cwin
17910 (calendar-goto-date (if (listp date) date
17911 (calendar-gregorian-from-absolute date))))))))
17913 (defun org-goto-calendar (&optional arg)
17914 "Go to the Emacs calendar at the current date.
17915 If there is a time stamp in the current line, go to that date.
17916 A prefix ARG can be used to force the current date."
17917 (interactive "P")
17918 (let ((tsr org-ts-regexp) diff
17919 (calendar-move-hook nil)
17920 (calendar-view-holidays-initially-flag nil)
17921 (calendar-view-diary-initially-flag nil))
17922 (if (or (org-at-timestamp-p)
17923 (save-excursion
17924 (beginning-of-line 1)
17925 (looking-at (concat ".*" tsr))))
17926 (let ((d1 (time-to-days (current-time)))
17927 (d2 (time-to-days
17928 (org-time-string-to-time (match-string 1)))))
17929 (setq diff (- d2 d1))))
17930 (calendar)
17931 (calendar-goto-today)
17932 (if (and diff (not arg)) (calendar-forward-day diff))))
17934 (defun org-get-date-from-calendar ()
17935 "Return a list (month day year) of date at point in calendar."
17936 (with-current-buffer "*Calendar*"
17937 (save-match-data
17938 (calendar-cursor-to-date))))
17940 (defun org-date-from-calendar ()
17941 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17942 If there is already a time stamp at the cursor position, update it."
17943 (interactive)
17944 (if (org-at-timestamp-p t)
17945 (org-timestamp-change 0 'calendar)
17946 (let ((cal-date (org-get-date-from-calendar)))
17947 (org-insert-time-stamp
17948 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17950 (defcustom org-effort-durations
17951 `(("min" . 1)
17952 ("h" . 60)
17953 ("d" . ,(* 60 8))
17954 ("w" . ,(* 60 8 5))
17955 ("m" . ,(* 60 8 5 4))
17956 ("y" . ,(* 60 8 5 40)))
17957 "Conversion factor to minutes for an effort modifier.
17959 Each entry has the form (MODIFIER . MINUTES).
17961 In an effort string, a number followed by MODIFIER is multiplied
17962 by the specified number of MINUTES to obtain an effort in
17963 minutes.
17965 For example, if the value of this variable is ((\"hours\" . 60)), then an
17966 effort string \"2hours\" is equivalent to 120 minutes."
17967 :group 'org-agenda
17968 :version "25.1"
17969 :package-version '(Org . "8.3")
17970 :type '(alist :key-type (string :tag "Modifier")
17971 :value-type (number :tag "Minutes")))
17973 (defun org-minutes-to-clocksum-string (m)
17974 "Format number of minutes as a clocksum string.
17975 The format is determined by `org-time-clocksum-format',
17976 `org-time-clocksum-use-fractional' and
17977 `org-time-clocksum-fractional-format' and
17978 `org-time-clocksum-use-effort-durations'."
17979 (let ((clocksum "")
17980 (m (round m)) ; Don't allow fractions of minutes
17981 h d w mo y fmt n)
17982 (setq h (if org-time-clocksum-use-effort-durations
17983 (cdr (assoc "h" org-effort-durations)) 60)
17984 d (if org-time-clocksum-use-effort-durations
17985 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17986 w (if org-time-clocksum-use-effort-durations
17987 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17988 mo (if org-time-clocksum-use-effort-durations
17989 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17990 y (if org-time-clocksum-use-effort-durations
17991 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17992 ;; fractional format
17993 (if org-time-clocksum-use-fractional
17994 (cond
17995 ;; single format string
17996 ((stringp org-time-clocksum-fractional-format)
17997 (format org-time-clocksum-fractional-format (/ m (float h))))
17998 ;; choice of fractional formats for different time units
17999 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18000 (> (/ (truncate m) (* y d h)) 0))
18001 (format fmt (/ m (* y d (float h)))))
18002 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18003 (> (/ (truncate m) (* mo d h)) 0))
18004 (format fmt (/ m (* mo d (float h)))))
18005 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18006 (> (/ (truncate m) (* w d h)) 0))
18007 (format fmt (/ m (* w d (float h)))))
18008 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18009 (> (/ (truncate m) (* d h)) 0))
18010 (format fmt (/ m (* d (float h)))))
18011 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18012 (> (/ (truncate m) h) 0))
18013 (format fmt (/ m (float h))))
18014 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18015 (format fmt m))
18016 ;; fall back to smallest time unit with a format
18017 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18018 (format fmt (/ m (float h))))
18019 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18020 (format fmt (/ m (* d (float h)))))
18021 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18022 (format fmt (/ m (* w d (float h)))))
18023 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18024 (format fmt (/ m (* mo d (float h)))))
18025 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18026 (format fmt (/ m (* y d (float h))))))
18027 ;; standard (non-fractional) format, with single format string
18028 (if (stringp org-time-clocksum-format)
18029 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18030 ;; separate formats components
18031 (and (setq fmt (plist-get org-time-clocksum-format :years))
18032 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18033 (plist-get org-time-clocksum-format :require-years))
18034 (setq clocksum (concat clocksum (format fmt n))
18035 m (- m (* n y d h))))
18036 (and (setq fmt (plist-get org-time-clocksum-format :months))
18037 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18038 (plist-get org-time-clocksum-format :require-months))
18039 (setq clocksum (concat clocksum (format fmt n))
18040 m (- m (* n mo d h))))
18041 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18042 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18043 (plist-get org-time-clocksum-format :require-weeks))
18044 (setq clocksum (concat clocksum (format fmt n))
18045 m (- m (* n w d h))))
18046 (and (setq fmt (plist-get org-time-clocksum-format :days))
18047 (or (> (setq n (/ (truncate m) (* d h))) 0)
18048 (plist-get org-time-clocksum-format :require-days))
18049 (setq clocksum (concat clocksum (format fmt n))
18050 m (- m (* n d h))))
18051 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18052 (or (> (setq n (/ (truncate m) h)) 0)
18053 (plist-get org-time-clocksum-format :require-hours))
18054 (setq clocksum (concat clocksum (format fmt n))
18055 m (- m (* n h))))
18056 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18057 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18058 (setq clocksum (concat clocksum (format fmt m))))
18059 ;; return formatted time duration
18060 clocksum))))
18062 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18063 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18064 "Org mode version 8.0")
18066 (defun org-hours-to-clocksum-string (n)
18067 (org-minutes-to-clocksum-string (* n 60)))
18069 (defun org-hh:mm-string-to-minutes (s)
18070 "Convert a string H:MM to a number of minutes.
18071 If the string is just a number, interpret it as minutes.
18072 In fact, the first hh:mm or number in the string will be taken,
18073 there can be extra stuff in the string.
18074 If no number is found, the return value is 0."
18075 (cond
18076 ((integerp s) s)
18077 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18078 (+ (* (string-to-number (match-string 1 s)) 60)
18079 (string-to-number (match-string 2 s))))
18080 ((string-match "\\([0-9]+\\)" s)
18081 (string-to-number (match-string 1 s)))
18082 (t 0)))
18084 (defcustom org-image-actual-width t
18085 "Should we use the actual width of images when inlining them?
18087 When set to `t', always use the image width.
18089 When set to a number, use imagemagick (when available) to set
18090 the image's width to this value.
18092 When set to a number in a list, try to get the width from any
18093 #+ATTR.* keyword if it matches a width specification like
18095 #+ATTR_HTML: :width 300px
18097 and fall back on that number if none is found.
18099 When set to nil, try to get the width from an #+ATTR.* keyword
18100 and fall back on the original width if none is found.
18102 This requires Emacs >= 24.1, build with imagemagick support."
18103 :group 'org-appearance
18104 :version "24.4"
18105 :package-version '(Org . "8.0")
18106 :type '(choice
18107 (const :tag "Use the image width" t)
18108 (integer :tag "Use a number of pixels")
18109 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18110 (const :tag "Use #+ATTR* or don't resize" nil)))
18112 (defcustom org-agenda-inhibit-startup nil
18113 "Inhibit startup when preparing agenda buffers.
18114 When this variable is `t', the initialization of the Org agenda
18115 buffers is inhibited: e.g. the visibility state is not set, the
18116 tables are not re-aligned, etc."
18117 :type 'boolean
18118 :version "24.3"
18119 :group 'org-agenda)
18121 (define-obsolete-variable-alias
18122 'org-agenda-ignore-drawer-properties
18123 'org-agenda-ignore-properties "25.1")
18125 (defcustom org-agenda-ignore-properties nil
18126 "Avoid updating text properties when building the agenda.
18127 Properties are used to prepare buffers for effort estimates,
18128 appointments, statistics and subtree-local categories.
18129 If you don't use these in the agenda, you can add them to this
18130 list and agenda building will be a bit faster.
18131 The value is a list, with zero or more of the symbols `effort', `appt',
18132 `stats' or `category'."
18133 :type '(set :greedy t
18134 (const effort)
18135 (const appt)
18136 (const stats)
18137 (const category))
18138 :version "25.1"
18139 :package-version '(Org . "8.3")
18140 :group 'org-agenda)
18142 (defun org-duration-string-to-minutes (s &optional output-to-string)
18143 "Convert a duration string S to minutes.
18145 A bare number is interpreted as minutes, modifiers can be set by
18146 customizing `org-effort-durations' (which see).
18148 Entries containing a colon are interpreted as H:MM by
18149 `org-hh:mm-string-to-minutes'."
18150 (let ((result 0)
18151 (re (concat "\\([0-9.]+\\) *\\("
18152 (regexp-opt (mapcar 'car org-effort-durations))
18153 "\\)")))
18154 (while (string-match re s)
18155 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18156 (string-to-number (match-string 1 s))))
18157 (setq s (replace-match "" nil t s)))
18158 (setq result (floor result))
18159 (incf result (org-hh:mm-string-to-minutes s))
18160 (if output-to-string (number-to-string result) result)))
18162 ;;;; Files
18164 (defun org-save-all-org-buffers ()
18165 "Save all Org-mode buffers without user confirmation."
18166 (interactive)
18167 (message "Saving all Org-mode buffers...")
18168 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18169 (when (featurep 'org-id) (org-id-locations-save))
18170 (message "Saving all Org-mode buffers... done"))
18172 (defun org-revert-all-org-buffers ()
18173 "Revert all Org-mode buffers.
18174 Prompt for confirmation when there are unsaved changes.
18175 Be sure you know what you are doing before letting this function
18176 overwrite your changes.
18178 This function is useful in a setup where one tracks org files
18179 with a version control system, to revert on one machine after pulling
18180 changes from another. I believe the procedure must be like this:
18182 1. M-x org-save-all-org-buffers
18183 2. Pull changes from the other machine, resolve conflicts
18184 3. M-x org-revert-all-org-buffers"
18185 (interactive)
18186 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18187 (user-error "Abort"))
18188 (save-excursion
18189 (save-window-excursion
18190 (mapc
18191 (lambda (b)
18192 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18193 (with-current-buffer b buffer-file-name))
18194 (org-pop-to-buffer-same-window b)
18195 (revert-buffer t 'no-confirm)))
18196 (buffer-list))
18197 (when (and (featurep 'org-id) org-id-track-globally)
18198 (org-id-locations-load)))))
18200 ;;;; Agenda files
18202 ;;;###autoload
18203 (defun org-switchb (&optional arg)
18204 "Switch between Org buffers.
18205 With one prefix argument, restrict available buffers to files.
18206 With two prefix arguments, restrict available buffers to agenda files.
18208 Defaults to `iswitchb' for buffer name completion.
18209 Set `org-completion-use-ido' to make it use ido instead."
18210 (interactive "P")
18211 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18212 ((equal arg '(16)) (org-buffer-list 'agenda))
18213 (t (org-buffer-list))))
18214 (org-completion-use-iswitchb org-completion-use-iswitchb)
18215 (org-completion-use-ido org-completion-use-ido))
18216 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18217 (setq org-completion-use-iswitchb t))
18218 (org-pop-to-buffer-same-window
18219 (org-icompleting-read "Org buffer: "
18220 (mapcar 'list (mapcar 'buffer-name blist))
18221 nil t))))
18223 ;;; Define some older names previously used for this functionality
18224 ;;;###autoload
18225 (defalias 'org-ido-switchb 'org-switchb)
18226 ;;;###autoload
18227 (defalias 'org-iswitchb 'org-switchb)
18229 (defun org-buffer-list (&optional predicate exclude-tmp)
18230 "Return a list of Org buffers.
18231 PREDICATE can be `export', `files' or `agenda'.
18233 export restrict the list to Export buffers.
18234 files restrict the list to buffers visiting Org files.
18235 agenda restrict the list to buffers visiting agenda files.
18237 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18238 (let* ((bfn nil)
18239 (agenda-files (and (eq predicate 'agenda)
18240 (mapcar 'file-truename (org-agenda-files t))))
18241 (filter
18242 (cond
18243 ((eq predicate 'files)
18244 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18245 ((eq predicate 'export)
18246 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
18247 ((eq predicate 'agenda)
18248 (lambda (b)
18249 (with-current-buffer b
18250 (and (derived-mode-p 'org-mode)
18251 (setq bfn (buffer-file-name b))
18252 (member (file-truename bfn) agenda-files)))))
18253 (t (lambda (b) (with-current-buffer b
18254 (or (derived-mode-p 'org-mode)
18255 (string-match "\*Org .*Export"
18256 (buffer-name b)))))))))
18257 (delq nil
18258 (mapcar
18259 (lambda(b)
18260 (if (and (funcall filter b)
18261 (or (not exclude-tmp)
18262 (not (string-match "tmp" (buffer-name b)))))
18264 nil))
18265 (buffer-list)))))
18267 (defun org-agenda-files (&optional unrestricted archives)
18268 "Get the list of agenda files.
18269 Optional UNRESTRICTED means return the full list even if a restriction
18270 is currently in place.
18271 When ARCHIVES is t, include all archive files that are really being
18272 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18273 `org-agenda-archives-mode' is t."
18274 (let ((files
18275 (cond
18276 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18277 ((stringp org-agenda-files) (org-read-agenda-file-list))
18278 ((listp org-agenda-files) org-agenda-files)
18279 (t (error "Invalid value of `org-agenda-files'")))))
18280 (setq files (apply 'append
18281 (mapcar (lambda (f)
18282 (if (file-directory-p f)
18283 (directory-files
18284 f t org-agenda-file-regexp)
18285 (list f)))
18286 files)))
18287 (when org-agenda-skip-unavailable-files
18288 (setq files (delq nil
18289 (mapcar (function
18290 (lambda (file)
18291 (and (file-readable-p file) file)))
18292 files))))
18293 (when (or (eq archives t)
18294 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18295 (setq files (org-add-archive-files files)))
18296 files))
18298 (defun org-agenda-file-p (&optional file)
18299 "Return non-nil, if FILE is an agenda file.
18300 If FILE is omitted, use the file associated with the current
18301 buffer."
18302 (let ((fname (or file (buffer-file-name))))
18303 (and fname
18304 (member (file-truename fname)
18305 (mapcar #'file-truename (org-agenda-files t))))))
18307 (defun org-edit-agenda-file-list ()
18308 "Edit the list of agenda files.
18309 Depending on setup, this either uses customize to edit the variable
18310 `org-agenda-files', or it visits the file that is holding the list. In the
18311 latter case, the buffer is set up in a way that saving it automatically kills
18312 the buffer and restores the previous window configuration."
18313 (interactive)
18314 (if (stringp org-agenda-files)
18315 (let ((cw (current-window-configuration)))
18316 (find-file org-agenda-files)
18317 (org-set-local 'org-window-configuration cw)
18318 (org-add-hook 'after-save-hook
18319 (lambda ()
18320 (set-window-configuration
18321 (prog1 org-window-configuration
18322 (kill-buffer (current-buffer))))
18323 (org-install-agenda-files-menu)
18324 (message "New agenda file list installed"))
18325 nil 'local)
18326 (message "%s" (substitute-command-keys
18327 "Edit list and finish with \\[save-buffer]")))
18328 (customize-variable 'org-agenda-files)))
18330 (defun org-store-new-agenda-file-list (list)
18331 "Set new value for the agenda file list and save it correctly."
18332 (if (stringp org-agenda-files)
18333 (let ((fe (org-read-agenda-file-list t)) b u)
18334 (while (setq b (find-buffer-visiting org-agenda-files))
18335 (kill-buffer b))
18336 (with-temp-file org-agenda-files
18337 (insert
18338 (mapconcat
18339 (lambda (f) ;; Keep un-expanded entries.
18340 (if (setq u (assoc f fe))
18341 (cdr u)
18343 list "\n")
18344 "\n")))
18345 (let ((org-mode-hook nil) (org-inhibit-startup t)
18346 (org-insert-mode-line-in-empty-file nil))
18347 (setq org-agenda-files list)
18348 (customize-save-variable 'org-agenda-files org-agenda-files))))
18350 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18351 "Read the list of agenda files from a file.
18352 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18353 filenames, used by `org-store-new-agenda-file-list' to write back
18354 un-expanded file names."
18355 (when (file-directory-p org-agenda-files)
18356 (error "`org-agenda-files' cannot be a single directory"))
18357 (when (stringp org-agenda-files)
18358 (with-temp-buffer
18359 (insert-file-contents org-agenda-files)
18360 (mapcar
18361 (lambda (f)
18362 (let ((e (expand-file-name (substitute-in-file-name f)
18363 org-directory)))
18364 (if pair-with-expansion
18365 (cons e f)
18366 e)))
18367 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18369 ;;;###autoload
18370 (defun org-cycle-agenda-files ()
18371 "Cycle through the files in `org-agenda-files'.
18372 If the current buffer visits an agenda file, find the next one in the list.
18373 If the current buffer does not, find the first agenda file."
18374 (interactive)
18375 (let* ((fs (org-agenda-files t))
18376 (files (append fs (list (car fs))))
18377 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18378 file)
18379 (unless files (user-error "No agenda files"))
18380 (catch 'exit
18381 (while (setq file (pop files))
18382 (if (equal (file-truename file) tcf)
18383 (when (car files)
18384 (find-file (car files))
18385 (throw 'exit t))))
18386 (find-file (car fs)))
18387 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18389 (defun org-agenda-file-to-front (&optional to-end)
18390 "Move/add the current file to the top of the agenda file list.
18391 If the file is not present in the list, it is added to the front. If it is
18392 present, it is moved there. With optional argument TO-END, add/move to the
18393 end of the list."
18394 (interactive "P")
18395 (let ((org-agenda-skip-unavailable-files nil)
18396 (file-alist (mapcar (lambda (x)
18397 (cons (file-truename x) x))
18398 (org-agenda-files t)))
18399 (ctf (file-truename
18400 (or buffer-file-name
18401 (user-error "Please save the current buffer to a file"))))
18402 x had)
18403 (setq x (assoc ctf file-alist) had x)
18405 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18406 (if to-end
18407 (setq file-alist (append (delq x file-alist) (list x)))
18408 (setq file-alist (cons x (delq x file-alist))))
18409 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18410 (org-install-agenda-files-menu)
18411 (message "File %s to %s of agenda file list"
18412 (if had "moved" "added") (if to-end "end" "front"))))
18414 (defun org-remove-file (&optional file)
18415 "Remove current file from the list of files in variable `org-agenda-files'.
18416 These are the files which are being checked for agenda entries.
18417 Optional argument FILE means use this file instead of the current."
18418 (interactive)
18419 (let* ((org-agenda-skip-unavailable-files nil)
18420 (file (or file buffer-file-name
18421 (user-error "Current buffer does not visit a file")))
18422 (true-file (file-truename file))
18423 (afile (abbreviate-file-name file))
18424 (files (delq nil (mapcar
18425 (lambda (x)
18426 (if (equal true-file
18427 (file-truename x))
18428 nil x))
18429 (org-agenda-files t)))))
18430 (if (not (= (length files) (length (org-agenda-files t))))
18431 (progn
18432 (org-store-new-agenda-file-list files)
18433 (org-install-agenda-files-menu)
18434 (message "Removed from Org Agenda list: %s" afile))
18435 (message "File was not in list: %s (not removed)" afile))))
18437 (defun org-file-menu-entry (file)
18438 (vector file (list 'find-file file) t))
18440 (defun org-check-agenda-file (file)
18441 "Make sure FILE exists. If not, ask user what to do."
18442 (when (not (file-exists-p file))
18443 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18444 (abbreviate-file-name file))
18445 (let ((r (downcase (read-char-exclusive))))
18446 (cond
18447 ((equal r ?r)
18448 (org-remove-file file)
18449 (throw 'nextfile t))
18450 (t (user-error "Abort"))))))
18452 (defun org-get-agenda-file-buffer (file)
18453 "Get an agenda buffer visiting FILE.
18454 If the buffer needs to be created, add it to the list of buffers
18455 which might be released later."
18456 (let ((buf (org-find-base-buffer-visiting file)))
18457 (if buf
18458 buf ; just return it
18459 ;; Make a new buffer and remember it
18460 (setq buf (find-file-noselect file))
18461 (if buf (push buf org-agenda-new-buffers))
18462 buf)))
18464 (defun org-release-buffers (blist)
18465 "Release all buffers in list, asking the user for confirmation when needed.
18466 When a buffer is unmodified, it is just killed. When modified, it is saved
18467 \(if the user agrees) and then killed."
18468 (let (buf file)
18469 (while (setq buf (pop blist))
18470 (setq file (buffer-file-name buf))
18471 (when (and (buffer-modified-p buf)
18472 file
18473 (y-or-n-p (format "Save file %s? " file)))
18474 (with-current-buffer buf (save-buffer)))
18475 (kill-buffer buf))))
18477 (defun org-agenda-prepare-buffers (files)
18478 "Create buffers for all agenda files, protect archived trees and comments."
18479 (interactive)
18480 (let ((pa '(:org-archived t))
18481 (pc '(:org-comment t))
18482 (pall '(:org-archived t :org-comment t))
18483 (inhibit-read-only t)
18484 (org-inhibit-startup org-agenda-inhibit-startup)
18485 (rea (concat ":" org-archive-tag ":"))
18486 file re pos)
18487 (setq org-tag-alist-for-agenda nil
18488 org-tag-groups-alist-for-agenda nil)
18489 (save-excursion
18490 (save-restriction
18491 (while (setq file (pop files))
18492 (catch 'nextfile
18493 (if (bufferp file)
18494 (set-buffer file)
18495 (org-check-agenda-file file)
18496 (set-buffer (org-get-agenda-file-buffer file)))
18497 (widen)
18498 (org-set-regexps-and-options 'tags-only)
18499 (setq pos (point))
18500 (or (memq 'category org-agenda-ignore-properties)
18501 (org-refresh-category-properties))
18502 (or (memq 'stats org-agenda-ignore-properties)
18503 (org-refresh-stats-properties))
18504 (or (memq 'effort org-agenda-ignore-properties)
18505 (org-refresh-effort-properties))
18506 (or (memq 'appt org-agenda-ignore-properties)
18507 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18508 (setq org-todo-keywords-for-agenda
18509 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18510 (setq org-done-keywords-for-agenda
18511 (append org-done-keywords-for-agenda org-done-keywords))
18512 (setq org-todo-keyword-alist-for-agenda
18513 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18514 (setq org-tag-alist-for-agenda
18515 (org-uniquify
18516 (append org-tag-alist-for-agenda
18517 org-tag-alist
18518 org-tag-persistent-alist)))
18519 (if org-group-tags
18520 (setq org-tag-groups-alist-for-agenda
18521 (org-uniquify-alist
18522 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18523 (org-with-silent-modifications
18524 (save-excursion
18525 (remove-text-properties (point-min) (point-max) pall)
18526 (when org-agenda-skip-archived-trees
18527 (goto-char (point-min))
18528 (while (re-search-forward rea nil t)
18529 (if (org-at-heading-p t)
18530 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18531 (goto-char (point-min))
18532 (setq re (format "^\\* .*\\<%s\\>" org-comment-string))
18533 (while (re-search-forward re nil t)
18534 (when (save-match-data (org-in-commented-heading-p t))
18535 (add-text-properties
18536 (match-beginning 0) (org-end-of-subtree t) pc)))))
18537 (goto-char pos)))))
18538 (setq org-todo-keywords-for-agenda
18539 (org-uniquify org-todo-keywords-for-agenda))
18540 (setq org-todo-keyword-alist-for-agenda
18541 (org-uniquify org-todo-keyword-alist-for-agenda))))
18544 ;;;; CDLaTeX minor mode
18546 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18547 "Keymap for the minor `org-cdlatex-mode'.")
18549 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18550 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18551 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18552 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18553 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18555 (defvar org-cdlatex-texmathp-advice-is-done nil
18556 "Flag remembering if we have applied the advice to texmathp already.")
18558 (define-minor-mode org-cdlatex-mode
18559 "Toggle the minor `org-cdlatex-mode'.
18560 This mode supports entering LaTeX environment and math in LaTeX fragments
18561 in Org-mode.
18562 \\{org-cdlatex-mode-map}"
18563 nil " OCDL" nil
18564 (when org-cdlatex-mode
18565 (require 'cdlatex)
18566 (run-hooks 'cdlatex-mode-hook)
18567 (cdlatex-compute-tables))
18568 (unless org-cdlatex-texmathp-advice-is-done
18569 (setq org-cdlatex-texmathp-advice-is-done t)
18570 (defadvice texmathp (around org-math-always-on activate)
18571 "Always return t in org-mode buffers.
18572 This is because we want to insert math symbols without dollars even outside
18573 the LaTeX math segments. If Orgmode thinks that point is actually inside
18574 an embedded LaTeX fragment, let texmathp do its job.
18575 \\[org-cdlatex-mode-map]"
18576 (interactive)
18577 (let (p)
18578 (cond
18579 ((not (derived-mode-p 'org-mode)) ad-do-it)
18580 ((eq this-command 'cdlatex-math-symbol)
18581 (setq ad-return-value t
18582 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18584 (let ((p (org-inside-LaTeX-fragment-p)))
18585 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18586 (setq ad-return-value t
18587 texmathp-why '("Org-mode embedded math" . 0))
18588 (if p ad-do-it)))))))))
18590 (defun turn-on-org-cdlatex ()
18591 "Unconditionally turn on `org-cdlatex-mode'."
18592 (org-cdlatex-mode 1))
18594 (defun org-try-cdlatex-tab ()
18595 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18596 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18597 - inside a LaTeX fragment, or
18598 - after the first word in a line, where an abbreviation expansion could
18599 insert a LaTeX environment."
18600 (when org-cdlatex-mode
18601 (cond
18602 ;; Before any word on the line: No expansion possible.
18603 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18604 ;; Just after first word on the line: Expand it. Make sure it
18605 ;; cannot happen on headlines, though.
18606 ((save-excursion
18607 (skip-chars-backward "a-zA-Z0-9*")
18608 (skip-chars-backward " \t")
18609 (and (bolp) (not (org-at-heading-p))))
18610 (cdlatex-tab) t)
18611 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18613 (defun org-cdlatex-underscore-caret (&optional arg)
18614 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18615 Revert to the normal definition outside of these fragments."
18616 (interactive "P")
18617 (if (org-inside-LaTeX-fragment-p)
18618 (call-interactively 'cdlatex-sub-superscript)
18619 (let (org-cdlatex-mode)
18620 (call-interactively (key-binding (vector last-input-event))))))
18622 (defun org-cdlatex-math-modify (&optional arg)
18623 "Execute `cdlatex-math-modify' in LaTeX fragments.
18624 Revert to the normal definition outside of these fragments."
18625 (interactive "P")
18626 (if (org-inside-LaTeX-fragment-p)
18627 (call-interactively 'cdlatex-math-modify)
18628 (let (org-cdlatex-mode)
18629 (call-interactively (key-binding (vector last-input-event))))))
18631 (defun org-cdlatex-environment-indent (&optional environment item)
18632 "Execute `cdlatex-environment' and indent the inserted environment."
18633 (interactive)
18634 (cdlatex-environment environment item)
18635 (let ((element (org-element-at-point)))
18636 (org-indent-region (org-element-property :begin element)
18637 (org-element-property :end element))))
18640 ;;;; LaTeX fragments
18642 (defun org-inside-LaTeX-fragment-p ()
18643 "Test if point is inside a LaTeX fragment.
18644 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18645 sequence appearing also before point.
18646 Even though the matchers for math are configurable, this function assumes
18647 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18648 delimiters are skipped when they have been removed by customization.
18649 The return value is nil, or a cons cell with the delimiter and the
18650 position of this delimiter.
18652 This function does a reasonably good job, but can locally be fooled by
18653 for example currency specifications. For example it will assume being in
18654 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18655 fragments that are properly closed, but during editing, we have to live
18656 with the uncertainty caused by missing closing delimiters. This function
18657 looks only before point, not after."
18658 (catch 'exit
18659 (let ((pos (point))
18660 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18661 (lim (progn
18662 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18663 (point)))
18664 dd-on str (start 0) m re)
18665 (goto-char pos)
18666 (when dodollar
18667 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18668 re (nth 1 (assoc "$" org-latex-regexps)))
18669 (while (string-match re str start)
18670 (cond
18671 ((= (match-end 0) (length str))
18672 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18673 ((= (match-end 0) (- (length str) 5))
18674 (throw 'exit nil))
18675 (t (setq start (match-end 0))))))
18676 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18677 (goto-char pos)
18678 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18679 (and (match-beginning 2) (throw 'exit nil))
18680 ;; count $$
18681 (while (re-search-backward "\\$\\$" lim t)
18682 (setq dd-on (not dd-on)))
18683 (goto-char pos)
18684 (if dd-on (cons "$$" m))))))
18686 (defun org-inside-latex-macro-p ()
18687 "Is point inside a LaTeX macro or its arguments?"
18688 (save-match-data
18689 (org-in-regexp
18690 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18692 (defvar org-latex-fragment-image-overlays nil
18693 "List of overlays carrying the images of latex fragments.")
18694 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18696 (defun org-remove-latex-fragment-image-overlays ()
18697 "Remove all overlays with LaTeX fragment images in current buffer."
18698 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18699 (setq org-latex-fragment-image-overlays nil))
18701 (define-obsolete-function-alias
18702 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18703 (defun org-toggle-latex-fragment (&optional subtree)
18704 "Preview the LaTeX fragment at point, or all locally or globally.
18705 If the cursor is in a LaTeX fragment, create the image and overlay
18706 it over the source code. If there is no fragment at point, display
18707 all fragments in the current text, from one headline to the next. With
18708 prefix SUBTREE, display all fragments in the current subtree. With a
18709 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18710 the cursor is before the first headline,
18711 display all fragments in the buffer.
18712 The images can be removed again with \\[org-toggle-latex-fragment]."
18713 (interactive "P")
18714 (unless (buffer-file-name (buffer-base-buffer))
18715 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18716 (if org-latex-fragment-image-overlays
18717 (progn (org-remove-latex-fragment-image-overlays)
18718 (message "LaTeX fragments images removed"))
18719 (when (display-graphic-p)
18720 (org-remove-latex-fragment-image-overlays)
18721 (org-with-wide-buffer
18722 (let (beg end msg)
18723 (cond
18724 ((equal subtree '(16))
18725 (setq beg (point-min) end (point-max)
18726 msg "Creating images for buffer...%s"))
18727 ((equal subtree '(4))
18728 (org-back-to-heading)
18729 (setq beg (point) end (org-end-of-subtree t)
18730 msg "Creating images for subtree...%s"))
18731 ((let ((context (org-element-context)))
18732 (when (memq (org-element-type context)
18733 '(latex-environment latex-fragment))
18734 (setq beg (org-element-property :begin context)
18735 end (org-element-property :end context)
18736 msg "Creating image...%s"))))
18737 ((org-before-first-heading-p)
18738 (setq beg (point-min) end (point-max)
18739 msg "Creating images for buffer...%s"))
18741 (org-back-to-heading)
18742 (setq beg (point) end (progn (outline-next-heading) (point))
18743 msg "Creating images for entry...%s")))
18744 (message msg "")
18745 (narrow-to-region beg end)
18746 (goto-char beg)
18747 (org-format-latex
18748 (concat org-latex-preview-ltxpng-directory
18749 (file-name-sans-extension
18750 (file-name-nondirectory
18751 (buffer-file-name (buffer-base-buffer)))))
18752 default-directory 'overlays msg 'forbuffer
18753 org-latex-create-formula-image-program)
18754 (message msg "done. Use `C-c C-x C-l' to remove images."))))))
18756 (defun org-format-latex
18757 (prefix &optional dir overlays msg forbuffer processing-type)
18758 "Replace LaTeX fragments with links to an image, and produce images.
18759 Some of the options can be changed using the variable
18760 `org-format-latex-options'."
18761 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18762 (unless (eq processing-type 'verbatim)
18763 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18764 (cnt 0)
18765 checkdir-flag)
18766 (goto-char (point-min))
18767 (while (re-search-forward math-regexp nil t)
18768 (unless (and overlays
18769 (eq (get-char-property (point) 'org-overlay-type)
18770 'org-latex-overlay))
18771 (let* ((context (org-element-context))
18772 (type (org-element-type context)))
18773 (when (memq type '(latex-environment latex-fragment))
18774 (let ((block-type (eq type 'latex-environment))
18775 (value (org-element-property :value context))
18776 (beg (org-element-property :begin context))
18777 (end (save-excursion
18778 (goto-char (org-element-property :end context))
18779 (skip-chars-backward " \r\t\n")
18780 (point))))
18781 (case processing-type
18782 (mathjax
18783 ;; Prepare for MathJax processing.
18784 (if (eq (char-after beg) ?$)
18785 (save-excursion
18786 (delete-region beg end)
18787 (insert "\\(" (substring value 1 -1) "\\)"))
18788 (goto-char end)))
18789 ((dvipng imagemagick)
18790 ;; Process to an image.
18791 (incf cnt)
18792 (goto-char beg)
18793 (let* ((face (face-at-point))
18794 ;; Get the colors from the face at point.
18796 (let ((color (plist-get org-format-latex-options
18797 :foreground)))
18798 (if (and forbuffer (eq color 'auto))
18799 (face-attribute face :foreground nil 'default)
18800 color)))
18802 (let ((color (plist-get org-format-latex-options
18803 :background)))
18804 (if (and forbuffer (eq color 'auto))
18805 (face-attribute face :background nil 'default)
18806 color)))
18807 (hash (sha1 (prin1-to-string
18808 (list org-format-latex-header
18809 org-latex-default-packages-alist
18810 org-latex-packages-alist
18811 org-format-latex-options
18812 forbuffer value fg bg))))
18813 (absprefix (expand-file-name prefix dir))
18814 (linkfile (format "%s_%s.png" prefix hash))
18815 (movefile (format "%s_%s.png" absprefix hash))
18816 (sep (and block-type "\n\n"))
18817 (link (concat sep "[[file:" linkfile "]]" sep))
18818 (options
18819 (org-combine-plists
18820 org-format-latex-options
18821 `(:foreground ,fg :background ,bg))))
18822 (when msg (message msg cnt))
18823 (unless checkdir-flag ; Ensure the directory exists.
18824 (setq checkdir-flag t)
18825 (let ((todir (file-name-directory absprefix)))
18826 (unless (file-directory-p todir)
18827 (make-directory todir t))))
18828 (unless (file-exists-p movefile)
18829 (org-create-formula-image
18830 value movefile options forbuffer processing-type))
18831 (if overlays
18832 (progn
18833 (dolist (o (overlays-in beg end))
18834 (when (eq (overlay-get o 'org-overlay-type)
18835 'org-latex-overlay)
18836 (delete-overlay o)))
18837 (let ((ov (make-overlay beg end)))
18838 (overlay-put ov
18839 'org-overlay-type
18840 'org-latex-overlay)
18841 (if (featurep 'xemacs)
18842 (progn
18843 (overlay-put ov 'invisible t)
18844 (overlay-put
18845 ov 'end-glyph
18846 (make-glyph
18847 (vector 'png :file movefile))))
18848 (overlay-put
18849 ov 'display
18850 (list 'image
18851 :type 'png
18852 :file movefile
18853 :ascent 'center)))
18854 (push ov org-latex-fragment-image-overlays))
18855 (goto-char end))
18856 (delete-region beg end)
18857 (insert
18858 (org-add-props link
18859 (list 'org-latex-src
18860 (replace-regexp-in-string "\"" "" value)
18861 'org-latex-src-embed-type
18862 (if block-type 'paragraph 'character)))))))
18863 (mathml
18864 ;; Process to MathML.
18865 (unless (org-format-latex-mathml-available-p)
18866 (user-error "LaTeX to MathML converter not configured"))
18867 (incf cnt)
18868 (when msg (message msg cnt))
18869 (goto-char beg)
18870 (delete-region beg end)
18871 (insert (org-format-latex-as-mathml
18872 value block-type prefix dir)))
18873 (otherwise
18874 (error "Unknown conversion type %s for LaTeX fragments"
18875 processing-type)))))))))))
18877 (defun org-create-math-formula (latex-frag &optional mathml-file)
18878 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18879 Use `org-latex-to-mathml-convert-command'. If the conversion is
18880 sucessful, return the portion between \"<math...> </math>\"
18881 elements otherwise return nil. When MATHML-FILE is specified,
18882 write the results in to that file. When invoked as an
18883 interactive command, prompt for LATEX-FRAG, with initial value
18884 set to the current active region and echo the results for user
18885 inspection."
18886 (interactive (list (let ((frag (when (org-region-active-p)
18887 (buffer-substring-no-properties
18888 (region-beginning) (region-end)))))
18889 (read-string "LaTeX Fragment: " frag nil frag))))
18890 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18891 (let* ((tmp-in-file (file-relative-name
18892 (make-temp-name (expand-file-name "ltxmathml-in"))))
18893 (ignore (write-region latex-frag nil tmp-in-file))
18894 (tmp-out-file (file-relative-name
18895 (make-temp-name (expand-file-name "ltxmathml-out"))))
18896 (cmd (format-spec
18897 org-latex-to-mathml-convert-command
18898 `((?j . ,(shell-quote-argument
18899 (expand-file-name org-latex-to-mathml-jar-file)))
18900 (?I . ,(shell-quote-argument tmp-in-file))
18901 (?o . ,(shell-quote-argument tmp-out-file)))))
18902 mathml shell-command-output)
18903 (when (org-called-interactively-p 'any)
18904 (unless (org-format-latex-mathml-available-p)
18905 (user-error "LaTeX to MathML converter not configured")))
18906 (message "Running %s" cmd)
18907 (setq shell-command-output (shell-command-to-string cmd))
18908 (setq mathml
18909 (when (file-readable-p tmp-out-file)
18910 (with-current-buffer (find-file-noselect tmp-out-file t)
18911 (goto-char (point-min))
18912 (when (re-search-forward
18913 (concat
18914 (regexp-quote
18915 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18916 "\\(.\\|\n\\)*"
18917 (regexp-quote "</math>")) nil t)
18918 (prog1 (match-string 0) (kill-buffer))))))
18919 (cond
18920 (mathml
18921 (setq mathml
18922 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18923 (when mathml-file
18924 (write-region mathml nil mathml-file))
18925 (when (org-called-interactively-p 'any)
18926 (message mathml)))
18927 ((message "LaTeX to MathML conversion failed")
18928 (message shell-command-output)))
18929 (delete-file tmp-in-file)
18930 (when (file-exists-p tmp-out-file)
18931 (delete-file tmp-out-file))
18932 mathml))
18934 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18935 prefix &optional dir)
18936 "Use `org-create-math-formula' but check local cache first."
18937 (let* ((absprefix (expand-file-name prefix dir))
18938 (print-length nil) (print-level nil)
18939 (formula-id (concat
18940 "formula-"
18941 (sha1
18942 (prin1-to-string
18943 (list latex-frag
18944 org-latex-to-mathml-convert-command)))))
18945 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18946 (formula-cache-dir (file-name-directory formula-cache)))
18948 (unless (file-directory-p formula-cache-dir)
18949 (make-directory formula-cache-dir t))
18951 (unless (file-exists-p formula-cache)
18952 (org-create-math-formula latex-frag formula-cache))
18954 (if (file-exists-p formula-cache)
18955 ;; Successful conversion. Return the link to MathML file.
18956 (org-add-props
18957 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18958 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18959 'org-latex-src-embed-type (if latex-frag-type
18960 'paragraph 'character)))
18961 ;; Failed conversion. Return the LaTeX fragment verbatim
18962 latex-frag)))
18964 (defun org-create-formula-image (string tofile options buffer &optional type)
18965 "Create an image from LaTeX source using dvipng or convert.
18966 This function calls either `org-create-formula-image-with-dvipng'
18967 or `org-create-formula-image-with-imagemagick' depending on the
18968 value of `org-latex-create-formula-image-program' or on the value
18969 of the optional TYPE variable.
18971 Note: ultimately these two function should be combined as they
18972 share a good deal of logic."
18973 (org-check-external-command
18974 "latex" "needed to convert LaTeX fragments to images")
18975 (funcall
18976 (case (or type org-latex-create-formula-image-program)
18977 ('dvipng
18978 (org-check-external-command
18979 "dvipng" "needed to convert LaTeX fragments to images")
18980 'org-create-formula-image-with-dvipng)
18981 ('imagemagick
18982 (org-check-external-command
18983 "convert" "you need to install imagemagick")
18984 'org-create-formula-image-with-imagemagick)
18985 (t (error
18986 "Invalid value of `org-latex-create-formula-image-program'")))
18987 string tofile options buffer))
18989 (declare-function org-export-get-backend "ox" (name))
18990 (declare-function org-export--get-global-options "ox" (&optional backend))
18991 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18992 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18993 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18994 (defun org-create-formula--latex-header ()
18995 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18996 (let ((info (org-combine-plists (org-export--get-global-options
18997 (org-export-get-backend 'latex))
18998 (org-export--get-inbuffer-options
18999 (org-export-get-backend 'latex)))))
19000 (org-latex-guess-babel-language
19001 (org-latex-guess-inputenc
19002 (org-splice-latex-header
19003 org-format-latex-header
19004 org-latex-default-packages-alist
19005 org-latex-packages-alist t
19006 (plist-get info :latex-header)))
19007 info)))
19009 (defun org--get-display-dpi ()
19010 "Get the DPI of the display.
19012 Assumes that the display has the same pixel width in the
19013 horizontal and vertical directions."
19014 (if (display-graphic-p)
19015 (round (/ (display-pixel-height)
19016 (/ (display-mm-height) 25.4)))
19017 (error "Attempt to calculate the dpi of a non-graphic display.")))
19019 ;; This function borrows from Ganesh Swami's latex2png.el
19020 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
19021 "This calls dvipng."
19022 (require 'ox-latex)
19023 (let* ((tmpdir (if (featurep 'xemacs)
19024 (temp-directory)
19025 temporary-file-directory))
19026 (texfilebase (make-temp-name
19027 (expand-file-name "orgtex" tmpdir)))
19028 (texfile (concat texfilebase ".tex"))
19029 (dvifile (concat texfilebase ".dvi"))
19030 (pngfile (concat texfilebase ".png"))
19031 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19032 ;; This assumes that the display has the same pixel width in
19033 ;; the horizontal and vertical directions
19034 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19035 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19036 "Black"))
19037 (bg (or (plist-get options (if buffer :background :html-background))
19038 "Transparent")))
19039 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
19040 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
19041 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
19042 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
19043 (let ((latex-header (org-create-formula--latex-header)))
19044 (with-temp-file texfile
19045 (insert latex-header)
19046 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19047 (let ((dir default-directory))
19048 (ignore-errors
19049 (cd tmpdir)
19050 (call-process "latex" nil nil nil texfile))
19051 (cd dir))
19052 (if (not (file-exists-p dvifile))
19053 (progn (message "Failed to create dvi file from %s" texfile) nil)
19054 (ignore-errors
19055 (if (featurep 'xemacs)
19056 (call-process "dvipng" nil nil nil
19057 "-fg" fg "-bg" bg
19058 "-T" "tight"
19059 "-o" pngfile
19060 dvifile)
19061 (call-process "dvipng" nil nil nil
19062 "-fg" fg "-bg" bg
19063 "-D" dpi
19064 ;;"-x" scale "-y" scale
19065 "-T" "tight"
19066 "-o" pngfile
19067 dvifile)))
19068 (if (not (file-exists-p pngfile))
19069 (if org-format-latex-signal-error
19070 (error "Failed to create png file from %s" texfile)
19071 (message "Failed to create png file from %s" texfile)
19072 nil)
19073 ;; Use the requested file name and clean up
19074 (copy-file pngfile tofile 'replace)
19075 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
19076 (if (file-exists-p (concat texfilebase e))
19077 (delete-file (concat texfilebase e))))
19078 pngfile))))
19080 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
19081 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
19082 "This calls convert, which is included into imagemagick."
19083 (require 'ox-latex)
19084 (let* ((tmpdir (if (featurep 'xemacs)
19085 (temp-directory)
19086 temporary-file-directory))
19087 (texfilebase (make-temp-name
19088 (expand-file-name "orgtex" tmpdir)))
19089 (texfile (concat texfilebase ".tex"))
19090 (pdffile (concat texfilebase ".pdf"))
19091 (pngfile (concat texfilebase ".png"))
19092 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19093 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19094 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19095 "black"))
19096 (bg (or (plist-get options (if buffer :background :html-background))
19097 "white")))
19098 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
19099 (setq fg (org-latex-color-format fg)))
19100 (if (eq bg 'default) (setq bg (org-latex-color :background))
19101 (setq bg (org-latex-color-format
19102 (if (string= bg "Transparent") "white" bg))))
19103 (let ((latex-header (org-create-formula--latex-header)))
19104 (with-temp-file texfile
19105 (insert latex-header)
19106 (insert "\n\\begin{document}\n"
19107 "\\definecolor{fg}{rgb}{" fg "}\n"
19108 "\\definecolor{bg}{rgb}{" bg "}\n"
19109 "\n\\pagecolor{bg}\n"
19110 "\n{\\color{fg}\n"
19111 string
19112 "\n}\n"
19113 "\n\\end{document}\n")))
19114 (org-latex-compile texfile t)
19115 (if (not (file-exists-p pdffile))
19116 (progn (message "Failed to create pdf file from %s" texfile) nil)
19117 (ignore-errors
19118 (if (featurep 'xemacs)
19119 (call-process "convert" nil nil nil
19120 "-density" "96"
19121 "-trim"
19122 "-antialias"
19123 pdffile
19124 "-quality" "100"
19125 ;; "-sharpen" "0x1.0"
19126 pngfile)
19127 (call-process "convert" nil nil nil
19128 "-density" dpi
19129 "-trim"
19130 "-antialias"
19131 pdffile
19132 "-quality" "100"
19133 ;; "-sharpen" "0x1.0"
19134 pngfile)))
19135 (if (not (file-exists-p pngfile))
19136 (if org-format-latex-signal-error
19137 (error "Failed to create png file from %s" texfile)
19138 (message "Failed to create png file from %s" texfile)
19139 nil)
19140 ;; Use the requested file name and clean up
19141 (copy-file pngfile tofile 'replace)
19142 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
19143 (if (file-exists-p (concat texfilebase e))
19144 (delete-file (concat texfilebase e))))
19145 pngfile))))
19147 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19148 "Fill a LaTeX header template TPL.
19149 In the template, the following place holders will be recognized:
19151 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19152 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19153 [PACKAGES] \\usepackage statements for PKG
19154 [NO-PACKAGES] do not include PKG
19155 [EXTRA] the string EXTRA
19156 [NO-EXTRA] do not include EXTRA
19158 For backward compatibility, if both the positive and the negative place
19159 holder is missing, the positive one (without the \"NO-\") will be
19160 assumed to be present at the end of the template.
19161 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19162 EXTRA is a string.
19163 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19164 (let (rpl (end ""))
19165 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19166 (setq rpl (if (or (match-end 1) (not def-pkg))
19167 "" (org-latex-packages-to-string def-pkg snippets-p t))
19168 tpl (replace-match rpl t t tpl))
19169 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19171 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19172 (setq rpl (if (or (match-end 1) (not pkg))
19173 "" (org-latex-packages-to-string pkg snippets-p t))
19174 tpl (replace-match rpl t t tpl))
19175 (if pkg (setq end
19176 (concat end "\n"
19177 (org-latex-packages-to-string pkg snippets-p)))))
19179 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19180 (setq rpl (if (or (match-end 1) (not extra))
19181 "" (concat extra "\n"))
19182 tpl (replace-match rpl t t tpl))
19183 (if (and extra (string-match "\\S-" extra))
19184 (setq end (concat end "\n" extra))))
19186 (if (string-match "\\S-" end)
19187 (concat tpl "\n" end)
19188 tpl)))
19190 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19191 "Turn an alist of packages into a string with the \\usepackage macros."
19192 (setq pkg (mapconcat (lambda(p)
19193 (cond
19194 ((stringp p) p)
19195 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19196 (format "%% Package %s omitted" (cadr p)))
19197 ((equal "" (car p))
19198 (format "\\usepackage{%s}" (cadr p)))
19200 (format "\\usepackage[%s]{%s}"
19201 (car p) (cadr p)))))
19203 "\n"))
19204 (if newline (concat pkg "\n") pkg))
19206 (defun org-dvipng-color (attr)
19207 "Return a RGB color specification for dvipng."
19208 (apply 'format "rgb %s %s %s"
19209 (mapcar 'org-normalize-color
19210 (if (featurep 'xemacs)
19211 (color-rgb-components
19212 (face-property 'default
19213 (cond ((eq attr :foreground) 'foreground)
19214 ((eq attr :background) 'background))))
19215 (color-values (face-attribute 'default attr nil))))))
19217 (defun org-dvipng-color-format (color-name)
19218 "Convert COLOR-NAME to a RGB color value for dvipng."
19219 (apply 'format "rgb %s %s %s"
19220 (mapcar 'org-normalize-color
19221 (color-values color-name))))
19223 (defun org-latex-color (attr)
19224 "Return a RGB color for the LaTeX color package."
19225 (apply 'format "%s,%s,%s"
19226 (mapcar 'org-normalize-color
19227 (if (featurep 'xemacs)
19228 (color-rgb-components
19229 (face-property 'default
19230 (cond ((eq attr :foreground) 'foreground)
19231 ((eq attr :background) 'background))))
19232 (color-values (face-attribute 'default attr nil))))))
19234 (defun org-latex-color-format (color-name)
19235 "Convert COLOR-NAME to a RGB color value."
19236 (apply 'format "%s,%s,%s"
19237 (mapcar 'org-normalize-color
19238 (color-values color-name))))
19240 (defun org-normalize-color (value)
19241 "Return string to be used as color value for an RGB component."
19242 (format "%g" (/ value 65535.0)))
19246 ;; Image display
19248 (defvar org-inline-image-overlays nil)
19249 (make-variable-buffer-local 'org-inline-image-overlays)
19251 (defun org-toggle-inline-images (&optional include-linked)
19252 "Toggle the display of inline images.
19253 INCLUDE-LINKED is passed to `org-display-inline-images'."
19254 (interactive "P")
19255 (if org-inline-image-overlays
19256 (progn
19257 (org-remove-inline-images)
19258 (when (org-called-interactively-p 'interactive)
19259 (message "Inline image display turned off")))
19260 (org-display-inline-images include-linked)
19261 (when (org-called-interactively-p 'interactive)
19262 (message (if org-inline-image-overlays
19263 (format "%d images displayed inline"
19264 (length org-inline-image-overlays))
19265 "No images to display inline")))))
19267 (defun org-redisplay-inline-images ()
19268 "Refresh the display of inline images."
19269 (interactive)
19270 (if (not org-inline-image-overlays)
19271 (org-toggle-inline-images)
19272 (org-toggle-inline-images)
19273 (org-toggle-inline-images)))
19275 (defun org-display-inline-images (&optional include-linked refresh beg end)
19276 "Display inline images.
19278 An inline image is a link which follows either of these
19279 conventions:
19281 1. Its path is a file with an extension matching return value
19282 from `image-file-name-regexp' and it has no contents.
19284 2. Its description consists in a single link of the previous
19285 type.
19287 When optional argument INCLUDE-LINKED is non-nil, also links with
19288 a text description part will be inlined. This can be nice for
19289 a quick look at those images, but it does not reflect what
19290 exported files will look like.
19292 When optional argument REFRESH is non-nil, refresh existing
19293 images between BEG and END. This will create new image displays
19294 only if necessary. BEG and END default to the buffer
19295 boundaries."
19296 (interactive "P")
19297 (when (display-graphic-p)
19298 (unless refresh
19299 (org-remove-inline-images)
19300 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19301 (org-with-wide-buffer
19302 (goto-char (or beg (point-min)))
19303 (let ((case-fold-search t)
19304 (file-extension-re (org-image-file-name-regexp)))
19305 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19306 (let ((link (save-match-data (org-element-context))))
19307 ;; Check if we're at an inline image.
19308 (when (and (equal (org-element-property :type link) "file")
19309 (or include-linked
19310 (not (org-element-property :contents-begin link)))
19311 (let ((parent (org-element-property :parent link)))
19312 (or (not (eq (org-element-type parent) 'link))
19313 (not (cdr (org-element-contents parent)))))
19314 (org-string-match-p file-extension-re
19315 (org-element-property :path link)))
19316 (let ((file (expand-file-name (org-element-property :path link))))
19317 (when (file-exists-p file)
19318 (let ((width
19319 ;; Apply `org-image-actual-width' specifications.
19320 (cond
19321 ((not (image-type-available-p 'imagemagick)) nil)
19322 ((eq org-image-actual-width t) nil)
19323 ((listp org-image-actual-width)
19325 ;; First try to find a width among
19326 ;; attributes associated to the paragraph
19327 ;; containing link.
19328 (let ((paragraph
19329 (let ((e link))
19330 (while (and (setq e (org-element-property
19331 :parent e))
19332 (not (eq (org-element-type e)
19333 'paragraph))))
19334 e)))
19335 (when paragraph
19336 (save-excursion
19337 (goto-char (org-element-property :begin paragraph))
19338 (when
19339 (re-search-forward
19340 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19341 (org-element-property
19342 :post-affiliated paragraph)
19344 (string-to-number (match-string 1))))))
19345 ;; Otherwise, fall-back to provided number.
19346 (car org-image-actual-width)))
19347 ((numberp org-image-actual-width)
19348 org-image-actual-width)))
19349 (old (get-char-property-and-overlay
19350 (org-element-property :begin link)
19351 'org-image-overlay)))
19352 (if (and (car-safe old) refresh)
19353 (image-refresh (overlay-get (cdr old) 'display))
19354 (let ((image (create-image file
19355 (and width 'imagemagick)
19357 :width width)))
19358 (when image
19359 (let* ((link
19360 ;; If inline image is the description
19361 ;; of another link, be sure to
19362 ;; consider the latter as the one to
19363 ;; apply the overlay on.
19364 (let ((parent
19365 (org-element-property :parent link)))
19366 (if (eq (org-element-type parent) 'link)
19367 parent
19368 link)))
19369 (ov (make-overlay
19370 (org-element-property :begin link)
19371 (progn
19372 (goto-char
19373 (org-element-property :end link))
19374 (skip-chars-backward " \t")
19375 (point)))))
19376 (overlay-put ov 'display image)
19377 (overlay-put ov 'face 'default)
19378 (overlay-put ov 'org-image-overlay t)
19379 (overlay-put
19380 ov 'modification-hooks
19381 (list 'org-display-inline-remove-overlay))
19382 (push ov org-inline-image-overlays)))))))))))))))
19384 (define-obsolete-function-alias
19385 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19387 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19388 "Remove inline-display overlay if a corresponding region is modified."
19389 (let ((inhibit-modification-hooks t))
19390 (when (and ov after)
19391 (delete ov org-inline-image-overlays)
19392 (delete-overlay ov))))
19394 (defun org-remove-inline-images ()
19395 "Remove inline display of images."
19396 (interactive)
19397 (mapc 'delete-overlay org-inline-image-overlays)
19398 (setq org-inline-image-overlays nil))
19400 ;;;; Key bindings
19402 ;; Outline functions from `outline-mode-prefix-map'
19403 ;; that can be remapped in Org:
19404 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19405 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19406 (define-key org-mode-map [remap outline-forward-same-level]
19407 'org-forward-heading-same-level)
19408 (define-key org-mode-map [remap outline-backward-same-level]
19409 'org-backward-heading-same-level)
19410 (define-key org-mode-map [remap show-branches]
19411 'org-kill-note-or-show-branches)
19412 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19413 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19414 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19415 (define-key org-mode-map [remap outline-next-visible-heading]
19416 'org-next-visible-heading)
19417 (define-key org-mode-map [remap outline-previous-visible-heading]
19418 'org-previous-visible-heading)
19420 ;; Outline functions from `outline-mode-prefix-map' that can not
19421 ;; be remapped in Org:
19423 ;; - the column "key binding" shows whether the Outline function is still
19424 ;; available in Org mode on the same key that it has been bound to in
19425 ;; Outline mode:
19426 ;; - "overridden": key used for a different functionality in Org mode
19427 ;; - else: key still bound to the same Outline function in Org mode
19429 ;; | Outline function | key binding | Org replacement |
19430 ;; |------------------------------------+-------------+--------------------------|
19431 ;; | `outline-next-visible-heading' | `C-c C-n' | better: skip inlinetasks |
19432 ;; | `outline-previous-visible-heading' | `C-c C-p' | better: skip inlinetasks |
19433 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19434 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19435 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19436 ;; | `show-entry' | overridden | no replacement |
19437 ;; | `show-children' | `C-c C-i' | visibility cycling |
19438 ;; | `show-branches' | `C-c C-k' | still same function |
19439 ;; | `show-subtree' | overridden | visibility cycling |
19440 ;; | `show-all' | overridden | no replacement |
19441 ;; | `hide-subtree' | overridden | visibility cycling |
19442 ;; | `hide-body' | overridden | no replacement |
19443 ;; | `hide-entry' | overridden | visibility cycling |
19444 ;; | `hide-leaves' | overridden | no replacement |
19445 ;; | `hide-sublevels' | overridden | no replacement |
19446 ;; | `hide-other' | overridden | no replacement |
19448 ;; Make `C-c C-x' a prefix key
19449 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19451 ;; TAB key with modifiers
19452 (org-defkey org-mode-map "\C-i" 'org-cycle)
19453 (org-defkey org-mode-map [(tab)] 'org-cycle)
19454 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19455 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19456 ;; The following line is necessary under Suse GNU/Linux
19457 (unless (featurep 'xemacs)
19458 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19459 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19460 (define-key org-mode-map [backtab] 'org-shifttab)
19462 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19463 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19464 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19466 ;; Cursor keys with modifiers
19467 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19468 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19469 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19470 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19472 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19473 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19474 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19475 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19476 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19477 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19479 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19480 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19481 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19482 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19484 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19485 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19486 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19487 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19489 ;; Babel keys
19490 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19491 (mapc (lambda (pair)
19492 (define-key org-babel-map (car pair) (cdr pair)))
19493 org-babel-key-bindings)
19495 ;;; Extra keys for tty access.
19496 ;; We only set them when really needed because otherwise the
19497 ;; menus don't show the simple keys
19499 (when (or org-use-extra-keys
19500 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19501 (not window-system))
19502 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19503 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19504 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19505 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19506 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19507 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19508 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19509 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19510 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19511 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19512 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19513 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19514 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19515 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19516 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19517 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19518 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19519 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19520 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19521 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19522 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19523 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19524 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19525 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19526 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19527 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19528 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19529 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19531 ;; All the other keys
19533 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19534 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19535 (if (boundp 'narrow-map)
19536 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19537 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19538 (if (boundp 'narrow-map)
19539 (org-defkey narrow-map "b" 'org-narrow-to-block)
19540 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19541 (if (boundp 'narrow-map)
19542 (org-defkey narrow-map "e" 'org-narrow-to-element)
19543 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19544 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19545 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19546 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19547 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19548 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19549 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19550 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19551 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19552 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19553 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19554 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19555 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19556 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19557 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19558 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19559 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19560 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19561 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19562 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19563 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19564 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19565 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19566 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19567 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19568 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19569 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19570 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19571 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19572 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19573 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19574 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19575 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19576 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19577 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19578 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19579 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19580 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19581 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19582 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19583 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19584 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19585 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19586 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19587 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19588 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19589 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19590 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19591 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19592 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19593 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19594 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19595 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19596 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19597 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19598 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19599 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19600 (org-defkey org-mode-map "\C-c^" 'org-sort)
19601 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19602 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19603 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19604 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19605 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19606 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19607 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19608 (org-defkey org-mode-map "\C-m" 'org-return)
19609 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19610 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19611 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19612 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19613 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19614 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19615 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19616 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19617 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19618 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19619 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19620 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19621 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19622 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19623 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19624 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19625 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19626 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19627 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19628 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19629 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19630 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19631 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19632 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19633 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19635 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19636 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19637 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19639 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19640 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19641 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19642 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19643 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19644 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19645 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19646 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19647 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19648 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19649 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19650 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19651 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19652 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19653 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19654 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19655 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19656 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19657 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19658 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19659 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19660 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19661 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19663 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19664 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19665 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19666 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19667 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19669 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19671 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19673 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19674 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19676 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19679 (when (featurep 'xemacs)
19680 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19683 (defconst org-speed-commands-default
19685 ("Outline Navigation")
19686 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19687 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19688 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19689 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19690 ("F" . org-next-block)
19691 ("B" . org-previous-block)
19692 ("u" . (org-speed-move-safe 'outline-up-heading))
19693 ("j" . org-goto)
19694 ("g" . (org-refile t))
19695 ("Outline Visibility")
19696 ("c" . org-cycle)
19697 ("C" . org-shifttab)
19698 (" " . org-display-outline-path)
19699 ("s" . org-narrow-to-subtree)
19700 ("=" . org-columns)
19701 ("Outline Structure Editing")
19702 ("U" . org-metaup)
19703 ("D" . org-metadown)
19704 ("r" . org-metaright)
19705 ("l" . org-metaleft)
19706 ("R" . org-shiftmetaright)
19707 ("L" . org-shiftmetaleft)
19708 ("i" . (progn (forward-char 1) (call-interactively
19709 'org-insert-heading-respect-content)))
19710 ("^" . org-sort)
19711 ("w" . org-refile)
19712 ("a" . org-archive-subtree-default-with-confirmation)
19713 ("@" . org-mark-subtree)
19714 ("#" . org-toggle-comment)
19715 ("Clock Commands")
19716 ("I" . org-clock-in)
19717 ("O" . org-clock-out)
19718 ("Meta Data Editing")
19719 ("t" . org-todo)
19720 ("," . (org-priority))
19721 ("0" . (org-priority ?\ ))
19722 ("1" . (org-priority ?A))
19723 ("2" . (org-priority ?B))
19724 ("3" . (org-priority ?C))
19725 (":" . org-set-tags-command)
19726 ("e" . org-set-effort)
19727 ("E" . org-inc-effort)
19728 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19729 (org-entry-put (point) "APPT_WARNTIME" m)))
19730 ("Agenda Views etc")
19731 ("v" . org-agenda)
19732 ("/" . org-sparse-tree)
19733 ("Misc")
19734 ("o" . org-open-at-point)
19735 ("?" . org-speed-command-help)
19736 ("<" . (org-agenda-set-restriction-lock 'subtree))
19737 (">" . (org-agenda-remove-restriction-lock))
19739 "The default speed commands.")
19741 (defun org-print-speed-command (e)
19742 (if (> (length (car e)) 1)
19743 (progn
19744 (princ "\n")
19745 (princ (car e))
19746 (princ "\n")
19747 (princ (make-string (length (car e)) ?-))
19748 (princ "\n"))
19749 (princ (car e))
19750 (princ " ")
19751 (if (symbolp (cdr e))
19752 (princ (symbol-name (cdr e)))
19753 (prin1 (cdr e)))
19754 (princ "\n")))
19756 (defun org-speed-command-help ()
19757 "Show the available speed commands."
19758 (interactive)
19759 (if (not org-use-speed-commands)
19760 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19761 (with-output-to-temp-buffer "*Help*"
19762 (princ "User-defined Speed commands\n===========================\n")
19763 (mapc 'org-print-speed-command org-speed-commands-user)
19764 (princ "\n")
19765 (princ "Built-in Speed commands\n=======================\n")
19766 (mapc 'org-print-speed-command org-speed-commands-default))
19767 (with-current-buffer "*Help*"
19768 (setq truncate-lines t))))
19770 (defun org-speed-move-safe (cmd)
19771 "Execute CMD, but make sure that the cursor always ends up in a headline.
19772 If not, return to the original position and throw an error."
19773 (interactive)
19774 (let ((pos (point)))
19775 (call-interactively cmd)
19776 (unless (and (bolp) (org-at-heading-p))
19777 (goto-char pos)
19778 (error "Boundary reached while executing %s" cmd))))
19780 (defvar org-self-insert-command-undo-counter 0)
19782 (defvar org-table-auto-blank-field) ; defined in org-table.el
19783 (defvar org-speed-command nil)
19785 (define-obsolete-function-alias
19786 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19788 (defun org-speed-command-activate (keys)
19789 "Hook for activating single-letter speed commands.
19790 `org-speed-commands-default' specifies a minimal command set.
19791 Use `org-speed-commands-user' for further customization."
19792 (when (or (and (bolp) (looking-at org-outline-regexp))
19793 (and (functionp org-use-speed-commands)
19794 (funcall org-use-speed-commands)))
19795 (cdr (assoc keys (append org-speed-commands-user
19796 org-speed-commands-default)))))
19798 (define-obsolete-function-alias
19799 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19801 (defun org-babel-speed-command-activate (keys)
19802 "Hook for activating single-letter code block commands."
19803 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19804 (cdr (assoc keys org-babel-key-bindings))))
19806 (defcustom org-speed-command-hook
19807 '(org-speed-command-default-hook org-babel-speed-command-hook)
19808 "Hook for activating speed commands at strategic locations.
19809 Hook functions are called in sequence until a valid handler is
19810 found.
19812 Each hook takes a single argument, a user-pressed command key
19813 which is also a `self-insert-command' from the global map.
19815 Within the hook, examine the cursor position and the command key
19816 and return nil or a valid handler as appropriate. Handler could
19817 be one of an interactive command, a function, or a form.
19819 Set `org-use-speed-commands' to non-nil value to enable this
19820 hook. The default setting is `org-speed-command-activate'."
19821 :group 'org-structure
19822 :version "24.1"
19823 :type 'hook)
19825 (defun org-self-insert-command (N)
19826 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19827 If the cursor is in a table looking at whitespace, the whitespace is
19828 overwritten, and the table is not marked as requiring realignment."
19829 (interactive "p")
19830 (org-check-before-invisible-edit 'insert)
19831 (cond
19832 ((and org-use-speed-commands
19833 (let ((kv (this-command-keys-vector)))
19834 (setq org-speed-command
19835 (run-hook-with-args-until-success
19836 'org-speed-command-hook
19837 (make-string 1 (aref kv (1- (length kv))))))))
19838 (cond
19839 ((commandp org-speed-command)
19840 (setq this-command org-speed-command)
19841 (call-interactively org-speed-command))
19842 ((functionp org-speed-command)
19843 (funcall org-speed-command))
19844 ((and org-speed-command (listp org-speed-command))
19845 (eval org-speed-command))
19846 (t (let (org-use-speed-commands)
19847 (call-interactively 'org-self-insert-command)))))
19848 ((and
19849 (org-table-p)
19850 (progn
19851 ;; check if we blank the field, and if that triggers align
19852 (and (featurep 'org-table) org-table-auto-blank-field
19853 (memq last-command
19854 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19855 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19856 ;; got extra space, this field does not determine column width
19857 (let (org-table-may-need-update) (org-table-blank-field))
19858 ;; no extra space, this field may determine column width
19859 (org-table-blank-field)))
19861 (eq N 1)
19862 (looking-at "[^|\n]* |"))
19863 (let (org-table-may-need-update)
19864 (goto-char (1- (match-end 0)))
19865 (backward-delete-char 1)
19866 (goto-char (match-beginning 0))
19867 (self-insert-command N)))
19869 (setq org-table-may-need-update t)
19870 (self-insert-command N)
19871 (org-fix-tags-on-the-fly)
19872 (if org-self-insert-cluster-for-undo
19873 (if (not (eq last-command 'org-self-insert-command))
19874 (setq org-self-insert-command-undo-counter 1)
19875 (if (>= org-self-insert-command-undo-counter 20)
19876 (setq org-self-insert-command-undo-counter 1)
19877 (and (> org-self-insert-command-undo-counter 0)
19878 buffer-undo-list (listp buffer-undo-list)
19879 (not (cadr buffer-undo-list)) ; remove nil entry
19880 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19881 (setq org-self-insert-command-undo-counter
19882 (1+ org-self-insert-command-undo-counter))))))))
19884 (defun org-check-before-invisible-edit (kind)
19885 "Check is editing if kind KIND would be dangerous with invisible text around.
19886 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19887 ;; First, try to get out of here as quickly as possible, to reduce overhead
19888 (if (and org-catch-invisible-edits
19889 (or (not (boundp 'visible-mode)) (not visible-mode))
19890 (or (get-char-property (point) 'invisible)
19891 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19892 ;; OK, we need to take a closer look
19893 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19894 (invisible-before-point (if (bobp) nil (get-char-property
19895 (1- (point)) 'invisible)))
19896 (border-and-ok-direction
19898 ;; Check if we are acting predictably before invisible text
19899 (and invisible-at-point (not invisible-before-point)
19900 (memq kind '(insert delete-backward)))
19901 ;; Check if we are acting predictably after invisible text
19902 ;; This works not well, and I have turned it off. It seems
19903 ;; better to always show and stop after invisible text.
19904 ;; (and (not invisible-at-point) invisible-before-point
19905 ;; (memq kind '(insert delete)))
19907 (when (or (memq invisible-at-point '(outline org-hide-block t))
19908 (memq invisible-before-point '(outline org-hide-block t)))
19909 (if (eq org-catch-invisible-edits 'error)
19910 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19911 (if (and org-custom-properties-overlays
19912 (y-or-n-p "Display invisible properties in this buffer? "))
19913 (org-toggle-custom-properties-visibility)
19914 ;; Make the area visible
19915 (save-excursion
19916 (if invisible-before-point
19917 (goto-char (previous-single-char-property-change
19918 (point) 'invisible)))
19919 (show-subtree))
19920 (cond
19921 ((eq org-catch-invisible-edits 'show)
19922 ;; That's it, we do the edit after showing
19923 (message
19924 "Unfolding invisible region around point before editing")
19925 (sit-for 1))
19926 ((and (eq org-catch-invisible-edits 'smart)
19927 border-and-ok-direction)
19928 (message "Unfolding invisible region around point before editing"))
19930 ;; Don't do the edit, make the user repeat it in full visibility
19931 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19933 (defun org-fix-tags-on-the-fly ()
19934 (when (and (equal (char-after (point-at-bol)) ?*)
19935 (org-at-heading-p))
19936 (org-align-tags-here org-tags-column)))
19938 (defun org-delete-backward-char (N)
19939 "Like `delete-backward-char', insert whitespace at field end in tables.
19940 When deleting backwards, in tables this function will insert whitespace in
19941 front of the next \"|\" separator, to keep the table aligned. The table will
19942 still be marked for re-alignment if the field did fill the entire column,
19943 because, in this case the deletion might narrow the column."
19944 (interactive "p")
19945 (save-match-data
19946 (org-check-before-invisible-edit 'delete-backward)
19947 (if (and (org-table-p)
19948 (eq N 1)
19949 (string-match "|" (buffer-substring (point-at-bol) (point)))
19950 (looking-at ".*?|"))
19951 (let ((pos (point))
19952 (noalign (looking-at "[^|\n\r]* |"))
19953 (c org-table-may-need-update))
19954 (backward-delete-char N)
19955 (if (not overwrite-mode)
19956 (progn
19957 (skip-chars-forward "^|")
19958 (insert " ")
19959 (goto-char (1- pos))))
19960 ;; noalign: if there were two spaces at the end, this field
19961 ;; does not determine the width of the column.
19962 (if noalign (setq org-table-may-need-update c)))
19963 (backward-delete-char N)
19964 (org-fix-tags-on-the-fly))))
19966 (defun org-delete-char (N)
19967 "Like `delete-char', but insert whitespace at field end in tables.
19968 When deleting characters, in tables this function will insert whitespace in
19969 front of the next \"|\" separator, to keep the table aligned. The table will
19970 still be marked for re-alignment if the field did fill the entire column,
19971 because, in this case the deletion might narrow the column."
19972 (interactive "p")
19973 (save-match-data
19974 (org-check-before-invisible-edit 'delete)
19975 (if (and (org-table-p)
19976 (not (bolp))
19977 (not (= (char-after) ?|))
19978 (eq N 1))
19979 (if (looking-at ".*?|")
19980 (let ((pos (point))
19981 (noalign (looking-at "[^|\n\r]* |"))
19982 (c org-table-may-need-update))
19983 (replace-match
19984 (concat (substring (match-string 0) 1 -1) " |") nil t)
19985 (goto-char pos)
19986 ;; noalign: if there were two spaces at the end, this field
19987 ;; does not determine the width of the column.
19988 (if noalign (setq org-table-may-need-update c)))
19989 (delete-char N))
19990 (delete-char N)
19991 (org-fix-tags-on-the-fly))))
19993 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19994 (put 'org-self-insert-command 'delete-selection
19995 (lambda ()
19996 (not (run-hook-with-args-until-success
19997 'self-insert-uses-region-functions))))
19998 (put 'orgtbl-self-insert-command 'delete-selection
19999 (lambda ()
20000 (not (run-hook-with-args-until-success
20001 'self-insert-uses-region-functions))))
20002 (put 'org-delete-char 'delete-selection 'supersede)
20003 (put 'org-delete-backward-char 'delete-selection 'supersede)
20004 (put 'org-yank 'delete-selection 'yank)
20006 ;; Make `flyspell-mode' delay after some commands
20007 (put 'org-self-insert-command 'flyspell-delayed t)
20008 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20009 (put 'org-delete-char 'flyspell-delayed t)
20010 (put 'org-delete-backward-char 'flyspell-delayed t)
20012 ;; Make pabbrev-mode expand after org-mode commands
20013 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20014 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20016 (defun org-remap (map &rest commands)
20017 "In MAP, remap the functions given in COMMANDS.
20018 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20019 (let (new old)
20020 (while commands
20021 (setq old (pop commands) new (pop commands))
20022 (if (fboundp 'command-remapping)
20023 (org-defkey map (vector 'remap old) new)
20024 (substitute-key-definition old new map global-map)))))
20026 (defun org-transpose-words ()
20027 "Transpose words for Org.
20028 This uses the `org-mode-transpose-word-syntax-table' syntax
20029 table, which interprets characters in `org-emphasis-alist' as
20030 word constituents."
20031 (interactive)
20032 (with-syntax-table org-mode-transpose-word-syntax-table
20033 (call-interactively 'transpose-words)))
20034 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20036 (when (eq org-enable-table-editor 'optimized)
20037 ;; If the user wants maximum table support, we need to hijack
20038 ;; some standard editing functions
20039 (org-remap org-mode-map
20040 'self-insert-command 'org-self-insert-command
20041 'delete-char 'org-delete-char
20042 'delete-backward-char 'org-delete-backward-char)
20043 (org-defkey org-mode-map "|" 'org-force-self-insert))
20045 (defvar org-ctrl-c-ctrl-c-hook nil
20046 "Hook for functions attaching themselves to `C-c C-c'.
20048 This can be used to add additional functionality to the C-c C-c
20049 key which executes context-dependent commands. This hook is run
20050 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20051 run after the last test.
20053 Each function will be called with no arguments. The function
20054 must check if the context is appropriate for it to act. If yes,
20055 it should do its thing and then return a non-nil value. If the
20056 context is wrong, just do nothing and return nil.")
20058 (defvar org-ctrl-c-ctrl-c-final-hook nil
20059 "Hook for functions attaching themselves to `C-c C-c'.
20061 This can be used to add additional functionality to the C-c C-c
20062 key which executes context-dependent commands. This hook is run
20063 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20064 before the first test.
20066 Each function will be called with no arguments. The function
20067 must check if the context is appropriate for it to act. If yes,
20068 it should do its thing and then return a non-nil value. If the
20069 context is wrong, just do nothing and return nil.")
20071 (defvar org-tab-first-hook nil
20072 "Hook for functions to attach themselves to TAB.
20073 See `org-ctrl-c-ctrl-c-hook' for more information.
20074 This hook runs as the first action when TAB is pressed, even before
20075 `org-cycle' messes around with the `outline-regexp' to cater for
20076 inline tasks and plain list item folding.
20077 If any function in this hook returns t, any other actions that
20078 would have been caused by TAB (such as table field motion or visibility
20079 cycling) will not occur.")
20081 (defvar org-tab-after-check-for-table-hook nil
20082 "Hook for functions to attach themselves to TAB.
20083 See `org-ctrl-c-ctrl-c-hook' for more information.
20084 This hook runs after it has been established that the cursor is not in a
20085 table, but before checking if the cursor is in a headline or if global cycling
20086 should be done.
20087 If any function in this hook returns t, not other actions like visibility
20088 cycling will be done.")
20090 (defvar org-tab-after-check-for-cycling-hook nil
20091 "Hook for functions to attach themselves to TAB.
20092 See `org-ctrl-c-ctrl-c-hook' for more information.
20093 This hook runs after it has been established that not table field motion and
20094 not visibility should be done because of current context. This is probably
20095 the place where a package like yasnippets can hook in.")
20097 (defvar org-tab-before-tab-emulation-hook nil
20098 "Hook for functions to attach themselves to TAB.
20099 See `org-ctrl-c-ctrl-c-hook' for more information.
20100 This hook runs after every other options for TAB have been exhausted, but
20101 before indentation and \t insertion takes place.")
20103 (defvar org-metaleft-hook nil
20104 "Hook for functions attaching themselves to `M-left'.
20105 See `org-ctrl-c-ctrl-c-hook' for more information.")
20106 (defvar org-metaright-hook nil
20107 "Hook for functions attaching themselves to `M-right'.
20108 See `org-ctrl-c-ctrl-c-hook' for more information.")
20109 (defvar org-metaup-hook nil
20110 "Hook for functions attaching themselves to `M-up'.
20111 See `org-ctrl-c-ctrl-c-hook' for more information.")
20112 (defvar org-metadown-hook nil
20113 "Hook for functions attaching themselves to `M-down'.
20114 See `org-ctrl-c-ctrl-c-hook' for more information.")
20115 (defvar org-shiftmetaleft-hook nil
20116 "Hook for functions attaching themselves to `M-S-left'.
20117 See `org-ctrl-c-ctrl-c-hook' for more information.")
20118 (defvar org-shiftmetaright-hook nil
20119 "Hook for functions attaching themselves to `M-S-right'.
20120 See `org-ctrl-c-ctrl-c-hook' for more information.")
20121 (defvar org-shiftmetaup-hook nil
20122 "Hook for functions attaching themselves to `M-S-up'.
20123 See `org-ctrl-c-ctrl-c-hook' for more information.")
20124 (defvar org-shiftmetadown-hook nil
20125 "Hook for functions attaching themselves to `M-S-down'.
20126 See `org-ctrl-c-ctrl-c-hook' for more information.")
20127 (defvar org-metareturn-hook nil
20128 "Hook for functions attaching themselves to `M-RET'.
20129 See `org-ctrl-c-ctrl-c-hook' for more information.")
20130 (defvar org-shiftup-hook nil
20131 "Hook for functions attaching themselves to `S-up'.
20132 See `org-ctrl-c-ctrl-c-hook' for more information.")
20133 (defvar org-shiftup-final-hook nil
20134 "Hook for functions attaching themselves to `S-up'.
20135 This one runs after all other options except shift-select have been excluded.
20136 See `org-ctrl-c-ctrl-c-hook' for more information.")
20137 (defvar org-shiftdown-hook nil
20138 "Hook for functions attaching themselves to `S-down'.
20139 See `org-ctrl-c-ctrl-c-hook' for more information.")
20140 (defvar org-shiftdown-final-hook nil
20141 "Hook for functions attaching themselves to `S-down'.
20142 This one runs after all other options except shift-select have been excluded.
20143 See `org-ctrl-c-ctrl-c-hook' for more information.")
20144 (defvar org-shiftleft-hook nil
20145 "Hook for functions attaching themselves to `S-left'.
20146 See `org-ctrl-c-ctrl-c-hook' for more information.")
20147 (defvar org-shiftleft-final-hook nil
20148 "Hook for functions attaching themselves to `S-left'.
20149 This one runs after all other options except shift-select have been excluded.
20150 See `org-ctrl-c-ctrl-c-hook' for more information.")
20151 (defvar org-shiftright-hook nil
20152 "Hook for functions attaching themselves to `S-right'.
20153 See `org-ctrl-c-ctrl-c-hook' for more information.")
20154 (defvar org-shiftright-final-hook nil
20155 "Hook for functions attaching themselves to `S-right'.
20156 This one runs after all other options except shift-select have been excluded.
20157 See `org-ctrl-c-ctrl-c-hook' for more information.")
20159 (defun org-modifier-cursor-error ()
20160 "Throw an error, a modified cursor command was applied in wrong context."
20161 (user-error "This command is active in special context like tables, headlines or items"))
20163 (defun org-shiftselect-error ()
20164 "Throw an error because Shift-Cursor command was applied in wrong context."
20165 (if (and (boundp 'shift-select-mode) shift-select-mode)
20166 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20167 (user-error "This command works only in special context like headlines or timestamps")))
20169 (defun org-call-for-shift-select (cmd)
20170 (let ((this-command-keys-shift-translated t))
20171 (call-interactively cmd)))
20173 (defun org-shifttab (&optional arg)
20174 "Global visibility cycling or move to previous table field.
20175 Call `org-table-previous-field' within a table.
20176 When ARG is nil, cycle globally through visibility states.
20177 When ARG is a numeric prefix, show contents of this level."
20178 (interactive "P")
20179 (cond
20180 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20181 ((integerp arg)
20182 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20183 (message "Content view to level: %d" arg)
20184 (org-content (prefix-numeric-value arg2))
20185 (org-cycle-show-empty-lines t)
20186 (setq org-cycle-global-status 'overview)))
20187 (t (call-interactively 'org-global-cycle))))
20189 (defun org-shiftmetaleft ()
20190 "Promote subtree or delete table column.
20191 Calls `org-promote-subtree', `org-outdent-item-tree', or
20192 `org-table-delete-column', depending on context. See the
20193 individual commands for more information."
20194 (interactive)
20195 (cond
20196 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20197 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20198 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20199 ((if (not (org-region-active-p)) (org-at-item-p)
20200 (save-excursion (goto-char (region-beginning))
20201 (org-at-item-p)))
20202 (call-interactively 'org-outdent-item-tree))
20203 (t (org-modifier-cursor-error))))
20205 (defun org-shiftmetaright ()
20206 "Demote subtree or insert table column.
20207 Calls `org-demote-subtree', `org-indent-item-tree', or
20208 `org-table-insert-column', depending on context. See the
20209 individual commands for more information."
20210 (interactive)
20211 (cond
20212 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20213 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20214 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20215 ((if (not (org-region-active-p)) (org-at-item-p)
20216 (save-excursion (goto-char (region-beginning))
20217 (org-at-item-p)))
20218 (call-interactively 'org-indent-item-tree))
20219 (t (org-modifier-cursor-error))))
20221 (defun org-shiftmetaup (&optional arg)
20222 "Drag the line at point up.
20223 In a table, kill the current row.
20224 On a clock timestamp, update the value of the timestamp like `S-<up>'
20225 but also adjust the previous clocked item in the clock history.
20226 Everywhere else, drag the line at point up."
20227 (interactive "P")
20228 (cond
20229 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20230 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20231 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20232 (call-interactively 'org-timestamp-up)))
20233 (t (call-interactively 'org-drag-line-backward))))
20235 (defun org-shiftmetadown (&optional arg)
20236 "Drag the line at point down.
20237 In a table, insert an empty row at the current line.
20238 On a clock timestamp, update the value of the timestamp like `S-<down>'
20239 but also adjust the previous clocked item in the clock history.
20240 Everywhere else, drag the line at point down."
20241 (interactive "P")
20242 (cond
20243 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20244 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20245 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20246 (call-interactively 'org-timestamp-down)))
20247 (t (call-interactively 'org-drag-line-forward))))
20249 (defsubst org-hidden-tree-error ()
20250 (user-error
20251 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20253 (defun org-metaleft (&optional arg)
20254 "Promote heading or move table column to left.
20255 Calls `org-do-promote' or `org-table-move-column', depending on context.
20256 With no specific context, calls the Emacs default `backward-word'.
20257 See the individual commands for more information."
20258 (interactive "P")
20259 (cond
20260 ((run-hook-with-args-until-success 'org-metaleft-hook))
20261 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20262 ((org-with-limited-levels
20263 (or (org-at-heading-p)
20264 (and (org-region-active-p)
20265 (save-excursion
20266 (goto-char (region-beginning))
20267 (org-at-heading-p)))))
20268 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20269 (call-interactively 'org-do-promote))
20270 ;; At an inline task.
20271 ((org-at-heading-p)
20272 (call-interactively 'org-inlinetask-promote))
20273 ((or (org-at-item-p)
20274 (and (org-region-active-p)
20275 (save-excursion
20276 (goto-char (region-beginning))
20277 (org-at-item-p))))
20278 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20279 (call-interactively 'org-outdent-item))
20280 (t (call-interactively 'backward-word))))
20282 (defun org-metaright (&optional arg)
20283 "Demote a subtree, a list item or move table column to right.
20284 In front of a drawer or a block keyword, indent it correctly.
20285 With no specific context, calls the Emacs default `forward-word'.
20286 See the individual commands for more information."
20287 (interactive "P")
20288 (cond
20289 ((run-hook-with-args-until-success 'org-metaright-hook))
20290 ((org-at-table-p) (call-interactively 'org-table-move-column))
20291 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20292 ((org-at-block-p) (call-interactively 'org-indent-block))
20293 ((org-with-limited-levels
20294 (or (org-at-heading-p)
20295 (and (org-region-active-p)
20296 (save-excursion
20297 (goto-char (region-beginning))
20298 (org-at-heading-p)))))
20299 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20300 (call-interactively 'org-do-demote))
20301 ;; At an inline task.
20302 ((org-at-heading-p)
20303 (call-interactively 'org-inlinetask-demote))
20304 ((or (org-at-item-p)
20305 (and (org-region-active-p)
20306 (save-excursion
20307 (goto-char (region-beginning))
20308 (org-at-item-p))))
20309 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20310 (call-interactively 'org-indent-item))
20311 (t (call-interactively 'forward-word))))
20313 (defun org-check-for-hidden (what)
20314 "Check if there are hidden headlines/items in the current visual line.
20315 WHAT can be either `headlines' or `items'. If the current line is
20316 an outline or item heading and it has a folded subtree below it,
20317 this function returns t, nil otherwise."
20318 (let ((re (cond
20319 ((eq what 'headlines) org-outline-regexp-bol)
20320 ((eq what 'items) (org-item-beginning-re))
20321 (t (error "This should not happen"))))
20322 beg end)
20323 (save-excursion
20324 (catch 'exit
20325 (unless (org-region-active-p)
20326 (setq beg (point-at-bol))
20327 (beginning-of-line 2)
20328 (while (and (not (eobp)) ;; this is like `next-line'
20329 (get-char-property (1- (point)) 'invisible))
20330 (beginning-of-line 2))
20331 (setq end (point))
20332 (goto-char beg)
20333 (goto-char (point-at-eol))
20334 (setq end (max end (point)))
20335 (while (re-search-forward re end t)
20336 (if (get-char-property (match-beginning 0) 'invisible)
20337 (throw 'exit t))))
20338 nil))))
20340 (defun org-metaup (&optional arg)
20341 "Move subtree up or move table row up.
20342 Calls `org-move-subtree-up' or `org-table-move-row' or
20343 `org-move-item-up', depending on context. See the individual commands
20344 for more information."
20345 (interactive "P")
20346 (cond
20347 ((run-hook-with-args-until-success 'org-metaup-hook))
20348 ((org-region-active-p)
20349 (let* ((a (min (region-beginning) (region-end)))
20350 (b (1- (max (region-beginning) (region-end))))
20351 (c (save-excursion (goto-char a)
20352 (move-beginning-of-line 0)))
20353 (d (save-excursion (goto-char a)
20354 (move-end-of-line 0) (point))))
20355 (transpose-regions a b c d)
20356 (goto-char c)))
20357 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20358 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20359 ((org-at-item-p) (call-interactively 'org-move-item-up))
20360 (t (org-drag-element-backward))))
20362 (defun org-metadown (&optional arg)
20363 "Move subtree down or move table row down.
20364 Calls `org-move-subtree-down' or `org-table-move-row' or
20365 `org-move-item-down', depending on context. See the individual
20366 commands for more information."
20367 (interactive "P")
20368 (cond
20369 ((run-hook-with-args-until-success 'org-metadown-hook))
20370 ((org-region-active-p)
20371 (let* ((a (min (region-beginning) (region-end)))
20372 (b (max (region-beginning) (region-end)))
20373 (c (save-excursion (goto-char b)
20374 (move-beginning-of-line 1)))
20375 (d (save-excursion (goto-char b)
20376 (move-end-of-line 1) (1+ (point)))))
20377 (transpose-regions a b c d)
20378 (goto-char d)))
20379 ((org-at-table-p) (call-interactively 'org-table-move-row))
20380 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20381 ((org-at-item-p) (call-interactively 'org-move-item-down))
20382 (t (org-drag-element-forward))))
20384 (defun org-shiftup (&optional arg)
20385 "Increase item in timestamp or increase priority of current headline.
20386 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20387 depending on context. See the individual commands for more information."
20388 (interactive "P")
20389 (cond
20390 ((run-hook-with-args-until-success 'org-shiftup-hook))
20391 ((and org-support-shift-select (org-region-active-p))
20392 (org-call-for-shift-select 'previous-line))
20393 ((org-at-timestamp-p t)
20394 (call-interactively (if org-edit-timestamp-down-means-later
20395 'org-timestamp-down 'org-timestamp-up)))
20396 ((and (not (eq org-support-shift-select 'always))
20397 org-enable-priority-commands
20398 (org-at-heading-p))
20399 (call-interactively 'org-priority-up))
20400 ((and (not org-support-shift-select) (org-at-item-p))
20401 (call-interactively 'org-previous-item))
20402 ((org-clocktable-try-shift 'up arg))
20403 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20404 (org-support-shift-select
20405 (org-call-for-shift-select 'previous-line))
20406 (t (org-shiftselect-error))))
20408 (defun org-shiftdown (&optional arg)
20409 "Decrease item in timestamp or decrease priority of current headline.
20410 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20411 depending on context. See the individual commands for more information."
20412 (interactive "P")
20413 (cond
20414 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20415 ((and org-support-shift-select (org-region-active-p))
20416 (org-call-for-shift-select 'next-line))
20417 ((org-at-timestamp-p t)
20418 (call-interactively (if org-edit-timestamp-down-means-later
20419 'org-timestamp-up 'org-timestamp-down)))
20420 ((and (not (eq org-support-shift-select 'always))
20421 org-enable-priority-commands
20422 (org-at-heading-p))
20423 (call-interactively 'org-priority-down))
20424 ((and (not org-support-shift-select) (org-at-item-p))
20425 (call-interactively 'org-next-item))
20426 ((org-clocktable-try-shift 'down arg))
20427 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20428 (org-support-shift-select
20429 (org-call-for-shift-select 'next-line))
20430 (t (org-shiftselect-error))))
20432 (defun org-shiftright (&optional arg)
20433 "Cycle the thing at point or in the current line, depending on context.
20434 Depending on context, this does one of the following:
20436 - switch a timestamp at point one day into the future
20437 - on a headline, switch to the next TODO keyword.
20438 - on an item, switch entire list to the next bullet type
20439 - on a property line, switch to the next allowed value
20440 - on a clocktable definition line, move time block into the future"
20441 (interactive "P")
20442 (cond
20443 ((run-hook-with-args-until-success 'org-shiftright-hook))
20444 ((and org-support-shift-select (org-region-active-p))
20445 (org-call-for-shift-select 'forward-char))
20446 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20447 ((and (not (eq org-support-shift-select 'always))
20448 (org-at-heading-p))
20449 (let ((org-inhibit-logging
20450 (not org-treat-S-cursor-todo-selection-as-state-change))
20451 (org-inhibit-blocking
20452 (not org-treat-S-cursor-todo-selection-as-state-change)))
20453 (org-call-with-arg 'org-todo 'right)))
20454 ((or (and org-support-shift-select
20455 (not (eq org-support-shift-select 'always))
20456 (org-at-item-bullet-p))
20457 (and (not org-support-shift-select) (org-at-item-p)))
20458 (org-call-with-arg 'org-cycle-list-bullet nil))
20459 ((and (not (eq org-support-shift-select 'always))
20460 (org-at-property-p))
20461 (call-interactively 'org-property-next-allowed-value))
20462 ((org-clocktable-try-shift 'right arg))
20463 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20464 (org-support-shift-select
20465 (org-call-for-shift-select 'forward-char))
20466 (t (org-shiftselect-error))))
20468 (defun org-shiftleft (&optional arg)
20469 "Cycle the thing at point or in the current line, depending on context.
20470 Depending on context, this does one of the following:
20472 - switch a timestamp at point one day into the past
20473 - on a headline, switch to the previous TODO keyword.
20474 - on an item, switch entire list to the previous bullet type
20475 - on a property line, switch to the previous allowed value
20476 - on a clocktable definition line, move time block into the past"
20477 (interactive "P")
20478 (cond
20479 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20480 ((and org-support-shift-select (org-region-active-p))
20481 (org-call-for-shift-select 'backward-char))
20482 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20483 ((and (not (eq org-support-shift-select 'always))
20484 (org-at-heading-p))
20485 (let ((org-inhibit-logging
20486 (not org-treat-S-cursor-todo-selection-as-state-change))
20487 (org-inhibit-blocking
20488 (not org-treat-S-cursor-todo-selection-as-state-change)))
20489 (org-call-with-arg 'org-todo 'left)))
20490 ((or (and org-support-shift-select
20491 (not (eq org-support-shift-select 'always))
20492 (org-at-item-bullet-p))
20493 (and (not org-support-shift-select) (org-at-item-p)))
20494 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20495 ((and (not (eq org-support-shift-select 'always))
20496 (org-at-property-p))
20497 (call-interactively 'org-property-previous-allowed-value))
20498 ((org-clocktable-try-shift 'left arg))
20499 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20500 (org-support-shift-select
20501 (org-call-for-shift-select 'backward-char))
20502 (t (org-shiftselect-error))))
20504 (defun org-shiftcontrolright ()
20505 "Switch to next TODO set."
20506 (interactive)
20507 (cond
20508 ((and org-support-shift-select (org-region-active-p))
20509 (org-call-for-shift-select 'forward-word))
20510 ((and (not (eq org-support-shift-select 'always))
20511 (org-at-heading-p))
20512 (org-call-with-arg 'org-todo 'nextset))
20513 (org-support-shift-select
20514 (org-call-for-shift-select 'forward-word))
20515 (t (org-shiftselect-error))))
20517 (defun org-shiftcontrolleft ()
20518 "Switch to previous TODO set."
20519 (interactive)
20520 (cond
20521 ((and org-support-shift-select (org-region-active-p))
20522 (org-call-for-shift-select 'backward-word))
20523 ((and (not (eq org-support-shift-select 'always))
20524 (org-at-heading-p))
20525 (org-call-with-arg 'org-todo 'previousset))
20526 (org-support-shift-select
20527 (org-call-for-shift-select 'backward-word))
20528 (t (org-shiftselect-error))))
20530 (defun org-shiftcontrolup (&optional n)
20531 "Change timestamps synchronously up in CLOCK log lines.
20532 Optional argument N tells to change by that many units."
20533 (interactive "P")
20534 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20535 (let (org-support-shift-select)
20536 (org-clock-timestamps-up n))
20537 (user-error "Not at a clock log")))
20539 (defun org-shiftcontroldown (&optional n)
20540 "Change timestamps synchronously down in CLOCK log lines.
20541 Optional argument N tells to change by that many units."
20542 (interactive "P")
20543 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20544 (let (org-support-shift-select)
20545 (org-clock-timestamps-down n))
20546 (user-error "Not at a clock log")))
20548 (defun org-increase-number-at-point (&optional inc)
20549 "Increment the number at point.
20550 With an optional prefix numeric argument INC, increment using
20551 this numeric value."
20552 (interactive "p")
20553 (if (not (number-at-point))
20554 (user-error "Not on a number")
20555 (unless inc (setq inc 1))
20556 (let ((pos (point))
20557 (beg (skip-chars-backward "-+^/*0-9eE."))
20558 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20559 (setq nap (buffer-substring-no-properties
20560 (+ pos beg) (+ pos beg end)))
20561 (delete-region (+ pos beg) (+ pos beg end))
20562 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20563 (when (org-at-table-p)
20564 (org-table-align)
20565 (org-table-end-of-field 1))))
20567 (defun org-decrease-number-at-point (&optional inc)
20568 "Decrement the number at point.
20569 With an optional prefix numeric argument INC, decrement using
20570 this numeric value."
20571 (interactive "p")
20572 (org-increase-number-at-point (- inc)))
20574 (defun org-ctrl-c-ret ()
20575 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20576 (interactive)
20577 (cond
20578 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20579 (t (call-interactively 'org-insert-heading))))
20581 (defun org-find-visible ()
20582 (let ((s (point)))
20583 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20584 (get-char-property s 'invisible)))
20586 (defun org-find-invisible ()
20587 (let ((s (point)))
20588 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20589 (not (get-char-property s 'invisible))))
20592 (defun org-copy-visible (beg end)
20593 "Copy the visible parts of the region."
20594 (interactive "r")
20595 (let (snippets s)
20596 (save-excursion
20597 (save-restriction
20598 (narrow-to-region beg end)
20599 (setq s (goto-char (point-min)))
20600 (while (not (= (point) (point-max)))
20601 (goto-char (org-find-invisible))
20602 (push (buffer-substring s (point)) snippets)
20603 (setq s (goto-char (org-find-visible))))))
20604 (kill-new (apply 'concat (nreverse snippets)))))
20606 (defun org-copy-special ()
20607 "Copy region in table or copy current subtree.
20608 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20609 See the individual commands for more information."
20610 (interactive)
20611 (call-interactively
20612 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20614 (defun org-cut-special ()
20615 "Cut region in table or cut current subtree.
20616 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20617 See the individual commands for more information."
20618 (interactive)
20619 (call-interactively
20620 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20622 (defun org-paste-special (arg)
20623 "Paste rectangular region into table, or past subtree relative to level.
20624 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20625 See the individual commands for more information."
20626 (interactive "P")
20627 (if (org-at-table-p)
20628 (org-table-paste-rectangle)
20629 (org-paste-subtree arg)))
20631 (defsubst org-in-fixed-width-region-p ()
20632 "Is point in a fixed-width region?"
20633 (save-match-data
20634 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20636 (defun org-edit-special (&optional arg)
20637 "Call a special editor for the element at point.
20638 When at a table, call the formula editor with `org-table-edit-formulas'.
20639 When in a source code block, call `org-edit-src-code'.
20640 When in a fixed-width region, call `org-edit-fixed-width-region'.
20641 When in an export block, call `org-edit-export-block'.
20642 When at an #+INCLUDE keyword, visit the included file.
20643 On a link, call `ffap' to visit the link at point.
20644 Otherwise, return a user error."
20645 (interactive "P")
20646 (let ((element (org-element-at-point)))
20647 (assert (not buffer-read-only) nil
20648 "Buffer is read-only: %s" (buffer-name))
20649 (case (org-element-type element)
20650 (src-block
20651 (if (not arg) (org-edit-src-code)
20652 (let* ((info (org-babel-get-src-block-info))
20653 (lang (nth 0 info))
20654 (params (nth 2 info))
20655 (session (cdr (assq :session params))))
20656 (if (not session) (org-edit-src-code)
20657 ;; At a src-block with a session and function called with
20658 ;; an ARG: switch to the buffer related to the inferior
20659 ;; process.
20660 (switch-to-buffer
20661 (funcall (intern (concat "org-babel-prep-session:" lang))
20662 session params))))))
20663 (keyword
20664 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20665 (org-open-link-from-string
20666 (format "[[%s]]"
20667 (expand-file-name
20668 (let ((value (org-element-property :value element)))
20669 (cond ((not (org-string-nw-p value))
20670 (user-error "No file to edit"))
20671 ((string-match "\\`\"\\(.*?\\)\"" value)
20672 (match-string 1 value))
20673 ((string-match "\\`[^ \t\"]\\S-*" value)
20674 (match-string 0 value))
20675 (t (user-error "No valid file specified")))))))
20676 (user-error "No special environment to edit here")))
20677 (table
20678 (if (eq (org-element-property :type element) 'table.el)
20679 (org-edit-table.el)
20680 (call-interactively 'org-table-edit-formulas)))
20681 ;; Only Org tables contain `table-row' type elements.
20682 (table-row (call-interactively 'org-table-edit-formulas))
20683 ((example-block src-block) (org-edit-src-code))
20684 (export-block (org-edit-export-block))
20685 (fixed-width (org-edit-fixed-width-region))
20686 (otherwise
20687 ;; No notable element at point. Though, we may be at a link,
20688 ;; which is an object. Thus, scan deeper.
20689 (if (eq (org-element-type (org-element-context element)) 'link)
20690 (call-interactively 'ffap)
20691 (user-error "No special environment to edit here"))))))
20693 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20694 (defun org-ctrl-c-ctrl-c (&optional arg)
20695 "Set tags in headline, or update according to changed information at point.
20697 This command does many different things, depending on context:
20699 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20700 this is what we do.
20702 - If the cursor is on a statistics cookie, update it.
20704 - If the cursor is in a headline, prompt for tags and insert them
20705 into the current line, aligned to `org-tags-column'. When called
20706 with prefix arg, realign all tags in the current buffer.
20708 - If the cursor is in one of the special #+KEYWORD lines, this
20709 triggers scanning the buffer for these lines and updating the
20710 information.
20712 - If the cursor is inside a table, realign the table. This command
20713 works even if the automatic table editor has been turned off.
20715 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20716 the entire table.
20718 - If the cursor is at a footnote reference or definition, jump to
20719 the corresponding definition or references, respectively.
20721 - If the cursor is a the beginning of a dynamic block, update it.
20723 - If the current buffer is a capture buffer, close note and file it.
20725 - If the cursor is on a <<<target>>>, update radio targets and
20726 corresponding links in this buffer.
20728 - If the cursor is on a numbered item in a plain list, renumber the
20729 ordered list.
20731 - If the cursor is on a checkbox, toggle it.
20733 - If the cursor is on a code block, evaluate it. The variable
20734 `org-confirm-babel-evaluate' can be used to control prompting
20735 before code block evaluation, by default every code block
20736 evaluation requires confirmation. Code block evaluation can be
20737 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20738 (interactive "P")
20739 (cond
20740 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20741 org-occur-highlights)
20742 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20743 (org-remove-occur-highlights)
20744 (message "Temporary highlights/overlays removed from current buffer"))
20745 ((and (local-variable-p 'org-finish-function (current-buffer))
20746 (fboundp org-finish-function))
20747 (funcall org-finish-function))
20748 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20750 (let* ((context (org-element-context)) (type (org-element-type context)))
20751 ;; Test if point is within a blank line.
20752 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20753 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20754 (user-error "C-c C-c can do nothing useful at this location"))
20755 (case type
20756 ;; When at a link, act according to the parent instead.
20757 (link (setq context (org-element-property :parent context))
20758 (setq type (org-element-type context)))
20759 ;; Unsupported object types: refer to the first supported
20760 ;; element or object containing it.
20761 ((bold code entity export-snippet inline-babel-call inline-src-block
20762 italic latex-fragment line-break macro strike-through subscript
20763 superscript underline verbatim)
20764 (while (and (setq context (org-element-property :parent context))
20765 (not (memq (setq type (org-element-type context))
20766 '(radio-target paragraph verse-block
20767 table-cell)))))))
20768 ;; For convenience: at the first line of a paragraph on the
20769 ;; same line as an item, apply function on that item instead.
20770 (when (eq type 'paragraph)
20771 (let ((parent (org-element-property :parent context)))
20772 (when (and (eq (org-element-type parent) 'item)
20773 (= (point-at-bol) (org-element-property :begin parent)))
20774 (setq context parent type 'item))))
20775 ;; Act according to type of element or object at point.
20776 (case type
20777 (clock (org-clock-update-time-maybe))
20778 (dynamic-block
20779 (save-excursion
20780 (goto-char (org-element-property :post-affiliated context))
20781 (org-update-dblock)))
20782 (footnote-definition
20783 (goto-char (org-element-property :post-affiliated context))
20784 (call-interactively 'org-footnote-action))
20785 (footnote-reference (call-interactively 'org-footnote-action))
20786 ((headline inlinetask)
20787 (save-excursion (goto-char (org-element-property :begin context))
20788 (call-interactively 'org-set-tags)))
20789 (item
20790 ;; At an item: a double C-u set checkbox to "[-]"
20791 ;; unconditionally, whereas a single one will toggle its
20792 ;; presence. Without an universal argument, if the item
20793 ;; has a checkbox, toggle it. Otherwise repair the list.
20794 (let* ((box (org-element-property :checkbox context))
20795 (struct (org-element-property :structure context))
20796 (old-struct (copy-tree struct))
20797 (parents (org-list-parents-alist struct))
20798 (prevs (org-list-prevs-alist struct))
20799 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20800 (org-list-set-checkbox
20801 (org-element-property :begin context) struct
20802 (cond ((equal arg '(16)) "[-]")
20803 ((and (not box) (equal arg '(4))) "[ ]")
20804 ((or (not box) (equal arg '(4))) nil)
20805 ((eq box 'on) "[ ]")
20806 (t "[X]")))
20807 ;; Mimic `org-list-write-struct' but with grabbing
20808 ;; a return value from `org-list-struct-fix-box'.
20809 (org-list-struct-fix-ind struct parents 2)
20810 (org-list-struct-fix-item-end struct)
20811 (org-list-struct-fix-bul struct prevs)
20812 (org-list-struct-fix-ind struct parents)
20813 (let ((block-item
20814 (org-list-struct-fix-box struct parents prevs orderedp)))
20815 (if (and box (equal struct old-struct))
20816 (if (equal arg '(16))
20817 (message "Checkboxes already reset")
20818 (user-error "Cannot toggle this checkbox: %s"
20819 (if (eq box 'on)
20820 "all subitems checked"
20821 "unchecked subitems")))
20822 (org-list-struct-apply-struct struct old-struct)
20823 (org-update-checkbox-count-maybe))
20824 (when block-item
20825 (message "Checkboxes were removed due to empty box at line %d"
20826 (org-current-line block-item))))))
20827 (keyword
20828 (let ((org-inhibit-startup-visibility-stuff t)
20829 (org-startup-align-all-tables nil))
20830 (when (boundp 'org-table-coordinate-overlays)
20831 (mapc 'delete-overlay org-table-coordinate-overlays)
20832 (setq org-table-coordinate-overlays nil))
20833 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20834 (message "Local setup has been refreshed"))
20835 (plain-list
20836 ;; At a plain list, with a double C-u argument, set
20837 ;; checkboxes of each item to "[-]", whereas a single one
20838 ;; will toggle their presence according to the state of the
20839 ;; first item in the list. Without an argument, repair the
20840 ;; list.
20841 (let* ((begin (org-element-property :contents-begin context))
20842 (beginm (move-marker (make-marker) begin))
20843 (struct (org-element-property :structure context))
20844 (old-struct (copy-tree struct))
20845 (first-box (save-excursion
20846 (goto-char begin)
20847 (looking-at org-list-full-item-re)
20848 (match-string-no-properties 3)))
20849 (new-box (cond ((equal arg '(16)) "[-]")
20850 ((equal arg '(4)) (unless first-box "[ ]"))
20851 ((equal first-box "[X]") "[ ]")
20852 (t "[X]"))))
20853 (cond
20854 (arg
20855 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20856 (org-list-get-all-items
20857 begin struct (org-list-prevs-alist struct))))
20858 ((and first-box (eq (point) begin))
20859 ;; For convenience, when point is at bol on the first
20860 ;; item of the list and no argument is provided, simply
20861 ;; toggle checkbox of that item, if any.
20862 (org-list-set-checkbox begin struct new-box)))
20863 (org-list-write-struct
20864 struct (org-list-parents-alist struct) old-struct)
20865 (org-update-checkbox-count-maybe)
20866 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20867 ((property-drawer node-property)
20868 (call-interactively 'org-property-action))
20869 ((radio-target target)
20870 (call-interactively 'org-update-radio-target-regexp))
20871 (statistics-cookie
20872 (call-interactively 'org-update-statistics-cookies))
20873 ((table table-cell table-row)
20874 ;; At a table, recalculate every field and align it. Also
20875 ;; send the table if necessary. If the table has
20876 ;; a `table.el' type, just give up. At a table row or
20877 ;; cell, maybe recalculate line but always align table.
20878 (if (eq (org-element-property :type context) 'table.el)
20879 (message "Use C-c ' to edit table.el tables")
20880 (let ((org-enable-table-editor t))
20881 (if (or (eq type 'table)
20882 ;; Check if point is at a TBLFM line.
20883 (and (eq type 'table-row)
20884 (= (point) (org-element-property :end context))))
20885 (save-excursion
20886 (if (org-at-TBLFM-p)
20887 (progn (require 'org-table)
20888 (org-table-calc-current-TBLFM))
20889 (goto-char (org-element-property :contents-begin context))
20890 (org-call-with-arg 'org-table-recalculate (or arg t))
20891 (orgtbl-send-table 'maybe)))
20892 (org-table-maybe-eval-formula)
20893 (cond (arg (call-interactively 'org-table-recalculate))
20894 ((org-table-maybe-recalculate-line))
20895 (t (org-table-align)))))))
20896 (timestamp (org-timestamp-change 0 'day))
20897 (otherwise
20898 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20899 (user-error
20900 "C-c C-c can do nothing useful at this location")))))))))
20902 (defun org-mode-restart ()
20903 (interactive)
20904 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20905 (funcall major-mode)
20906 (hack-local-variables)
20907 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20908 (org-indent-mode -1)))
20909 (message "%s restarted" major-mode))
20911 (defun org-kill-note-or-show-branches ()
20912 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20913 (interactive)
20914 (if (not org-finish-function)
20915 (progn
20916 (hide-subtree)
20917 (call-interactively 'show-branches))
20918 (let ((org-note-abort t))
20919 (funcall org-finish-function))))
20921 (defun org-open-line (n)
20922 "Insert a new row in tables, call `open-line' elsewhere.
20923 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20924 (interactive "*p")
20925 (cond
20926 ((not org-special-ctrl-o)
20927 (open-line n))
20928 ((org-at-table-p)
20929 (org-table-insert-row))
20931 (open-line n))))
20933 (defun org-return (&optional indent)
20934 "Goto next table row or insert a newline.
20936 Calls `org-table-next-row' or `newline', depending on context.
20938 When optional INDENT argument is non-nil, call
20939 `newline-and-indent' instead of `newline'.
20941 When `org-return-follows-link' is non-nil and point is on
20942 a timestamp or a link, call `org-open-at-point'. However, it
20943 will not happen if point is in a table or on a \"dead\"
20944 object (e.g., within a comment). In these case, you need to use
20945 `org-open-at-point' directly."
20946 (interactive)
20947 (if (and (save-excursion
20948 (beginning-of-line)
20949 (looking-at org-todo-line-regexp))
20950 (match-beginning 3)
20951 (>= (point) (match-beginning 3)))
20952 ;; Point is on headline tags. Do not break them: add a newline
20953 ;; after the headline instead.
20954 (progn (org-show-entry)
20955 (end-of-line)
20956 (if indent (newline-and-indent) (newline)))
20957 (let* ((context (if org-return-follows-link (org-element-context)
20958 (org-element-at-point)))
20959 (type (org-element-type context)))
20960 (cond
20961 ;; In a table, call `org-table-next-row'.
20962 ((or (and (eq type 'table)
20963 (>= (point) (org-element-property :contents-begin context))
20964 (< (point) (org-element-property :contents-end context)))
20965 (org-element-lineage context '(table-row table-cell) t))
20966 (org-table-justify-field-maybe)
20967 (call-interactively #'org-table-next-row))
20968 ;; On a link or a timestamp but not on white spaces after it,
20969 ;; call `org-open-line' if `org-return-follows-link' allows it.
20970 ((and org-return-follows-link
20971 (memq type '(link timestamp))
20972 (< (point)
20973 (save-excursion (goto-char (org-element-property :end context))
20974 (skip-chars-backward " \t")
20975 (point))))
20976 (call-interactively #'org-open-at-point))
20977 ;; In a list, make sure indenting keeps trailing text within.
20978 ((and indent
20979 (not (eolp))
20980 (org-element-lineage context '(item plain-list) t))
20981 (let ((trailing-data
20982 (delete-and-extract-region (point) (line-end-position))))
20983 (newline-and-indent)
20984 (save-excursion (insert trailing-data))))
20985 (t (if indent (newline-and-indent) (newline)))))))
20987 (defun org-return-indent ()
20988 "Goto next table row or insert a newline and indent.
20989 Calls `org-table-next-row' or `newline-and-indent', depending on
20990 context. See the individual commands for more information."
20991 (interactive)
20992 (org-return t))
20994 (defun org-ctrl-c-star ()
20995 "Compute table, or change heading status of lines.
20996 Calls `org-table-recalculate' or `org-toggle-heading',
20997 depending on context."
20998 (interactive)
20999 (cond
21000 ((org-at-table-p)
21001 (call-interactively 'org-table-recalculate))
21003 ;; Convert all lines in region to list items
21004 (call-interactively 'org-toggle-heading))))
21006 (defun org-ctrl-c-minus ()
21007 "Insert separator line in table or modify bullet status of line.
21008 Also turns a plain line or a region of lines into list items.
21009 Calls `org-table-insert-hline', `org-toggle-item', or
21010 `org-cycle-list-bullet', depending on context."
21011 (interactive)
21012 (cond
21013 ((org-at-table-p)
21014 (call-interactively 'org-table-insert-hline))
21015 ((org-region-active-p)
21016 (call-interactively 'org-toggle-item))
21017 ((org-in-item-p)
21018 (call-interactively 'org-cycle-list-bullet))
21020 (call-interactively 'org-toggle-item))))
21022 (defun org-toggle-item (arg)
21023 "Convert headings or normal lines to items, items to normal lines.
21024 If there is no active region, only the current line is considered.
21026 If the first non blank line in the region is a headline, convert
21027 all headlines to items, shifting text accordingly.
21029 If it is an item, convert all items to normal lines.
21031 If it is normal text, change region into a list of items.
21032 With a prefix argument ARG, change the region in a single item."
21033 (interactive "P")
21034 (let ((shift-text
21035 (function
21036 ;; Shift text in current section to IND, from point to END.
21037 ;; The function leaves point to END line.
21038 (lambda (ind end)
21039 (let ((min-i 1000) (end (copy-marker end)))
21040 ;; First determine the minimum indentation (MIN-I) of
21041 ;; the text.
21042 (save-excursion
21043 (catch 'exit
21044 (while (< (point) end)
21045 (let ((i (org-get-indentation)))
21046 (cond
21047 ;; Skip blank lines and inline tasks.
21048 ((looking-at "^[ \t]*$"))
21049 ((looking-at org-outline-regexp-bol))
21050 ;; We can't find less than 0 indentation.
21051 ((zerop i) (throw 'exit (setq min-i 0)))
21052 ((< i min-i) (setq min-i i))))
21053 (forward-line))))
21054 ;; Then indent each line so that a line indented to
21055 ;; MIN-I becomes indented to IND. Ignore blank lines
21056 ;; and inline tasks in the process.
21057 (let ((delta (- ind min-i)))
21058 (while (< (point) end)
21059 (unless (or (looking-at "^[ \t]*$")
21060 (looking-at org-outline-regexp-bol))
21061 (org-indent-line-to (+ (org-get-indentation) delta)))
21062 (forward-line)))))))
21063 (skip-blanks
21064 (function
21065 ;; Return beginning of first non-blank line, starting from
21066 ;; line at POS.
21067 (lambda (pos)
21068 (save-excursion
21069 (goto-char pos)
21070 (skip-chars-forward " \r\t\n")
21071 (point-at-bol)))))
21072 beg end)
21073 ;; Determine boundaries of changes.
21074 (if (org-region-active-p)
21075 (setq beg (funcall skip-blanks (region-beginning))
21076 end (copy-marker (region-end)))
21077 (setq beg (funcall skip-blanks (point-at-bol))
21078 end (copy-marker (point-at-eol))))
21079 ;; Depending on the starting line, choose an action on the text
21080 ;; between BEG and END.
21081 (org-with-limited-levels
21082 (save-excursion
21083 (goto-char beg)
21084 (cond
21085 ;; Case 1. Start at an item: de-itemize. Note that it only
21086 ;; happens when a region is active: `org-ctrl-c-minus'
21087 ;; would call `org-cycle-list-bullet' otherwise.
21088 ((org-at-item-p)
21089 (while (< (point) end)
21090 (when (org-at-item-p)
21091 (skip-chars-forward " \t")
21092 (delete-region (point) (match-end 0)))
21093 (forward-line)))
21094 ;; Case 2. Start at an heading: convert to items.
21095 ((org-at-heading-p)
21096 (let* ((bul (org-list-bullet-string "-"))
21097 (bul-len (length bul))
21098 (done (org-entry-is-done-p))
21099 (todo (org-entry-is-todo-p))
21100 ;; Indentation of the first heading. It should be
21101 ;; relative to the indentation of its parent, if any.
21102 (start-ind (save-excursion
21103 (cond
21104 ((not org-adapt-indentation) 0)
21105 ((not (outline-previous-heading)) 0)
21106 (t (length (match-string 0))))))
21107 ;; Level of first heading. Further headings will be
21108 ;; compared to it to determine hierarchy in the list.
21109 (ref-level (org-reduced-level (org-outline-level))))
21110 (when (or done todo) (org-todo ""))
21111 (while (< (point) end)
21112 (let* ((level (org-reduced-level (org-outline-level)))
21113 (delta (max 0 (- level ref-level))))
21114 ;; If current headline is less indented than the first
21115 ;; one, set it as reference, in order to preserve
21116 ;; subtrees.
21117 (when (< level ref-level) (setq ref-level level))
21118 (replace-match bul t t)
21119 (org-indent-line-to (+ start-ind (* delta bul-len)))
21120 (when (or done todo)
21121 (let* ((struct (org-list-struct))
21122 (old (copy-tree struct)))
21123 (org-list-set-checkbox (line-beginning-position)
21124 struct
21125 (if done "[X]" "[ ]"))
21126 (org-list-write-struct struct
21127 (org-list-parents-alist struct)
21128 old)))
21129 ;; Ensure all text down to END (or SECTION-END) belongs
21130 ;; to the newly created item.
21131 (let ((section-end (save-excursion
21132 (or (outline-next-heading) (point)))))
21133 (forward-line)
21134 (funcall shift-text
21135 (+ start-ind (* (1+ delta) bul-len))
21136 (min end section-end)))))))
21137 ;; Case 3. Normal line with ARG: make the first line of region
21138 ;; an item, and shift indentation of others lines to
21139 ;; set them as item's body.
21140 (arg (let* ((bul (org-list-bullet-string "-"))
21141 (bul-len (length bul))
21142 (ref-ind (org-get-indentation)))
21143 (skip-chars-forward " \t")
21144 (insert bul)
21145 (forward-line)
21146 (while (< (point) end)
21147 ;; Ensure that lines less indented than first one
21148 ;; still get included in item body.
21149 (funcall shift-text
21150 (+ ref-ind bul-len)
21151 (min end (save-excursion (or (outline-next-heading)
21152 (point)))))
21153 (forward-line))))
21154 ;; Case 4. Normal line without ARG: turn each non-item line
21155 ;; into an item.
21157 (while (< (point) end)
21158 (unless (or (org-at-heading-p) (org-at-item-p))
21159 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21160 (replace-match
21161 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21162 (forward-line))))))))
21164 (defun org-toggle-heading (&optional nstars)
21165 "Convert headings to normal text, or items or text to headings.
21166 If there is no active region, only convert the current line.
21168 With a \\[universal-argument] prefix, convert the whole list at
21169 point into heading.
21171 In a region:
21173 - If the first non blank line is a headline, remove the stars
21174 from all headlines in the region.
21176 - If it is a normal line, turn each and every normal line (i.e.,
21177 not an heading or an item) in the region into headings. If you
21178 want to convert only the first line of this region, use one
21179 universal prefix argument.
21181 - If it is a plain list item, turn all plain list items into headings.
21183 When converting a line into a heading, the number of stars is chosen
21184 such that the lines become children of the current entry. However,
21185 when a numeric prefix argument is given, its value determines the
21186 number of stars to add."
21187 (interactive "P")
21188 (let ((skip-blanks
21189 (function
21190 ;; Return beginning of first non-blank line, starting from
21191 ;; line at POS.
21192 (lambda (pos)
21193 (save-excursion
21194 (goto-char pos)
21195 (while (org-at-comment-p) (forward-line))
21196 (skip-chars-forward " \r\t\n")
21197 (point-at-bol)))))
21198 beg end toggled)
21199 ;; Determine boundaries of changes. If a universal prefix has
21200 ;; been given, put the list in a region. If region ends at a bol,
21201 ;; do not consider the last line to be in the region.
21203 (when (and current-prefix-arg (org-at-item-p))
21204 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
21205 (org-mark-element))
21207 (if (org-region-active-p)
21208 (setq beg (funcall skip-blanks (region-beginning))
21209 end (copy-marker (save-excursion
21210 (goto-char (region-end))
21211 (if (bolp) (point) (point-at-eol)))))
21212 (setq beg (funcall skip-blanks (point-at-bol))
21213 end (copy-marker (point-at-eol))))
21214 ;; Ensure inline tasks don't count as headings.
21215 (org-with-limited-levels
21216 (save-excursion
21217 (goto-char beg)
21218 (cond
21219 ;; Case 1. Started at an heading: de-star headings.
21220 ((org-at-heading-p)
21221 (while (< (point) end)
21222 (when (org-at-heading-p t)
21223 (looking-at org-outline-regexp) (replace-match "")
21224 (setq toggled t))
21225 (forward-line)))
21226 ;; Case 2. Started at an item: change items into headlines.
21227 ;; One star will be added by `org-list-to-subtree'.
21228 ((org-at-item-p)
21229 (let* ((stars (make-string
21230 ;; subtract the star that will be added again by
21231 ;; `org-list-to-subtree'
21232 (if (numberp nstars) (1- nstars)
21233 (or (org-current-level) 0))
21234 ?*))
21235 (add-stars
21236 (cond (nstars "") ; stars from prefix only
21237 ((equal stars "") "") ; before first heading
21238 (org-odd-levels-only "*") ; inside heading, odd
21239 (t "")))) ; inside heading, oddeven
21240 (while (< (point) end)
21241 (when (org-at-item-p)
21242 ;; Pay attention to cases when region ends before list.
21243 (let* ((struct (org-list-struct))
21244 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
21245 (save-restriction
21246 (narrow-to-region (point) list-end)
21247 (insert
21248 (org-list-to-subtree
21249 (org-list-parse-list t)
21250 '(:istart (concat stars add-stars (funcall get-stars depth))
21251 :icount (concat stars add-stars (funcall get-stars depth)))))))
21252 (setq toggled t))
21253 (forward-line))))
21254 ;; Case 3. Started at normal text: make every line an heading,
21255 ;; skipping headlines and items.
21256 (t (let* ((stars
21257 (make-string
21258 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21259 (add-stars
21260 (cond (nstars "") ; stars from prefix only
21261 ((equal stars "") "*") ; before first heading
21262 (org-odd-levels-only "**") ; inside heading, odd
21263 (t "*"))) ; inside heading, oddeven
21264 (rpl (concat stars add-stars " "))
21265 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
21266 (while (< (point) (if (equal nstars '(4)) lend end))
21267 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21268 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21269 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21270 (forward-line)))))))
21271 (unless toggled (message "Cannot toggle heading from here"))))
21273 (defun org-meta-return (&optional arg)
21274 "Insert a new heading or wrap a region in a table.
21275 Calls `org-insert-heading' or `org-table-wrap-region', depending
21276 on context. See the individual commands for more information."
21277 (interactive "P")
21278 (org-check-before-invisible-edit 'insert)
21279 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21280 (let* ((element (org-element-at-point))
21281 (type (org-element-type element)))
21282 (when (eq type 'table-row)
21283 (setq element (org-element-property :parent element))
21284 (setq type 'table))
21285 (if (and (eq type 'table)
21286 (eq (org-element-property :type element) 'org)
21287 (>= (point) (org-element-property :contents-begin element))
21288 (< (point) (org-element-property :contents-end element)))
21289 (call-interactively 'org-table-wrap-region)
21290 (call-interactively 'org-insert-heading)))))
21292 ;;; Menu entries
21294 (defsubst org-in-subtree-not-table-p ()
21295 "Are we in a subtree and not in a table?"
21296 (and (not (org-before-first-heading-p))
21297 (not (org-at-table-p))))
21299 ;; Define the Org-mode menus
21300 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21301 '("Tbl"
21302 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21303 ["Next Field" org-cycle (org-at-table-p)]
21304 ["Previous Field" org-shifttab (org-at-table-p)]
21305 ["Next Row" org-return (org-at-table-p)]
21306 "--"
21307 ["Blank Field" org-table-blank-field (org-at-table-p)]
21308 ["Edit Field" org-table-edit-field (org-at-table-p)]
21309 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21310 "--"
21311 ("Column"
21312 ["Move Column Left" org-metaleft (org-at-table-p)]
21313 ["Move Column Right" org-metaright (org-at-table-p)]
21314 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21315 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21316 ("Row"
21317 ["Move Row Up" org-metaup (org-at-table-p)]
21318 ["Move Row Down" org-metadown (org-at-table-p)]
21319 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21320 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21321 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21322 "--"
21323 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21324 ("Rectangle"
21325 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21326 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21327 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21328 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21329 "--"
21330 ("Calculate"
21331 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21332 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21333 ["Edit Formulas" org-edit-special (org-at-table-p)]
21334 "--"
21335 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21336 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21337 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21338 "--"
21339 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21340 "--"
21341 ["Sum Column/Rectangle" org-table-sum
21342 (or (org-at-table-p) (org-region-active-p))]
21343 ["Which Column?" org-table-current-column (org-at-table-p)])
21344 ["Debug Formulas"
21345 org-table-toggle-formula-debugger
21346 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21347 ["Show Col/Row Numbers"
21348 org-table-toggle-coordinate-overlays
21349 :style toggle
21350 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21351 "--"
21352 ["Create" org-table-create (and (not (org-at-table-p))
21353 org-enable-table-editor)]
21354 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21355 ["Import from File" org-table-import (not (org-at-table-p))]
21356 ["Export to File" org-table-export (org-at-table-p)]
21357 "--"
21358 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21359 "--"
21360 ("Plot"
21361 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21362 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21364 (easy-menu-define org-org-menu org-mode-map "Org menu"
21365 '("Org"
21366 ("Show/Hide"
21367 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21368 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21369 ["Sparse Tree..." org-sparse-tree t]
21370 ["Reveal Context" org-reveal t]
21371 ["Show All" show-all t]
21372 "--"
21373 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21374 "--"
21375 ["New Heading" org-insert-heading t]
21376 ("Navigate Headings"
21377 ["Up" outline-up-heading t]
21378 ["Next" outline-next-visible-heading t]
21379 ["Previous" outline-previous-visible-heading t]
21380 ["Next Same Level" outline-forward-same-level t]
21381 ["Previous Same Level" outline-backward-same-level t]
21382 "--"
21383 ["Jump" org-goto t])
21384 ("Edit Structure"
21385 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21386 "--"
21387 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21388 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21389 "--"
21390 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21391 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21392 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21393 "--"
21394 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21395 "--"
21396 ["Copy visible text" org-copy-visible t]
21397 "--"
21398 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21399 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21400 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21401 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21402 "--"
21403 ["Sort Region/Children" org-sort t]
21404 "--"
21405 ["Convert to odd levels" org-convert-to-odd-levels t]
21406 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21407 ("Editing"
21408 ["Emphasis..." org-emphasize t]
21409 ["Edit Source Example" org-edit-special t]
21410 "--"
21411 ["Footnote new/jump" org-footnote-action t]
21412 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21413 ("Archive"
21414 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21415 "--"
21416 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21417 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21418 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21420 "--"
21421 ("Hyperlinks"
21422 ["Store Link (Global)" org-store-link t]
21423 ["Find existing link to here" org-occur-link-in-agenda-files t]
21424 ["Insert Link" org-insert-link t]
21425 ["Follow Link" org-open-at-point t]
21426 "--"
21427 ["Next link" org-next-link t]
21428 ["Previous link" org-previous-link t]
21429 "--"
21430 ["Descriptive Links"
21431 org-toggle-link-display
21432 :style radio
21433 :selected org-descriptive-links
21435 ["Literal Links"
21436 org-toggle-link-display
21437 :style radio
21438 :selected (not org-descriptive-links)])
21439 "--"
21440 ("TODO Lists"
21441 ["TODO/DONE/-" org-todo t]
21442 ("Select keyword"
21443 ["Next keyword" org-shiftright (org-at-heading-p)]
21444 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21445 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21446 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21447 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21448 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21449 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21450 "--"
21451 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21452 :selected org-enforce-todo-dependencies :style toggle :active t]
21453 "Settings for tree at point"
21454 ["Do Children sequentially" org-toggle-ordered-property :style radio
21455 :selected (org-entry-get nil "ORDERED")
21456 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21457 ["Do Children parallel" org-toggle-ordered-property :style radio
21458 :selected (not (org-entry-get nil "ORDERED"))
21459 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21460 "--"
21461 ["Set Priority" org-priority t]
21462 ["Priority Up" org-shiftup t]
21463 ["Priority Down" org-shiftdown t]
21464 "--"
21465 ["Get news from all feeds" org-feed-update-all t]
21466 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21467 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21468 ("TAGS and Properties"
21469 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21470 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21471 "--"
21472 ["Set property" org-set-property (not (org-before-first-heading-p))]
21473 ["Column view of properties" org-columns t]
21474 ["Insert Column View DBlock" org-insert-columns-dblock t])
21475 ("Dates and Scheduling"
21476 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21477 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21478 ("Change Date"
21479 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21480 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21481 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21482 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21483 ["Compute Time Range" org-evaluate-time-range t]
21484 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21485 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21486 "--"
21487 ["Custom time format" org-toggle-time-stamp-overlays
21488 :style radio :selected org-display-custom-times]
21489 "--"
21490 ["Goto Calendar" org-goto-calendar t]
21491 ["Date from Calendar" org-date-from-calendar t]
21492 "--"
21493 ["Start/Restart Timer" org-timer-start t]
21494 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21495 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21496 ["Insert Timer String" org-timer t]
21497 ["Insert Timer Item" org-timer-item t])
21498 ("Logging work"
21499 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21500 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21501 ["Clock out" org-clock-out t]
21502 ["Clock cancel" org-clock-cancel t]
21503 "--"
21504 ["Mark as default task" org-clock-mark-default-task t]
21505 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21506 ["Goto running clock" org-clock-goto t]
21507 "--"
21508 ["Display times" org-clock-display t]
21509 ["Create clock table" org-clock-report t]
21510 "--"
21511 ["Record DONE time"
21512 (progn (setq org-log-done (not org-log-done))
21513 (message "Switching to %s will %s record a timestamp"
21514 (car org-done-keywords)
21515 (if org-log-done "automatically" "not")))
21516 :style toggle :selected org-log-done])
21517 "--"
21518 ["Agenda Command..." org-agenda t]
21519 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21520 ("File List for Agenda")
21521 ("Special views current file"
21522 ["TODO Tree" org-show-todo-tree t]
21523 ["Check Deadlines" org-check-deadlines t]
21524 ["Timeline" org-timeline t]
21525 ["Tags/Property tree" org-match-sparse-tree t])
21526 "--"
21527 ["Export/Publish..." org-export-dispatch t]
21528 ("LaTeX"
21529 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21530 :selected org-cdlatex-mode]
21531 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21532 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21533 ["Modify math symbol" org-cdlatex-math-modify
21534 (org-inside-LaTeX-fragment-p)]
21535 ["Insert citation" org-reftex-citation t]
21536 "--"
21537 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21538 "--"
21539 ("MobileOrg"
21540 ["Push Files and Views" org-mobile-push t]
21541 ["Get Captured and Flagged" org-mobile-pull t]
21542 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21543 "--"
21544 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21545 "--"
21546 ("Documentation"
21547 ["Show Version" org-version t]
21548 ["Info Documentation" org-info t])
21549 ("Customize"
21550 ["Browse Org Group" org-customize t]
21551 "--"
21552 ["Expand This Menu" org-create-customize-menu
21553 (fboundp 'customize-menu-create)])
21554 ["Send bug report" org-submit-bug-report t]
21555 "--"
21556 ("Refresh/Reload"
21557 ["Refresh setup current buffer" org-mode-restart t]
21558 ["Reload Org (after update)" org-reload t]
21559 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21562 (defun org-info (&optional node)
21563 "Read documentation for Org-mode in the info system.
21564 With optional NODE, go directly to that node."
21565 (interactive)
21566 (info (format "(org)%s" (or node ""))))
21568 ;;;###autoload
21569 (defun org-submit-bug-report ()
21570 "Submit a bug report on Org-mode via mail.
21572 Don't hesitate to report any problems or inaccurate documentation.
21574 If you don't have setup sending mail from (X)Emacs, please copy the
21575 output buffer into your mail program, as it gives us important
21576 information about your Org-mode version and configuration."
21577 (interactive)
21578 (require 'reporter)
21579 (org-load-modules-maybe)
21580 (org-require-autoloaded-modules)
21581 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21582 (reporter-submit-bug-report
21583 "emacs-orgmode@gnu.org"
21584 (org-version nil 'full)
21585 (let (list)
21586 (save-window-excursion
21587 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21588 (delete-other-windows)
21589 (erase-buffer)
21590 (insert "You are about to submit a bug report to the Org-mode mailing list.
21592 We would like to add your full Org-mode and Outline configuration to the
21593 bug report. This greatly simplifies the work of the maintainer and
21594 other experts on the mailing list.
21596 HOWEVER, some variables you have customized may contain private
21597 information. The names of customers, colleagues, or friends, might
21598 appear in the form of file names, tags, todo states, or search strings.
21599 If you answer yes to the prompt, you might want to check and remove
21600 such private information before sending the email.")
21601 (add-text-properties (point-min) (point-max) '(face org-warning))
21602 (when (yes-or-no-p "Include your Org-mode configuration ")
21603 (mapatoms
21604 (lambda (v)
21605 (and (boundp v)
21606 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21607 (or (and (symbol-value v)
21608 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21609 (and
21610 (get v 'custom-type) (get v 'standard-value)
21611 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21612 (push v list)))))
21613 (kill-buffer (get-buffer "*Warn about privacy*"))
21614 list))
21615 nil nil
21616 "Remember to cover the basics, that is, what you expected to happen and
21617 what in fact did happen. You don't know how to make a good report? See
21619 http://orgmode.org/manual/Feedback.html#Feedback
21621 Your bug report will be posted to the Org-mode mailing list.
21622 ------------------------------------------------------------------------")
21623 (save-excursion
21624 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21625 (replace-match "\\1Bug: \\3 [\\2]")))))
21628 (defun org-install-agenda-files-menu ()
21629 (let ((bl (buffer-list)))
21630 (save-excursion
21631 (while bl
21632 (set-buffer (pop bl))
21633 (if (derived-mode-p 'org-mode) (setq bl nil)))
21634 (when (derived-mode-p 'org-mode)
21635 (easy-menu-change
21636 '("Org") "File List for Agenda"
21637 (append
21638 (list
21639 ["Edit File List" (org-edit-agenda-file-list) t]
21640 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21641 ["Remove Current File from List" org-remove-file t]
21642 ["Cycle through agenda files" org-cycle-agenda-files t]
21643 ["Occur in all agenda files" org-occur-in-agenda-files t]
21644 "--")
21645 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21647 ;;;; Documentation
21649 (defun org-require-autoloaded-modules ()
21650 (interactive)
21651 (mapc 'require
21652 '(org-agenda org-archive org-attach org-clock org-colview org-id
21653 org-table org-timer)))
21655 ;;;###autoload
21656 (defun org-reload (&optional uncompiled)
21657 "Reload all org lisp files.
21658 With prefix arg UNCOMPILED, load the uncompiled versions."
21659 (interactive "P")
21660 (require 'loadhist)
21661 (let* ((org-dir (org-find-library-dir "org"))
21662 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21663 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21664 (remove-re (mapconcat 'identity
21665 (mapcar (lambda (f) (concat "^" f "$"))
21666 (list (if (featurep 'xemacs)
21667 "org-colview"
21668 "org-colview-xemacs")
21669 "org" "org-loaddefs" "org-version"))
21670 "\\|"))
21671 (feats (delete-dups
21672 (mapcar 'file-name-sans-extension
21673 (mapcar 'file-name-nondirectory
21674 (delq nil
21675 (mapcar 'feature-file
21676 features))))))
21677 (lfeat (append
21678 (sort
21679 (setq feats
21680 (delq nil (mapcar
21681 (lambda (f)
21682 (if (and (string-match feature-re f)
21683 (not (string-match remove-re f)))
21684 f nil))
21685 feats)))
21686 'string-lessp)
21687 (list "org-version" "org")))
21688 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21689 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21690 load-uncore load-misses)
21691 (setq load-misses
21692 (delq 't
21693 (mapcar (lambda (f)
21694 (or (org-load-noerror-mustsuffix (concat org-dir f))
21695 (and (string= org-dir contrib-dir)
21696 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21697 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21698 (add-to-list 'load-uncore f 'append)
21701 lfeat)))
21702 (if load-uncore
21703 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21704 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21705 (if load-misses
21706 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21707 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21708 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21710 ;;;###autoload
21711 (defun org-customize ()
21712 "Call the customize function with org as argument."
21713 (interactive)
21714 (org-load-modules-maybe)
21715 (org-require-autoloaded-modules)
21716 (customize-browse 'org))
21718 (defun org-create-customize-menu ()
21719 "Create a full customization menu for Org-mode, insert it into the menu."
21720 (interactive)
21721 (org-load-modules-maybe)
21722 (org-require-autoloaded-modules)
21723 (if (fboundp 'customize-menu-create)
21724 (progn
21725 (easy-menu-change
21726 '("Org") "Customize"
21727 `(["Browse Org group" org-customize t]
21728 "--"
21729 ,(customize-menu-create 'org)
21730 ["Set" Custom-set t]
21731 ["Save" Custom-save t]
21732 ["Reset to Current" Custom-reset-current t]
21733 ["Reset to Saved" Custom-reset-saved t]
21734 ["Reset to Standard Settings" Custom-reset-standard t]))
21735 (message "\"Org\"-menu now contains full customization menu"))
21736 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21738 ;;;; Miscellaneous stuff
21740 ;;; Generally useful functions
21742 (defsubst org-get-at-eol (property n)
21743 "Get text property PROPERTY at the end of line less N characters."
21744 (get-text-property (- (point-at-eol) n) property))
21746 (defun org-find-text-property-in-string (prop s)
21747 "Return the first non-nil value of property PROP in string S."
21748 (or (get-text-property 0 prop s)
21749 (get-text-property (or (next-single-property-change 0 prop s) 0)
21750 prop s)))
21752 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21753 "Display the given MESSAGE as a warning."
21754 (if (fboundp 'display-warning)
21755 (display-warning 'org message
21756 (if (featurep 'xemacs) 'warning :warning))
21757 (let ((buf (get-buffer-create "*Org warnings*")))
21758 (with-current-buffer buf
21759 (goto-char (point-max))
21760 (insert "Warning (Org): " message)
21761 (unless (bolp)
21762 (newline)))
21763 (display-buffer buf)
21764 (sit-for 0))))
21766 (defun org-eval (form)
21767 "Eval FORM and return result."
21768 (condition-case error
21769 (eval form)
21770 (error (format "%%![Error: %s]" error))))
21772 (defun org-in-clocktable-p ()
21773 "Check if the cursor is in a clocktable."
21774 (let ((pos (point)) start)
21775 (save-excursion
21776 (end-of-line 1)
21777 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21778 (setq start (match-beginning 0))
21779 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21780 (>= (match-end 0) pos)
21781 start))))
21783 (defun org-in-verbatim-emphasis ()
21784 (save-match-data
21785 (and (org-in-regexp org-emph-re 2)
21786 (>= (point) (match-beginning 3))
21787 (<= (point) (match-end 4))
21788 (member (match-string 3) '("=" "~")))))
21790 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21791 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21792 (if (and marker (marker-buffer marker)
21793 (buffer-live-p (marker-buffer marker)))
21794 (progn
21795 (org-pop-to-buffer-same-window (marker-buffer marker))
21796 (if (or (> marker (point-max)) (< marker (point-min)))
21797 (widen))
21798 (goto-char marker)
21799 (org-show-context 'org-goto))
21800 (if bookmark
21801 (bookmark-jump bookmark)
21802 (error "Cannot find location"))))
21804 (defun org-quote-csv-field (s)
21805 "Quote field for inclusion in CSV material."
21806 (if (string-match "[\",]" s)
21807 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21810 (defun org-force-self-insert (N)
21811 "Needed to enforce self-insert under remapping."
21812 (interactive "p")
21813 (self-insert-command N))
21815 (defun org-string-width (s)
21816 "Compute width of string, ignoring invisible characters.
21817 This ignores character with invisibility property `org-link', and also
21818 characters with property `org-cwidth', because these will become invisible
21819 upon the next fontification round."
21820 (let (b l)
21821 (when (or (eq t buffer-invisibility-spec)
21822 (assq 'org-link buffer-invisibility-spec))
21823 (while (setq b (text-property-any 0 (length s)
21824 'invisible 'org-link s))
21825 (setq s (concat (substring s 0 b)
21826 (substring s (or (next-single-property-change
21827 b 'invisible s) (length s)))))))
21828 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21829 (setq s (concat (substring s 0 b)
21830 (substring s (or (next-single-property-change
21831 b 'org-cwidth s) (length s))))))
21832 (setq l (string-width s) b -1)
21833 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21834 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21837 (defun org-shorten-string (s maxlength)
21838 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21839 If the string is shorter or has length MAXLENGTH, just return the
21840 original string. If it is longer, the functions finds a space in the
21841 string, breaks this string off at that locations and adds three dots
21842 as ellipsis. Including the ellipsis, the string will not be longer
21843 than MAXLENGTH. If finding a good breaking point in the string does
21844 not work, the string is just chopped off in the middle of a word
21845 if necessary."
21846 (if (<= (length s) maxlength)
21848 (let* ((n (max (- maxlength 4) 1))
21849 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21850 (if (string-match re s)
21851 (concat (match-string 1 s) "...")
21852 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21854 (defun org-get-indentation (&optional line)
21855 "Get the indentation of the current line, interpreting tabs.
21856 When LINE is given, assume it represents a line and compute its indentation."
21857 (if line
21858 (if (string-match "^ *" (org-remove-tabs line))
21859 (match-end 0))
21860 (save-excursion
21861 (beginning-of-line 1)
21862 (skip-chars-forward " \t")
21863 (current-column))))
21865 (defun org-get-string-indentation (s)
21866 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21867 (let ((n -1) (i 0) (w tab-width) c)
21868 (catch 'exit
21869 (while (< (setq n (1+ n)) (length s))
21870 (setq c (aref s n))
21871 (cond ((= c ?\ ) (setq i (1+ i)))
21872 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21873 (t (throw 'exit t)))))
21876 (defun org-remove-tabs (s &optional width)
21877 "Replace tabulators in S with spaces.
21878 Assumes that s is a single line, starting in column 0."
21879 (setq width (or width tab-width))
21880 (while (string-match "\t" s)
21881 (setq s (replace-match
21882 (make-string
21883 (- (* width (/ (+ (match-beginning 0) width) width))
21884 (match-beginning 0)) ?\ )
21885 t t s)))
21888 (defun org-fix-indentation (line ind)
21889 "Fix indentation in LINE.
21890 IND is a cons cell with target and minimum indentation.
21891 If the current indentation in LINE is smaller than the minimum,
21892 leave it alone. If it is larger than ind, set it to the target."
21893 (let* ((l (org-remove-tabs line))
21894 (i (org-get-indentation l))
21895 (i1 (car ind)) (i2 (cdr ind)))
21896 (if (>= i i2) (setq l (substring line i2)))
21897 (if (> i1 0)
21898 (concat (make-string i1 ?\ ) l)
21899 l)))
21901 (defun org-remove-indentation (code &optional n)
21902 "Remove the maximum common indentation from the lines in CODE.
21903 N may optionally be the number of spaces to remove."
21904 (with-temp-buffer
21905 (insert code)
21906 (org-do-remove-indentation n)
21907 (buffer-string)))
21909 (defun org-do-remove-indentation (&optional n)
21910 "Remove the maximum common indentation from the buffer."
21911 (untabify (point-min) (point-max))
21912 (let ((min 10000) re)
21913 (if n
21914 (setq min n)
21915 (goto-char (point-min))
21916 (while (re-search-forward "^ *[^ \n]" nil t)
21917 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21918 (unless (or (= min 0) (= min 10000))
21919 (setq re (format "^ \\{%d\\}" min))
21920 (goto-char (point-min))
21921 (while (re-search-forward re nil t)
21922 (replace-match "")
21923 (end-of-line 1))
21924 min)))
21926 (defun org-fill-template (template alist)
21927 "Find each %key of ALIST in TEMPLATE and replace it."
21928 (let ((case-fold-search nil)
21929 entry key value)
21930 (setq alist (sort (copy-sequence alist)
21931 (lambda (a b) (< (length (car a)) (length (car b))))))
21932 (while (setq entry (pop alist))
21933 (setq template
21934 (replace-regexp-in-string
21935 (concat "%" (regexp-quote (car entry)))
21936 (or (cdr entry) "") template t t)))
21937 template))
21939 (defun org-base-buffer (buffer)
21940 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21941 (if (not buffer)
21942 buffer
21943 (or (buffer-base-buffer buffer)
21944 buffer)))
21946 (defun org-wrap (string &optional width lines)
21947 "Wrap string to either a number of lines, or a width in characters.
21948 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21949 that costs. If there is a word longer than WIDTH, the text is actually
21950 wrapped to the length of that word.
21951 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21952 many lines, whatever width that takes.
21953 The return value is a list of lines, without newlines at the end."
21954 (let* ((words (org-split-string string "[ \t\n]+"))
21955 (maxword (apply 'max (mapcar 'org-string-width words)))
21956 w ll)
21957 (cond (width
21958 (org-do-wrap words (max maxword width)))
21959 (lines
21960 (setq w maxword)
21961 (setq ll (org-do-wrap words maxword))
21962 (if (<= (length ll) lines)
21964 (setq ll words)
21965 (while (> (length ll) lines)
21966 (setq w (1+ w))
21967 (setq ll (org-do-wrap words w)))
21968 ll))
21969 (t (error "Cannot wrap this")))))
21971 (defun org-do-wrap (words width)
21972 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21973 (let (lines line)
21974 (while words
21975 (setq line (pop words))
21976 (while (and words (< (+ (length line) (length (car words))) width))
21977 (setq line (concat line " " (pop words))))
21978 (setq lines (push line lines)))
21979 (nreverse lines)))
21981 (defun org-split-string (string &optional separators)
21982 "Splits STRING into substrings at SEPARATORS.
21983 No empty strings are returned if there are matches at the beginning
21984 and end of string."
21985 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21986 (start 0)
21987 notfirst
21988 (list nil))
21989 (while (and (string-match rexp string
21990 (if (and notfirst
21991 (= start (match-beginning 0))
21992 (< start (length string)))
21993 (1+ start) start))
21994 (< (match-beginning 0) (length string)))
21995 (setq notfirst t)
21996 (or (eq (match-beginning 0) 0)
21997 (and (eq (match-beginning 0) (match-end 0))
21998 (eq (match-beginning 0) start))
21999 (setq list
22000 (cons (substring string start (match-beginning 0))
22001 list)))
22002 (setq start (match-end 0)))
22003 (or (eq start (length string))
22004 (setq list
22005 (cons (substring string start)
22006 list)))
22007 (nreverse list)))
22009 (defun org-quote-vert (s)
22010 "Replace \"|\" with \"\\vert\"."
22011 (while (string-match "|" s)
22012 (setq s (replace-match "\\vert" t t s)))
22015 (defun org-uuidgen-p (s)
22016 "Is S an ID created by UUIDGEN?"
22017 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22019 (defun org-in-src-block-p (&optional inside)
22020 "Whether point is in a code source block.
22021 When INSIDE is non-nil, don't consider we are within a src block
22022 when point is at #+BEGIN_SRC or #+END_SRC."
22023 (let ((case-fold-search t) ov)
22024 (or (and (eq (get-char-property (point) 'src-block) t))
22025 (and (not inside)
22026 (save-match-data
22027 (save-excursion
22028 (beginning-of-line)
22029 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22031 (defun org-context ()
22032 "Return a list of contexts of the current cursor position.
22033 If several contexts apply, all are returned.
22034 Each context entry is a list with a symbol naming the context, and
22035 two positions indicating start and end of the context. Possible
22036 contexts are:
22038 :headline anywhere in a headline
22039 :headline-stars on the leading stars in a headline
22040 :todo-keyword on a TODO keyword (including DONE) in a headline
22041 :tags on the TAGS in a headline
22042 :priority on the priority cookie in a headline
22043 :item on the first line of a plain list item
22044 :item-bullet on the bullet/number of a plain list item
22045 :checkbox on the checkbox in a plain list item
22046 :table in an org-mode table
22047 :table-special on a special filed in a table
22048 :table-table in a table.el table
22049 :clocktable in a clocktable
22050 :src-block in a source block
22051 :link on a hyperlink
22052 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22053 :target on a <<target>>
22054 :radio-target on a <<<radio-target>>>
22055 :latex-fragment on a LaTeX fragment
22056 :latex-preview on a LaTeX fragment with overlaid preview image
22058 This function expects the position to be visible because it uses font-lock
22059 faces as a help to recognize the following contexts: :table-special, :link,
22060 and :keyword."
22061 (let* ((f (get-text-property (point) 'face))
22062 (faces (if (listp f) f (list f)))
22063 (case-fold-search t)
22064 (p (point)) clist o)
22065 ;; First the large context
22066 (cond
22067 ((org-at-heading-p t)
22068 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22069 (when (progn
22070 (beginning-of-line 1)
22071 (looking-at org-todo-line-tags-regexp))
22072 (push (org-point-in-group p 1 :headline-stars) clist)
22073 (push (org-point-in-group p 2 :todo-keyword) clist)
22074 (push (org-point-in-group p 4 :tags) clist))
22075 (goto-char p)
22076 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22077 (if (looking-at "\\[#[A-Z0-9]\\]")
22078 (push (org-point-in-group p 0 :priority) clist)))
22080 ((org-at-item-p)
22081 (push (org-point-in-group p 2 :item-bullet) clist)
22082 (push (list :item (point-at-bol)
22083 (save-excursion (org-end-of-item) (point)))
22084 clist)
22085 (and (org-at-item-checkbox-p)
22086 (push (org-point-in-group p 0 :checkbox) clist)))
22088 ((org-at-table-p)
22089 (push (list :table (org-table-begin) (org-table-end)) clist)
22090 (if (memq 'org-formula faces)
22091 (push (list :table-special
22092 (previous-single-property-change p 'face)
22093 (next-single-property-change p 'face)) clist)))
22094 ((org-at-table-p 'any)
22095 (push (list :table-table) clist)))
22096 (goto-char p)
22098 (let ((case-fold-search t))
22099 ;; New the "medium" contexts: clocktables, source blocks
22100 (cond ((org-in-clocktable-p)
22101 (push (list :clocktable
22102 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22103 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22104 (match-beginning 1))
22105 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22106 (match-end 0))) clist))
22107 ((org-in-src-block-p)
22108 (push (list :src-block
22109 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22110 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22111 (match-beginning 1))
22112 (and (search-forward "#+END_SRC" nil t)
22113 (match-beginning 0))) clist))))
22114 (goto-char p)
22116 ;; Now the small context
22117 (cond
22118 ((org-at-timestamp-p)
22119 (push (org-point-in-group p 0 :timestamp) clist))
22120 ((memq 'org-link faces)
22121 (push (list :link
22122 (previous-single-property-change p 'face)
22123 (next-single-property-change p 'face)) clist))
22124 ((memq 'org-special-keyword faces)
22125 (push (list :keyword
22126 (previous-single-property-change p 'face)
22127 (next-single-property-change p 'face)) clist))
22128 ((org-at-target-p)
22129 (push (org-point-in-group p 0 :target) clist)
22130 (goto-char (1- (match-beginning 0)))
22131 (if (looking-at org-radio-target-regexp)
22132 (push (org-point-in-group p 0 :radio-target) clist))
22133 (goto-char p))
22134 ((setq o (car (delq nil
22135 (mapcar
22136 (lambda (x)
22137 (if (memq x org-latex-fragment-image-overlays) x))
22138 (overlays-at (point))))))
22139 (push (list :latex-fragment
22140 (overlay-start o) (overlay-end o)) clist)
22141 (push (list :latex-preview
22142 (overlay-start o) (overlay-end o)) clist))
22143 ((org-inside-LaTeX-fragment-p)
22144 ;; FIXME: positions wrong.
22145 (push (list :latex-fragment (point) (point)) clist)))
22147 (setq clist (nreverse (delq nil clist)))
22148 clist))
22150 (defun org-in-regexp (re &optional nlines visually)
22151 "Check if point is inside a match of RE.
22153 Normally only the current line is checked, but you can include
22154 NLINES extra lines after point into the search. If VISUALLY is
22155 set, require that the cursor is not after the match but really
22156 on, so that the block visually is on the match."
22157 (catch 'exit
22158 (let ((pos (point))
22159 (eol (point-at-eol (+ 1 (or nlines 0))))
22160 (inc (if visually 1 0)))
22161 (save-excursion
22162 (beginning-of-line (- 1 (or nlines 0)))
22163 (while (re-search-forward re eol t)
22164 (if (and (<= (match-beginning 0) pos)
22165 (>= (+ inc (match-end 0)) pos))
22166 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
22167 (define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp
22168 "Org mode 8.3")
22170 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22171 "Non-nil when point is between matches of START-RE and END-RE.
22173 Also return a non-nil value when point is on one of the matches.
22175 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22176 buffer positions. Default values are the positions of headlines
22177 surrounding the point.
22179 The functions returns a cons cell whose car (resp. cdr) is the
22180 position before START-RE (resp. after END-RE)."
22181 (save-match-data
22182 (let ((pos (point))
22183 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22184 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22185 beg end)
22186 (save-excursion
22187 ;; Point is on a block when on START-RE or if START-RE can be
22188 ;; found before it...
22189 (and (or (org-in-regexp start-re)
22190 (re-search-backward start-re limit-up t))
22191 (setq beg (match-beginning 0))
22192 ;; ... and END-RE after it...
22193 (goto-char (match-end 0))
22194 (re-search-forward end-re limit-down t)
22195 (> (setq end (match-end 0)) pos)
22196 ;; ... without another START-RE in-between.
22197 (goto-char (match-beginning 0))
22198 (not (re-search-backward start-re (1+ beg) t))
22199 ;; Return value.
22200 (cons beg end))))))
22202 (defun org-in-block-p (names)
22203 "Non-nil when point belongs to a block whose name belongs to NAMES.
22205 NAMES is a list of strings containing names of blocks.
22207 Return first block name matched, or nil. Beware that in case of
22208 nested blocks, the returned name may not belong to the closest
22209 block from point."
22210 (save-match-data
22211 (catch 'exit
22212 (let ((case-fold-search t)
22213 (lim-up (save-excursion (outline-previous-heading)))
22214 (lim-down (save-excursion (outline-next-heading))))
22215 (mapc (lambda (name)
22216 (let ((n (regexp-quote name)))
22217 (when (org-between-regexps-p
22218 (concat "^[ \t]*#\\+begin_" n)
22219 (concat "^[ \t]*#\\+end_" n)
22220 lim-up lim-down)
22221 (throw 'exit n))))
22222 names))
22223 nil)))
22225 (defun org-occur-in-agenda-files (regexp &optional nlines)
22226 "Call `multi-occur' with buffers for all agenda files."
22227 (interactive "sOrg-files matching: \np")
22228 (let* ((files (org-agenda-files))
22229 (tnames (mapcar 'file-truename files))
22230 (extra org-agenda-text-search-extra-files)
22232 (when (eq (car extra) 'agenda-archives)
22233 (setq extra (cdr extra))
22234 (setq files (org-add-archive-files files)))
22235 (while (setq f (pop extra))
22236 (unless (member (file-truename f) tnames)
22237 (add-to-list 'files f 'append)
22238 (add-to-list 'tnames (file-truename f) 'append)))
22239 (multi-occur
22240 (mapcar (lambda (x)
22241 (with-current-buffer
22242 (or (get-file-buffer x) (find-file-noselect x))
22243 (widen)
22244 (current-buffer)))
22245 files)
22246 regexp)))
22248 (if (boundp 'occur-mode-find-occurrence-hook)
22249 ;; Emacs 23
22250 (add-hook 'occur-mode-find-occurrence-hook
22251 (lambda ()
22252 (when (derived-mode-p 'org-mode)
22253 (org-reveal))))
22254 ;; Emacs 22
22255 (defadvice occur-mode-goto-occurrence
22256 (after org-occur-reveal activate)
22257 (and (derived-mode-p 'org-mode) (org-reveal)))
22258 (defadvice occur-mode-goto-occurrence-other-window
22259 (after org-occur-reveal activate)
22260 (and (derived-mode-p 'org-mode) (org-reveal)))
22261 (defadvice occur-mode-display-occurrence
22262 (after org-occur-reveal activate)
22263 (when (derived-mode-p 'org-mode)
22264 (let ((pos (occur-mode-find-occurrence)))
22265 (with-current-buffer (marker-buffer pos)
22266 (save-excursion
22267 (goto-char pos)
22268 (org-reveal)))))))
22270 (defun org-occur-link-in-agenda-files ()
22271 "Create a link and search for it in the agendas.
22272 The link is not stored in `org-stored-links', it is just created
22273 for the search purpose."
22274 (interactive)
22275 (let ((link (condition-case nil
22276 (org-store-link nil)
22277 (error "Unable to create a link to here"))))
22278 (org-occur-in-agenda-files (regexp-quote link))))
22280 (defun org-reverse-string (string)
22281 "Return the reverse of STRING."
22282 (apply 'string (reverse (string-to-list string))))
22284 ;; defsubst org-uniquify must be defined before first use
22286 (defun org-uniquify-alist (alist)
22287 "Merge elements of ALIST with the same key.
22289 For example, in this alist:
22291 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
22292 => '((a 1 3) (b 2))
22294 merge (a 1) and (a 3) into (a 1 3).
22296 The function returns the new ALIST."
22297 (let (rtn)
22298 (mapc
22299 (lambda (e)
22300 (let (n)
22301 (if (not (assoc (car e) rtn))
22302 (push e rtn)
22303 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22304 (setq rtn (assq-delete-all (car e) rtn))
22305 (push n rtn))))
22306 alist)
22307 rtn))
22309 (defun org-delete-all (elts list)
22310 "Remove all elements in ELTS from LIST."
22311 (while elts
22312 (setq list (delete (pop elts) list)))
22313 list)
22315 (defun org-count (cl-item cl-seq)
22316 "Count the number of occurrences of ITEM in SEQ.
22317 Taken from `count' in cl-seq.el with all keyword arguments removed."
22318 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
22319 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
22320 (while (< cl-start cl-end)
22321 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
22322 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
22323 (setq cl-start (1+ cl-start)))
22324 cl-count))
22326 (defun org-remove-if (predicate seq)
22327 "Remove everything from SEQ that fulfills PREDICATE."
22328 (let (res e)
22329 (while seq
22330 (setq e (pop seq))
22331 (if (not (funcall predicate e)) (push e res)))
22332 (nreverse res)))
22334 (defun org-remove-if-not (predicate seq)
22335 "Remove everything from SEQ that does not fulfill PREDICATE."
22336 (let (res e)
22337 (while seq
22338 (setq e (pop seq))
22339 (if (funcall predicate e) (push e res)))
22340 (nreverse res)))
22342 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22343 "Reduce two-argument FUNCTION across SEQ.
22344 Taken from `reduce' in cl-seq.el with all keyword arguments but
22345 \":initial-value\" removed."
22346 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22347 (cadr (memq :initial-value cl-keys)))
22348 (cl-seq (pop cl-seq))
22349 (t (funcall cl-func)))))
22350 (while cl-seq
22351 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22352 cl-accum))
22354 (defun org-every (pred seq)
22355 "Return true if PREDICATE is true of every element of SEQ.
22356 Adapted from `every' in cl.el."
22357 (catch 'org-every
22358 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22361 (defun org-some (pred seq)
22362 "Return true if PREDICATE is true of any element of SEQ.
22363 Adapted from `some' in cl.el."
22364 (catch 'org-some
22365 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22366 nil))
22368 (defun org-back-over-empty-lines ()
22369 "Move backwards over whitespace, to the beginning of the first empty line.
22370 Returns the number of empty lines passed."
22371 (let ((pos (point)))
22372 (if (cdr (assoc 'heading org-blank-before-new-entry))
22373 (skip-chars-backward " \t\n\r")
22374 (unless (eobp)
22375 (forward-line -1)))
22376 (beginning-of-line 2)
22377 (goto-char (min (point) pos))
22378 (count-lines (point) pos)))
22380 (defun org-skip-whitespace ()
22381 (skip-chars-forward " \t\n\r"))
22383 (defun org-point-in-group (point group &optional context)
22384 "Check if POINT is in match-group GROUP.
22385 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22386 match. If the match group does not exist or point is not inside it,
22387 return nil."
22388 (and (match-beginning group)
22389 (>= point (match-beginning group))
22390 (<= point (match-end group))
22391 (if context
22392 (list context (match-beginning group) (match-end group))
22393 t)))
22395 (defun org-switch-to-buffer-other-window (&rest args)
22396 "Switch to buffer in a second window on the current frame.
22397 In particular, do not allow pop-up frames.
22398 Returns the newly created buffer."
22399 (org-no-popups
22400 (apply 'switch-to-buffer-other-window args)))
22402 (defun org-combine-plists (&rest plists)
22403 "Create a single property list from all plists in PLISTS.
22404 The process starts by copying the first list, and then setting properties
22405 from the other lists. Settings in the last list are the most significant
22406 ones and overrule settings in the other lists."
22407 (let ((rtn (copy-sequence (pop plists)))
22408 p v ls)
22409 (while plists
22410 (setq ls (pop plists))
22411 (while ls
22412 (setq p (pop ls) v (pop ls))
22413 (setq rtn (plist-put rtn p v))))
22414 rtn))
22416 (defun org-replace-escapes (string table)
22417 "Replace %-escapes in STRING with values in TABLE.
22418 TABLE is an association list with keys like \"%a\" and string values.
22419 The sequences in STRING may contain normal field width and padding information,
22420 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22421 so values can contain further %-escapes if they are define later in TABLE."
22422 (let ((tbl (copy-alist table))
22423 (case-fold-search nil)
22424 (pchg 0)
22425 e re rpl)
22426 (while (setq e (pop tbl))
22427 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22428 (when (and (cdr e) (string-match re (cdr e)))
22429 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22430 (safe "SREF"))
22431 (add-text-properties 0 3 (list 'sref sref) safe)
22432 (setcdr e (replace-match safe t t (cdr e)))))
22433 (while (string-match re string)
22434 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22435 (cdr e)))
22436 (setq string (replace-match rpl t t string))))
22437 (while (setq pchg (next-property-change pchg string))
22438 (let ((sref (get-text-property pchg 'sref string)))
22439 (when (and sref (string-match "SREF" string pchg))
22440 (setq string (replace-match sref t t string)))))
22441 string))
22443 (defun org-sublist (list start end)
22444 "Return a section of LIST, from START to END.
22445 Counting starts at 1."
22446 (let (rtn (c start))
22447 (setq list (nthcdr (1- start) list))
22448 (while (and list (<= c end))
22449 (push (pop list) rtn)
22450 (setq c (1+ c)))
22451 (nreverse rtn)))
22453 (defun org-find-base-buffer-visiting (file)
22454 "Like `find-buffer-visiting' but always return the base buffer and
22455 not an indirect buffer."
22456 (let ((buf (or (get-file-buffer file)
22457 (find-buffer-visiting file))))
22458 (if buf
22459 (or (buffer-base-buffer buf) buf)
22460 nil)))
22462 (defun org-image-file-name-regexp (&optional extensions)
22463 "Return regexp matching the file names of images.
22464 If EXTENSIONS is given, only match these."
22465 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22466 (image-file-name-regexp)
22467 (let ((image-file-name-extensions
22468 (or extensions
22469 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22470 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22471 (concat "\\."
22472 (regexp-opt (nconc (mapcar 'upcase
22473 image-file-name-extensions)
22474 image-file-name-extensions)
22476 "\\'"))))
22478 (defun org-file-image-p (file &optional extensions)
22479 "Return non-nil if FILE is an image."
22480 (save-match-data
22481 (string-match (org-image-file-name-regexp extensions) file)))
22483 (defun org-get-cursor-date (&optional with-time)
22484 "Return the date at cursor in as a time.
22485 This works in the calendar and in the agenda, anywhere else it just
22486 returns the current time.
22487 If WITH-TIME is non-nil, returns the time of the event at point (in
22488 the agenda) or the current time of the day."
22489 (let (date day defd tp tm hod mod)
22490 (when with-time
22491 (setq tp (get-text-property (point) 'time))
22492 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22493 (setq hod (string-to-number (match-string 1 tp))
22494 mod (string-to-number (match-string 2 tp))))
22495 (or tp (setq hod (nth 2 (decode-time (current-time)))
22496 mod (nth 1 (decode-time (current-time))))))
22497 (cond
22498 ((eq major-mode 'calendar-mode)
22499 (setq date (calendar-cursor-to-date)
22500 defd (encode-time 0 (or mod 0) (or hod 0)
22501 (nth 1 date) (nth 0 date) (nth 2 date))))
22502 ((eq major-mode 'org-agenda-mode)
22503 (setq day (get-text-property (point) 'day))
22504 (if day
22505 (setq date (calendar-gregorian-from-absolute day)
22506 defd (encode-time 0 (or mod 0) (or hod 0)
22507 (nth 1 date) (nth 0 date) (nth 2 date))))))
22508 (or defd (current-time))))
22510 (defun org-mark-subtree (&optional up)
22511 "Mark the current subtree.
22512 This puts point at the start of the current subtree, and mark at
22513 the end. If a numeric prefix UP is given, move up into the
22514 hierarchy of headlines by UP levels before marking the subtree."
22515 (interactive "P")
22516 (org-with-limited-levels
22517 (cond ((org-at-heading-p) (beginning-of-line))
22518 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22519 (t (outline-previous-visible-heading 1))))
22520 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22521 (if (org-called-interactively-p 'any)
22522 (call-interactively 'org-mark-element)
22523 (org-mark-element)))
22526 ;;; Indentation
22528 (defun org--get-expected-indentation (element contentsp)
22529 "Expected indentation column for current line, according to ELEMENT.
22530 ELEMENT is an element containing point. CONTENTSP is non-nil
22531 when indentation is to be computed according to contents of
22532 ELEMENT."
22533 (let ((type (org-element-type element))
22534 (start (org-element-property :begin element)))
22535 (org-with-wide-buffer
22536 (cond
22537 (contentsp
22538 (case type
22539 (footnote-definition 0)
22540 ((headline inlinetask nil)
22541 (if (not org-adapt-indentation) 0
22542 (let ((level (org-current-level)))
22543 (if level (1+ level) 0))))
22544 (item
22545 (org-list-item-body-column
22546 (org-element-property :post-affiliated element)))
22547 (plain-list
22548 (save-excursion
22549 (goto-char (org-element-property :post-affiliated element))
22550 (org-get-indentation)))
22551 (otherwise
22552 (goto-char start)
22553 (org-get-indentation))))
22554 ((memq type '(headline inlinetask nil))
22555 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22556 (org--get-expected-indentation element t)
22558 ((eq type 'footnote-definition) 0)
22559 ;; First paragraph of a footnote definition or an item.
22560 ;; Indent like parent.
22561 ((< (line-beginning-position) start)
22562 (org--get-expected-indentation
22563 (org-element-property :parent element) t))
22564 ;; At first line: indent according to previous sibling, if any,
22565 ;; ignoring footnote definitions and inline tasks, or parent's
22566 ;; contents.
22567 ((= (line-beginning-position) start)
22568 (catch 'exit
22569 (while t
22570 (if (= (point-min) start) (throw 'exit 0)
22571 (goto-char (1- start))
22572 (let* ((previous (org-element-at-point))
22573 (parent previous))
22574 (while (and parent (<= (org-element-property :end parent) start))
22575 (setq previous parent
22576 parent (org-element-property :parent parent)))
22577 (cond
22578 ((not previous) (throw 'exit 0))
22579 ((> (org-element-property :end previous) start)
22580 (throw 'exit (org--get-expected-indentation previous t)))
22581 ((memq (org-element-type previous)
22582 '(footnote-definition inlinetask))
22583 (setq start (org-element-property :begin previous)))
22584 (t (goto-char (org-element-property :begin previous))
22585 (throw 'exit
22586 (if (bolp) (org-get-indentation)
22587 ;; At first paragraph in an item or
22588 ;; a footnote definition.
22589 (org--get-expected-indentation
22590 (org-element-property :parent previous) t))))))))))
22591 ;; Otherwise, move to the first non-blank line above.
22593 (beginning-of-line)
22594 (let ((pos (point)))
22595 (skip-chars-backward " \r\t\n")
22596 (cond
22597 ;; Two blank lines end a footnote definition or a plain
22598 ;; list. When we indent an empty line after them, the
22599 ;; containing list or footnote definition is over, so it
22600 ;; qualifies as a previous sibling. Therefore, we indent
22601 ;; like its first line.
22602 ((and (memq type '(footnote-definition plain-list))
22603 (> (count-lines (point) pos) 2))
22604 (goto-char start)
22605 (org-get-indentation))
22606 ;; Line above is the first one of a paragraph at the
22607 ;; beginning of an item or a footnote definition. Indent
22608 ;; like parent.
22609 ((< (line-beginning-position) start)
22610 (org--get-expected-indentation
22611 (org-element-property :parent element) t))
22612 ;; POS is after contents in a greater element. Indent like
22613 ;; the beginning of the element.
22615 ;; As a special case, if point is at the end of a footnote
22616 ;; definition or an item, indent like the very last element
22617 ;; within.
22618 ((and (not (eq type 'paragraph))
22619 (let ((cend (org-element-property :contents-end element)))
22620 (and cend (<= cend pos))))
22621 (if (memq type '(footnote-definition item plain-list))
22622 (org--get-expected-indentation (org-element-at-point) nil)
22623 (goto-char start)
22624 (org-get-indentation)))
22625 ;; In any other case, indent like the current line.
22626 (t (org-get-indentation)))))))))
22628 (defun org--align-node-property ()
22629 "Align node property at point.
22630 Alignment is done according to `org-property-format', which see."
22631 (when (save-excursion
22632 (beginning-of-line)
22633 (looking-at org-property-re))
22634 (replace-match
22635 (concat (match-string 4)
22636 (org-trim
22637 (format org-property-format (match-string 1) (match-string 3))))
22638 t t)))
22640 (defun org-indent-line ()
22641 "Indent line depending on context.
22643 Indentation is done according to the following rules:
22645 - Footnote definitions, headlines and inline tasks have to
22646 start at column 0.
22648 - On the very first line of an element, consider, in order, the
22649 next rules until one matches:
22651 1. If there's a sibling element before, ignoring footnote
22652 definitions and inline tasks, indent like its first line.
22654 2. If element has a parent, indent like its contents. More
22655 precisely, if parent is an item, indent after the
22656 description part, if any, or the bullet (see
22657 `org-list-description-max-indent'). Else, indent like
22658 parent's first line.
22660 3. Otherwise, indent relatively to current level, if
22661 `org-adapt-indentation' is non-nil, or to left margin.
22663 - On a blank line at the end of an element, indent according to
22664 the type of the element. More precisely
22666 1. If element is a plain list, an item, or a footnote
22667 definition, indent like the very last element within.
22669 2. If element is a paragraph, indent like its last non blank
22670 line.
22672 3. Otherwise, indent like its very first line.
22674 - In the code part of a source block, use language major mode
22675 to indent current line if `org-src-tab-acts-natively' is
22676 non-nil. If it is nil, do nothing.
22678 - Otherwise, indent like the first non-blank line above.
22680 The function doesn't indent an item as it could break the whole
22681 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22682 \\[org-shiftmetaright].
22684 Also align node properties according to `org-property-format'."
22685 (interactive)
22686 (cond
22687 (orgstruct-is-++
22688 (let ((indent-line-function
22689 (cadadr (assq 'indent-line-function org-fb-vars))))
22690 (indent-according-to-mode)))
22691 ((org-at-heading-p) 'noindent)
22693 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22694 (type (org-element-type element)))
22695 (cond ((and (memq type '(plain-list item))
22696 (= (line-beginning-position)
22697 (org-element-property :post-affiliated element)))
22698 'noindent)
22699 ((and (eq type 'src-block)
22700 org-src-tab-acts-natively
22701 (> (line-beginning-position)
22702 (org-element-property :post-affiliated element))
22703 (< (line-beginning-position)
22704 (org-with-wide-buffer
22705 (goto-char (org-element-property :end element))
22706 (skip-chars-backward " \r\t\n")
22707 (line-beginning-position))))
22708 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22710 (let ((column (org--get-expected-indentation element nil)))
22711 ;; Preserve current column.
22712 (if (<= (current-column) (current-indentation))
22713 (org-indent-line-to column)
22714 (save-excursion (org-indent-line-to column))))
22715 ;; Align node property. Also preserve current column.
22716 (when (eq type 'node-property)
22717 (let ((column (current-column)))
22718 (org--align-node-property)
22719 (org-move-to-column column)))))))))
22721 (defun org-indent-region (start end)
22722 "Indent each non-blank line in the region.
22723 Called from a program, START and END specify the region to
22724 indent. The function will not indent contents of example blocks,
22725 verse blocks and export blocks as leading white spaces are
22726 assumed to be significant there."
22727 (interactive "r")
22728 (save-excursion
22729 (goto-char start)
22730 (skip-chars-forward " \r\t\n")
22731 (unless (eobp) (beginning-of-line))
22732 (let ((indent-to
22733 (lambda (ind pos)
22734 ;; Set IND as indentation for all lines between point and
22735 ;; POS or END, whichever comes first. Blank lines are
22736 ;; ignored. Leave point after POS once done.
22737 (let ((limit (copy-marker (min end pos))))
22738 (while (< (point) limit)
22739 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
22740 (forward-line))
22741 (set-marker limit nil))))
22742 (end (copy-marker end)))
22743 (while (< (point) end)
22744 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22745 (let* ((element (org-element-at-point))
22746 (type (org-element-type element))
22747 (element-end (copy-marker (org-element-property :end element)))
22748 (ind (org--get-expected-indentation element nil)))
22749 (cond
22750 ((or (memq type '(paragraph table table-row))
22751 (not (or (org-element-property :contents-begin element)
22752 (memq type
22753 '(example-block export-block src-block)))))
22754 ;; Elements here are indented as a single block. Also
22755 ;; align node properties.
22756 (when (eq type 'node-property)
22757 (org--align-node-property)
22758 (beginning-of-line))
22759 (funcall indent-to ind element-end))
22761 ;; Elements in this category consist of three parts:
22762 ;; before the contents, the contents, and after the
22763 ;; contents. The contents are treated specially,
22764 ;; according to the element type, or not indented at
22765 ;; all. Other parts are indented as a single block.
22766 (let* ((post (copy-marker
22767 (org-element-property :post-affiliated element)))
22768 (cbeg
22769 (copy-marker
22770 (cond
22771 ((not (org-element-property :contents-begin element))
22772 ;; Fake contents for source blocks.
22773 (org-with-wide-buffer
22774 (goto-char post)
22775 (forward-line)
22776 (point)))
22777 ((memq type '(footnote-definition item plain-list))
22778 ;; Contents in these elements could start on
22779 ;; the same line as the beginning of the
22780 ;; element. Make sure we start indenting
22781 ;; from the second line.
22782 (org-with-wide-buffer
22783 (goto-char post)
22784 (end-of-line)
22785 (skip-chars-forward " \r\t\n")
22786 (if (eobp) (point) (line-beginning-position))))
22787 (t (org-element-property :contents-begin element)))))
22788 (cend (copy-marker
22789 (or (org-element-property :contents-end element)
22790 ;; Fake contents for source blocks.
22791 (org-with-wide-buffer
22792 (goto-char element-end)
22793 (skip-chars-backward " \r\t\n")
22794 (line-beginning-position)))
22795 t)))
22796 ;; Do not change items indentation individually as it
22797 ;; might break the list as a whole. On the other
22798 ;; hand, when at a plain list, indent it as a whole.
22799 (cond ((eq type 'plain-list)
22800 (let ((offset (- ind (org-get-indentation))))
22801 (unless (zerop offset)
22802 (indent-rigidly (org-element-property :begin element)
22803 (org-element-property :end element)
22804 offset))
22805 (goto-char cbeg)))
22806 ((eq type 'item) (goto-char cbeg))
22807 (t (funcall indent-to ind cbeg)))
22808 (when (< (point) end)
22809 (case type
22810 ((example-block export-block verse-block))
22811 (src-block
22812 ;; In a source block, indent source code
22813 ;; according to language major mode, but only if
22814 ;; `org-src-tab-acts-natively' is non-nil.
22815 (when (and (< (point) end) org-src-tab-acts-natively)
22816 (ignore-errors
22817 (org-babel-do-in-edit-buffer
22818 (indent-region (point-min) (point-max))))))
22819 (t (org-indent-region (point) (min cend end))))
22820 (goto-char (min cend end))
22821 (when (< (point) end) (funcall indent-to ind element-end)))
22822 (set-marker post nil)
22823 (set-marker cbeg nil)
22824 (set-marker cend nil))))
22825 (set-marker element-end nil))))
22826 (set-marker end nil))))
22828 (defun org-indent-drawer ()
22829 "Indent the drawer at point."
22830 (interactive)
22831 (unless (save-excursion
22832 (beginning-of-line)
22833 (org-looking-at-p org-drawer-regexp))
22834 (user-error "Not at a drawer"))
22835 (let ((element (org-element-at-point)))
22836 (unless (memq (org-element-type element) '(drawer property-drawer))
22837 (user-error "Not at a drawer"))
22838 (org-with-wide-buffer
22839 (org-indent-region (org-element-property :begin element)
22840 (org-element-property :end element))))
22841 (message "Drawer at point indented"))
22843 (defun org-indent-block ()
22844 "Indent the block at point."
22845 (interactive)
22846 (unless (save-excursion
22847 (beginning-of-line)
22848 (let ((case-fold-search t))
22849 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22850 (user-error "Not at a block"))
22851 (let ((element (org-element-at-point)))
22852 (unless (memq (org-element-type element)
22853 '(comment-block center-block dynamic-block example-block
22854 export-block quote-block special-block
22855 src-block verse-block))
22856 (user-error "Not at a block"))
22857 (org-with-wide-buffer
22858 (org-indent-region (org-element-property :begin element)
22859 (org-element-property :end element))))
22860 (message "Block at point indented"))
22863 ;;; Filling
22865 ;; We use our own fill-paragraph and auto-fill functions.
22867 ;; `org-fill-paragraph' relies on adaptive filling and context
22868 ;; checking. Appropriate `fill-prefix' is computed with
22869 ;; `org-adaptive-fill-function'.
22871 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22872 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22873 ;; `org-adaptive-fill-function' value. Internally,
22874 ;; `org-comment-line-break-function' breaks the line.
22876 ;; `org-setup-filling' installs filling and auto-filling related
22877 ;; variables during `org-mode' initialization.
22879 (defvar org-element-paragraph-separate) ; org-element.el
22880 (defun org-setup-filling ()
22881 (require 'org-element)
22882 ;; Prevent auto-fill from inserting unwanted new items.
22883 (when (boundp 'fill-nobreak-predicate)
22884 (org-set-local
22885 'fill-nobreak-predicate
22886 (org-uniquify
22887 (append fill-nobreak-predicate
22888 '(org-fill-line-break-nobreak-p
22889 org-fill-paragraph-with-timestamp-nobreak-p)))))
22890 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22891 (org-set-local 'paragraph-start paragraph-ending)
22892 (org-set-local 'paragraph-separate paragraph-ending))
22893 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22894 (org-set-local 'auto-fill-inhibit-regexp nil)
22895 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22896 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22897 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22899 (defun org-fill-line-break-nobreak-p ()
22900 "Non-nil when a new line at point would create an Org line break."
22901 (save-excursion
22902 (skip-chars-backward "[ \t]")
22903 (skip-chars-backward "\\\\")
22904 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22906 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22907 "Non-nil when a new line at point would split a timestamp."
22908 (and (org-at-timestamp-p t)
22909 (not (looking-at org-ts-regexp-both))))
22911 (declare-function message-in-body-p "message" ())
22912 (defvar orgtbl-line-start-regexp) ; From org-table.el
22913 (defun org-adaptive-fill-function ()
22914 "Compute a fill prefix for the current line.
22915 Return fill prefix, as a string, or nil if current line isn't
22916 meant to be filled. For convenience, if `adaptive-fill-regexp'
22917 matches in paragraphs or comments, use it."
22918 (catch 'exit
22919 (when (derived-mode-p 'message-mode)
22920 (save-excursion
22921 (beginning-of-line)
22922 (cond ((or (not (message-in-body-p))
22923 (looking-at orgtbl-line-start-regexp))
22924 (throw 'exit nil))
22925 ((looking-at message-cite-prefix-regexp)
22926 (throw 'exit (match-string-no-properties 0)))
22927 ((looking-at org-outline-regexp)
22928 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22929 (org-with-wide-buffer
22930 (unless (org-at-heading-p)
22931 (let* ((p (line-beginning-position))
22932 (element (save-excursion
22933 (beginning-of-line)
22934 (org-element-at-point)))
22935 (type (org-element-type element))
22936 (post-affiliated (org-element-property :post-affiliated element)))
22937 (unless (< p post-affiliated)
22938 (case type
22939 (comment
22940 (save-excursion
22941 (beginning-of-line)
22942 (looking-at "[ \t]*")
22943 (concat (match-string 0) "# ")))
22944 (footnote-definition "")
22945 ((item plain-list)
22946 (make-string (org-list-item-body-column post-affiliated) ?\s))
22947 (paragraph
22948 ;; Fill prefix is usually the same as the current line,
22949 ;; unless the paragraph is at the beginning of an item.
22950 (let ((parent (org-element-property :parent element)))
22951 (save-excursion
22952 (beginning-of-line)
22953 (cond ((eq (org-element-type parent) 'item)
22954 (make-string (org-list-item-body-column
22955 (org-element-property :begin parent))
22956 ?\s))
22957 ((and adaptive-fill-regexp
22958 ;; Locally disable
22959 ;; `adaptive-fill-function' to let
22960 ;; `fill-context-prefix' handle
22961 ;; `adaptive-fill-regexp' variable.
22962 (let (adaptive-fill-function)
22963 (fill-context-prefix
22964 post-affiliated
22965 (org-element-property :end element)))))
22966 ((looking-at "[ \t]+") (match-string 0))
22967 (t "")))))
22968 (comment-block
22969 ;; Only fill contents if P is within block boundaries.
22970 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22971 (forward-line)
22972 (point)))
22973 (cend (save-excursion
22974 (goto-char (org-element-property :end element))
22975 (skip-chars-backward " \r\t\n")
22976 (line-beginning-position))))
22977 (when (and (>= p cbeg) (< p cend))
22978 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22979 (match-string 0)
22980 "")))))))))))
22982 (declare-function message-goto-body "message" ())
22983 (defvar message-cite-prefix-regexp) ; From message.el
22984 (defun org-fill-paragraph (&optional justify)
22985 "Fill element at point, when applicable.
22987 This function only applies to comment blocks, comments, example
22988 blocks and paragraphs. Also, as a special case, re-align table
22989 when point is at one.
22991 If JUSTIFY is non-nil (interactively, with prefix argument),
22992 justify as well. If `sentence-end-double-space' is non-nil, then
22993 period followed by one space does not end a sentence, so don't
22994 break a line there. The variable `fill-column' controls the
22995 width for filling.
22997 For convenience, when point is at a plain list, an item or
22998 a footnote definition, try to fill the first paragraph within."
22999 (interactive)
23000 (if (and (derived-mode-p 'message-mode)
23001 (or (not (message-in-body-p))
23002 (save-excursion (move-beginning-of-line 1)
23003 (looking-at message-cite-prefix-regexp))))
23004 ;; First ensure filling is correct in message-mode.
23005 (let ((fill-paragraph-function
23006 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
23007 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
23008 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
23009 (paragraph-separate
23010 (cadadr (assoc 'paragraph-separate org-fb-vars))))
23011 (fill-paragraph nil))
23012 (with-syntax-table org-mode-transpose-word-syntax-table
23013 ;; Move to end of line in order to get the first paragraph
23014 ;; within a plain list or a footnote definition.
23015 (let ((element (save-excursion
23016 (end-of-line)
23017 (or (ignore-errors (org-element-at-point))
23018 (user-error "An element cannot be parsed line %d"
23019 (line-number-at-pos (point)))))))
23020 ;; First check if point is in a blank line at the beginning of
23021 ;; the buffer. In that case, ignore filling.
23022 (case (org-element-type element)
23023 ;; Use major mode filling function is src blocks.
23024 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23025 ;; Align Org tables, leave table.el tables as-is.
23026 (table-row (org-table-align) t)
23027 (table
23028 (when (eq (org-element-property :type element) 'org)
23029 (save-excursion
23030 (goto-char (org-element-property :post-affiliated element))
23031 (org-table-align)))
23033 (paragraph
23034 ;; Paragraphs may contain `line-break' type objects.
23035 (let ((beg (max (point-min)
23036 (org-element-property :contents-begin element)))
23037 (end (min (point-max)
23038 (org-element-property :contents-end element))))
23039 ;; Do nothing if point is at an affiliated keyword.
23040 (if (< (line-end-position) beg) t
23041 (when (derived-mode-p 'message-mode)
23042 ;; In `message-mode', do not fill following citation
23043 ;; in current paragraph nor text before message body.
23044 (let ((body-start (save-excursion (message-goto-body))))
23045 (when body-start (setq beg (max body-start beg))))
23046 (when (save-excursion
23047 (re-search-forward
23048 (concat "^" message-cite-prefix-regexp) end t))
23049 (setq end (match-beginning 0))))
23050 ;; Fill paragraph, taking line breaks into account.
23051 (save-excursion
23052 (goto-char beg)
23053 (let ((cuts (list beg)))
23054 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23055 (when (eq 'line-break
23056 (org-element-type
23057 (save-excursion (backward-char)
23058 (org-element-context))))
23059 (push (point) cuts)))
23060 (dolist (c (delq end cuts))
23061 (fill-region-as-paragraph c end justify)
23062 (setq end c))))
23063 t)))
23064 ;; Contents of `comment-block' type elements should be
23065 ;; filled as plain text, but only if point is within block
23066 ;; markers.
23067 (comment-block
23068 (let* ((case-fold-search t)
23069 (beg (save-excursion
23070 (goto-char (org-element-property :begin element))
23071 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23072 (forward-line)
23073 (point)))
23074 (end (save-excursion
23075 (goto-char (org-element-property :end element))
23076 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23077 (line-beginning-position))))
23078 (if (or (< (point) beg) (> (point) end)) t
23079 (fill-region-as-paragraph
23080 (save-excursion (end-of-line)
23081 (re-search-backward "^[ \t]*$" beg 'move)
23082 (line-beginning-position))
23083 (save-excursion (beginning-of-line)
23084 (re-search-forward "^[ \t]*$" end 'move)
23085 (line-beginning-position))
23086 justify))))
23087 ;; Fill comments.
23088 (comment
23089 (let ((begin (org-element-property :post-affiliated element))
23090 (end (org-element-property :end element)))
23091 (when (and (>= (point) begin) (<= (point) end))
23092 (let ((begin (save-excursion
23093 (end-of-line)
23094 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23095 (progn (forward-line) (point))
23096 begin)))
23097 (end (save-excursion
23098 (end-of-line)
23099 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23100 (1- (line-beginning-position))
23101 (skip-chars-backward " \r\t\n")
23102 (line-end-position)))))
23103 ;; Do not fill comments when at a blank line.
23104 (when (> end begin)
23105 (let ((fill-prefix
23106 (save-excursion
23107 (beginning-of-line)
23108 (looking-at "[ \t]*#")
23109 (let ((comment-prefix (match-string 0)))
23110 (goto-char (match-end 0))
23111 (if (looking-at adaptive-fill-regexp)
23112 (concat comment-prefix (match-string 0))
23113 (concat comment-prefix " "))))))
23114 (save-excursion
23115 (fill-region-as-paragraph begin end justify))))))
23117 ;; Ignore every other element.
23118 (otherwise t))))))
23120 (defun org-auto-fill-function ()
23121 "Auto-fill function."
23122 ;; Check if auto-filling is meaningful.
23123 (let ((fc (current-fill-column)))
23124 (when (and fc (> (current-column) fc))
23125 (let* ((fill-prefix (org-adaptive-fill-function))
23126 ;; Enforce empty fill prefix, if required. Otherwise, it
23127 ;; will be computed again.
23128 (adaptive-fill-mode (not (equal fill-prefix ""))))
23129 (when fill-prefix (do-auto-fill))))))
23131 (defun org-comment-line-break-function (&optional soft)
23132 "Break line at point and indent, continuing comment if within one.
23133 The inserted newline is marked hard if variable
23134 `use-hard-newlines' is true, unless optional argument SOFT is
23135 non-nil."
23136 (if soft (insert-and-inherit ?\n) (newline 1))
23137 (save-excursion (forward-char -1) (delete-horizontal-space))
23138 (delete-horizontal-space)
23139 (indent-to-left-margin)
23140 (insert-before-markers-and-inherit fill-prefix))
23143 ;;; Fixed Width Areas
23145 (defun org-toggle-fixed-width ()
23146 "Toggle fixed-width markup.
23148 Add or remove fixed-width markup on current line, whenever it
23149 makes sense. Return an error otherwise.
23151 If a region is active and if it contains only fixed-width areas
23152 or blank lines, remove all fixed-width markup in it. If the
23153 region contains anything else, convert all non-fixed-width lines
23154 to fixed-width ones.
23156 Blank lines at the end of the region are ignored unless the
23157 region only contains such lines."
23158 (interactive)
23159 (if (not (org-region-active-p))
23160 ;; No region:
23162 ;; Remove fixed width marker only in a fixed-with element.
23164 ;; Add fixed width maker in paragraphs, in blank lines after
23165 ;; elements or at the beginning of a headline or an inlinetask,
23166 ;; and before any one-line elements (e.g., a clock).
23167 (progn
23168 (beginning-of-line)
23169 (let* ((element (org-element-at-point))
23170 (type (org-element-type element)))
23171 (cond
23172 ((and (eq type 'fixed-width)
23173 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23174 (replace-match
23175 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23176 ((and (memq type '(babel-call clock comment diary-sexp headline
23177 horizontal-rule keyword paragraph
23178 planning))
23179 (<= (org-element-property :post-affiliated element) (point)))
23180 (skip-chars-forward " \t")
23181 (insert ": "))
23182 ((and (org-looking-at-p "[ \t]*$")
23183 (or (eq type 'inlinetask)
23184 (save-excursion
23185 (skip-chars-forward " \r\t\n")
23186 (<= (org-element-property :end element) (point)))))
23187 (delete-region (point) (line-end-position))
23188 (org-indent-line)
23189 (insert ": "))
23190 (t (user-error "Cannot insert a fixed-width line here")))))
23191 ;; Region active.
23192 (let* ((begin (save-excursion
23193 (goto-char (region-beginning))
23194 (line-beginning-position)))
23195 (end (copy-marker
23196 (save-excursion
23197 (goto-char (region-end))
23198 (unless (eolp) (beginning-of-line))
23199 (if (save-excursion (re-search-backward "\\S-" begin t))
23200 (progn (skip-chars-backward " \r\t\n") (point))
23201 (point)))))
23202 (all-fixed-width-p
23203 (catch 'not-all-p
23204 (save-excursion
23205 (goto-char begin)
23206 (skip-chars-forward " \r\t\n")
23207 (when (eobp) (throw 'not-all-p nil))
23208 (while (< (point) end)
23209 (let ((element (org-element-at-point)))
23210 (if (eq (org-element-type element) 'fixed-width)
23211 (goto-char (org-element-property :end element))
23212 (throw 'not-all-p nil))))
23213 t))))
23214 (if all-fixed-width-p
23215 (save-excursion
23216 (goto-char begin)
23217 (while (< (point) end)
23218 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23219 (replace-match
23220 "" nil nil nil
23221 (if (= (line-end-position) (match-end 0)) 0 1)))
23222 (forward-line)))
23223 (let ((min-ind (point-max)))
23224 ;; Find minimum indentation across all lines.
23225 (save-excursion
23226 (goto-char begin)
23227 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23228 (setq min-ind 0)
23229 (catch 'zerop
23230 (while (< (point) end)
23231 (unless (org-looking-at-p "[ \t]*$")
23232 (let ((ind (org-get-indentation)))
23233 (setq min-ind (min min-ind ind))
23234 (when (zerop ind) (throw 'zerop t))))
23235 (forward-line)))))
23236 ;; Loop over all lines and add fixed-width markup everywhere
23237 ;; but in fixed-width lines.
23238 (save-excursion
23239 (goto-char begin)
23240 (while (< (point) end)
23241 (cond
23242 ((org-at-heading-p)
23243 (insert ": ")
23244 (forward-line)
23245 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23246 (insert ":")
23247 (forward-line)))
23248 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23249 (let* ((element (org-element-at-point))
23250 (element-end (org-element-property :end element)))
23251 (if (eq (org-element-type element) 'fixed-width)
23252 (progn (goto-char element-end)
23253 (skip-chars-backward " \r\t\n")
23254 (forward-line))
23255 (let ((limit (min end element-end)))
23256 (while (< (point) limit)
23257 (org-move-to-column min-ind t)
23258 (insert ": ")
23259 (forward-line))))))
23261 (org-move-to-column min-ind t)
23262 (insert ": ")
23263 (forward-line)))))))
23264 (set-marker end nil))))
23267 ;;; Comments
23269 ;; Org comments syntax is quite complex. It requires the entire line
23270 ;; to be just a comment. Also, even with the right syntax at the
23271 ;; beginning of line, some some elements (i.e. verse-block or
23272 ;; example-block) don't accept comments. Usual Emacs comment commands
23273 ;; cannot cope with those requirements. Therefore, Org replaces them.
23275 ;; Org still relies on `comment-dwim', but cannot trust
23276 ;; `comment-only-p'. So, `comment-region-function' and
23277 ;; `uncomment-region-function' both point
23278 ;; to`org-comment-or-uncomment-region'. Eventually,
23279 ;; `org-insert-comment' takes care of insertion of comments at the
23280 ;; beginning of line.
23282 ;; `org-setup-comments-handling' install comments related variables
23283 ;; during `org-mode' initialization.
23285 (defun org-setup-comments-handling ()
23286 (interactive)
23287 (org-set-local 'comment-use-syntax nil)
23288 (org-set-local 'comment-start "# ")
23289 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23290 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
23291 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
23292 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
23294 (defun org-insert-comment ()
23295 "Insert an empty comment above current line.
23296 If the line is empty, insert comment at its beginning. When
23297 point is within a source block, comment according to the related
23298 major mode."
23299 (if (let ((element (org-element-at-point)))
23300 (and (eq (org-element-type element) 'src-block)
23301 (< (save-excursion
23302 (goto-char (org-element-property :post-affiliated element))
23303 (line-end-position))
23304 (point))
23305 (> (save-excursion
23306 (goto-char (org-element-property :end element))
23307 (skip-chars-backward " \r\t\n")
23308 (line-beginning-position))
23309 (point))))
23310 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23311 (beginning-of-line)
23312 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23313 (open-line 1))
23314 (org-indent-line)
23315 (insert "# ")))
23317 (defvar comment-empty-lines) ; From newcomment.el.
23318 (defun org-comment-or-uncomment-region (beg end &rest ignore)
23319 "Comment or uncomment each non-blank line in the region.
23320 Uncomment each non-blank line between BEG and END if it only
23321 contains commented lines. Otherwise, comment them. If region is
23322 strictly within a source block, use appropriate comment syntax."
23323 (if (let ((element (org-element-at-point)))
23324 (and (eq (org-element-type element) 'src-block)
23325 (< (save-excursion
23326 (goto-char (org-element-property :post-affiliated element))
23327 (line-end-position))
23328 beg)
23329 (>= (save-excursion
23330 (goto-char (org-element-property :end element))
23331 (skip-chars-backward " \r\t\n")
23332 (line-beginning-position))
23333 end)))
23334 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23335 (save-restriction
23336 ;; Restrict region
23337 (narrow-to-region (save-excursion (goto-char beg)
23338 (skip-chars-forward " \r\t\n" end)
23339 (line-beginning-position))
23340 (save-excursion (goto-char end)
23341 (skip-chars-backward " \r\t\n" beg)
23342 (line-end-position)))
23343 (let ((uncommentp
23344 ;; UNCOMMENTP is non-nil when every non blank line between
23345 ;; BEG and END is a comment.
23346 (save-excursion
23347 (goto-char (point-min))
23348 (while (and (not (eobp))
23349 (let ((element (org-element-at-point)))
23350 (and (eq (org-element-type element) 'comment)
23351 (goto-char (min (point-max)
23352 (org-element-property
23353 :end element)))))))
23354 (eobp))))
23355 (if uncommentp
23356 ;; Only blank lines and comments in region: uncomment it.
23357 (save-excursion
23358 (goto-char (point-min))
23359 (while (not (eobp))
23360 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23361 (replace-match "" nil nil nil 1))
23362 (forward-line)))
23363 ;; Comment each line in region.
23364 (let ((min-indent (point-max)))
23365 ;; First find the minimum indentation across all lines.
23366 (save-excursion
23367 (goto-char (point-min))
23368 (while (and (not (eobp)) (not (zerop min-indent)))
23369 (unless (looking-at "[ \t]*$")
23370 (setq min-indent (min min-indent (current-indentation))))
23371 (forward-line)))
23372 ;; Then loop over all lines.
23373 (save-excursion
23374 (goto-char (point-min))
23375 (while (not (eobp))
23376 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23377 ;; Don't get fooled by invisible text (e.g. link path)
23378 ;; when moving to column MIN-INDENT.
23379 (let ((buffer-invisibility-spec nil))
23380 (org-move-to-column min-indent t))
23381 (insert comment-start))
23382 (forward-line)))))))))
23384 (defun org-comment-dwim (arg)
23385 "Call `comment-dwim' within a source edit buffer if needed."
23386 (interactive "*P")
23387 (if (org-in-src-block-p)
23388 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23389 (call-interactively 'comment-dwim)))
23392 ;;; Timestamps API
23394 ;; This section contains tools to operate on timestamp objects, as
23395 ;; returned by, e.g. `org-element-context'.
23397 (defun org-timestamp-has-time-p (timestamp)
23398 "Non-nil when TIMESTAMP has a time specified."
23399 (org-element-property :hour-start timestamp))
23401 (defun org-timestamp-format (timestamp format &optional end utc)
23402 "Format a TIMESTAMP element into a string.
23404 FORMAT is a format specifier to be passed to
23405 `format-time-string'.
23407 When optional argument END is non-nil, use end of date-range or
23408 time-range, if possible.
23410 When optional argument UTC is non-nil, time will be expressed as
23411 Universal Time."
23412 (format-time-string
23413 format
23414 (apply 'encode-time
23415 (cons 0
23416 (mapcar
23417 (lambda (prop) (or (org-element-property prop timestamp) 0))
23418 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23419 '(:minute-start :hour-start :day-start :month-start
23420 :year-start)))))
23421 utc))
23423 (defun org-timestamp-split-range (timestamp &optional end)
23424 "Extract a timestamp object from a date or time range.
23426 TIMESTAMP is a timestamp object. END, when non-nil, means extract
23427 the end of the range. Otherwise, extract its start.
23429 Return a new timestamp object sharing the same parent as
23430 TIMESTAMP."
23431 (let ((type (org-element-property :type timestamp)))
23432 (if (memq type '(active inactive diary)) timestamp
23433 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
23434 ;; Set new type.
23435 (org-element-put-property
23436 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23437 ;; Copy start properties over end properties if END is
23438 ;; non-nil. Otherwise, copy end properties over `start' ones.
23439 (let ((p-alist '((:minute-start . :minute-end)
23440 (:hour-start . :hour-end)
23441 (:day-start . :day-end)
23442 (:month-start . :month-end)
23443 (:year-start . :year-end))))
23444 (dolist (p-cell p-alist)
23445 (org-element-put-property
23446 split-ts
23447 (funcall (if end 'car 'cdr) p-cell)
23448 (org-element-property
23449 (funcall (if end 'cdr 'car) p-cell) split-ts)))
23450 ;; Eventually refresh `:raw-value'.
23451 (org-element-put-property split-ts :raw-value nil)
23452 (org-element-put-property
23453 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23455 (defun org-timestamp-translate (timestamp &optional boundary)
23456 "Translate TIMESTAMP object to custom format.
23458 Format string is defined in `org-time-stamp-custom-formats',
23459 which see.
23461 When optional argument BOUNDARY is non-nil, it is either the
23462 symbol `start' or `end'. In this case, only translate the
23463 starting or ending part of TIMESTAMP if it is a date or time
23464 range. Otherwise, translate both parts.
23466 Return timestamp as-is if `org-display-custom-times' is nil or if
23467 it has a `diary' type."
23468 (let ((type (org-element-property :type timestamp)))
23469 (if (or (not org-display-custom-times) (eq type 'diary))
23470 (org-element-interpret-data timestamp)
23471 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23472 org-time-stamp-custom-formats)))
23473 (if (and (not boundary) (memq type '(active-range inactive-range)))
23474 (concat (org-timestamp-format timestamp fmt)
23475 "--"
23476 (org-timestamp-format timestamp fmt t))
23477 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23481 ;;; Other stuff.
23483 (defun org-reftex-citation ()
23484 "Use reftex-citation to insert a citation into the buffer.
23485 This looks for a line like
23487 #+BIBLIOGRAPHY: foo plain option:-d
23489 and derives from it that foo.bib is the bibliography file relevant
23490 for this document. It then installs the necessary environment for RefTeX
23491 to work in this buffer and calls `reftex-citation' to insert a citation
23492 into the buffer.
23494 Export of such citations to both LaTeX and HTML is handled by the contributed
23495 package ox-bibtex by Taru Karttunen."
23496 (interactive)
23497 (let ((reftex-docstruct-symbol 'rds)
23498 (reftex-cite-format "\\cite{%l}")
23499 rds bib)
23500 (save-excursion
23501 (save-restriction
23502 (widen)
23503 (let ((case-fold-search t)
23504 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23505 (if (not (save-excursion
23506 (or (re-search-forward re nil t)
23507 (re-search-backward re nil t))))
23508 (user-error "No bibliography defined in file")
23509 (setq bib (concat (match-string 1) ".bib")
23510 rds (list (list 'bib bib)))))))
23511 (call-interactively 'reftex-citation)))
23513 ;;;; Functions extending outline functionality
23515 (defun org-beginning-of-line (&optional arg)
23516 "Go to the beginning of the current line. If that is invisible, continue
23517 to a visible line beginning. This makes the function of C-a more intuitive.
23518 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23519 first attempt, and only move to after the tags when the cursor is already
23520 beyond the end of the headline."
23521 (interactive "P")
23522 (let ((pos (point))
23523 (special (if (consp org-special-ctrl-a/e)
23524 (car org-special-ctrl-a/e)
23525 org-special-ctrl-a/e))
23526 deactivate-mark refpos)
23527 (if (org-bound-and-true-p visual-line-mode)
23528 (beginning-of-visual-line 1)
23529 (beginning-of-line 1))
23530 (if (and arg (fboundp 'move-beginning-of-line))
23531 (call-interactively 'move-beginning-of-line)
23532 (if (bobp)
23534 (backward-char 1)
23535 (if (org-truely-invisible-p)
23536 (while (and (not (bobp)) (org-truely-invisible-p))
23537 (backward-char 1)
23538 (beginning-of-line 1))
23539 (forward-char 1))))
23540 (when special
23541 (cond
23542 ((and (looking-at org-complex-heading-regexp)
23543 (= (char-after (match-end 1)) ?\ ))
23544 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23545 (point-at-eol)))
23546 (goto-char
23547 (if (eq special t)
23548 (cond ((> pos refpos) refpos)
23549 ((= pos (point)) refpos)
23550 (t (point)))
23551 (cond ((> pos (point)) (point))
23552 ((not (eq last-command this-command)) (point))
23553 (t refpos)))))
23554 ((org-at-item-p)
23555 ;; Being at an item and not looking at an the item means point
23556 ;; was previously moved to beginning of a visual line, which
23557 ;; doesn't contain the item. Therefore, do nothing special,
23558 ;; just stay here.
23559 (when (looking-at org-list-full-item-re)
23560 ;; Set special position at first white space character after
23561 ;; bullet, and check-box, if any.
23562 (let ((after-bullet
23563 (let ((box (match-end 3)))
23564 (if (not box) (match-end 1)
23565 (let ((after (char-after box)))
23566 (if (and after (= after ? )) (1+ box) box))))))
23567 ;; Special case: Move point to special position when
23568 ;; currently after it or at beginning of line.
23569 (if (eq special t)
23570 (when (or (> pos after-bullet) (= (point) pos))
23571 (goto-char after-bullet))
23572 ;; Reversed case: Move point to special position when
23573 ;; point was already at beginning of line and command is
23574 ;; repeated.
23575 (when (and (= (point) pos) (eq last-command this-command))
23576 (goto-char after-bullet))))))))
23577 (org-no-warnings
23578 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23579 (setq disable-point-adjustment
23580 (or (not (invisible-p (point)))
23581 (not (invisible-p (max (point-min) (1- (point))))))))
23583 (defun org-end-of-line (&optional arg)
23584 "Go to the end of the line.
23585 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23586 tags on the first attempt, and only move to after the tags when
23587 the cursor is already beyond the end of the headline."
23588 (interactive "P")
23589 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23590 org-special-ctrl-a/e))
23591 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23592 'end-of-visual-line)
23593 ((fboundp 'move-end-of-line) 'move-end-of-line)
23594 (t 'end-of-line)))
23595 deactivate-mark)
23596 (if (or (not special) arg) (call-interactively move-fun)
23597 (let* ((element (save-excursion (beginning-of-line)
23598 (org-element-at-point)))
23599 (type (org-element-type element)))
23600 (cond
23601 ((memq type '(headline inlinetask))
23602 (let ((pos (point)))
23603 (beginning-of-line 1)
23604 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23605 (if (eq special t)
23606 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23607 (goto-char (match-beginning 1))
23608 (goto-char (match-end 0)))
23609 (if (or (< pos (match-end 0))
23610 (not (eq this-command last-command)))
23611 (goto-char (match-end 0))
23612 (goto-char (match-beginning 1))))
23613 (call-interactively move-fun))))
23614 ((outline-invisible-p (line-end-position))
23615 ;; If element is hidden, `move-end-of-line' would put point
23616 ;; after it. Use `end-of-line' to stay on current line.
23617 (call-interactively 'end-of-line))
23618 (t (call-interactively move-fun)))))
23619 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23620 (setq disable-point-adjustment
23621 (or (not (invisible-p (point)))
23622 (not (invisible-p (max (point-min) (1- (point))))))))
23624 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23625 (define-key org-mode-map "\C-e" 'org-end-of-line)
23627 (defun org-backward-sentence (&optional arg)
23628 "Go to beginning of sentence, or beginning of table field.
23629 This will call `backward-sentence' or `org-table-beginning-of-field',
23630 depending on context."
23631 (interactive "P")
23632 (cond
23633 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
23634 (t (call-interactively 'backward-sentence))))
23636 (defun org-forward-sentence (&optional arg)
23637 "Go to end of sentence, or end of table field.
23638 This will call `forward-sentence' or `org-table-end-of-field',
23639 depending on context."
23640 (interactive "P")
23641 (cond
23642 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23643 (t (call-interactively 'forward-sentence))))
23645 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23646 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23648 (defun org-kill-line (&optional arg)
23649 "Kill line, to tags or end of line."
23650 (interactive "P")
23651 (cond
23652 ((or (not org-special-ctrl-k)
23653 (bolp)
23654 (not (org-at-heading-p)))
23655 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23656 org-ctrl-k-protect-subtree)
23657 (if (or (eq org-ctrl-k-protect-subtree 'error)
23658 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23659 (user-error "C-k aborted as it would kill a hidden subtree")))
23660 (call-interactively
23661 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23662 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23663 (kill-region (point) (match-beginning 1))
23664 (org-set-tags nil t))
23665 (t (kill-region (point) (point-at-eol)))))
23667 (define-key org-mode-map "\C-k" 'org-kill-line)
23669 (defun org-yank (&optional arg)
23670 "Yank. If the kill is a subtree, treat it specially.
23671 This command will look at the current kill and check if is a single
23672 subtree, or a series of subtrees[1]. If it passes the test, and if the
23673 cursor is at the beginning of a line or after the stars of a currently
23674 empty headline, then the yank is handled specially. How exactly depends
23675 on the value of the following variables, both set by default.
23677 `org-yank-folded-subtrees'
23678 When set, the subtree(s) will be folded after insertion, but only
23679 if doing so would now swallow text after the yanked text.
23681 `org-yank-adjusted-subtrees'
23682 When set, the subtree will be promoted or demoted in order to
23683 fit into the local outline tree structure, which means that the
23684 level will be adjusted so that it becomes the smaller one of the
23685 two *visible* surrounding headings.
23687 Any prefix to this command will cause `yank' to be called directly with
23688 no special treatment. In particular, a simple \\[universal-argument] prefix \
23689 will just
23690 plainly yank the text as it is.
23692 \[1] The test checks if the first non-white line is a heading
23693 and if there are no other headings with fewer stars."
23694 (interactive "P")
23695 (org-yank-generic 'yank arg))
23697 (defun org-yank-generic (command arg)
23698 "Perform some yank-like command.
23700 This function implements the behavior described in the `org-yank'
23701 documentation. However, it has been generalized to work for any
23702 interactive command with similar behavior."
23704 ;; pretend to be command COMMAND
23705 (setq this-command command)
23707 (if arg
23708 (call-interactively command)
23710 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23711 (and (org-kill-is-subtree-p)
23712 (or (bolp)
23713 (and (looking-at "[ \t]*$")
23714 (string-match
23715 "\\`\\*+\\'"
23716 (buffer-substring (point-at-bol) (point)))))))
23717 swallowp)
23718 (cond
23719 ((and subtreep org-yank-folded-subtrees)
23720 (let ((beg (point))
23721 end)
23722 (if (and subtreep org-yank-adjusted-subtrees)
23723 (org-paste-subtree nil nil 'for-yank)
23724 (call-interactively command))
23726 (setq end (point))
23727 (goto-char beg)
23728 (when (and (bolp) subtreep
23729 (not (setq swallowp
23730 (org-yank-folding-would-swallow-text beg end))))
23731 (org-with-limited-levels
23732 (or (looking-at org-outline-regexp)
23733 (re-search-forward org-outline-regexp-bol end t))
23734 (while (and (< (point) end) (looking-at org-outline-regexp))
23735 (hide-subtree)
23736 (org-cycle-show-empty-lines 'folded)
23737 (condition-case nil
23738 (outline-forward-same-level 1)
23739 (error (goto-char end))))))
23740 (when swallowp
23741 (message
23742 "Inserted text not folded because that would swallow text"))
23744 (goto-char end)
23745 (skip-chars-forward " \t\n\r")
23746 (beginning-of-line 1)
23747 (push-mark beg 'nomsg)))
23748 ((and subtreep org-yank-adjusted-subtrees)
23749 (let ((beg (point-at-bol)))
23750 (org-paste-subtree nil nil 'for-yank)
23751 (push-mark beg 'nomsg)))
23753 (call-interactively command))))))
23755 (defun org-yank-folding-would-swallow-text (beg end)
23756 "Would hide-subtree at BEG swallow any text after END?"
23757 (let (level)
23758 (org-with-limited-levels
23759 (save-excursion
23760 (goto-char beg)
23761 (when (or (looking-at org-outline-regexp)
23762 (re-search-forward org-outline-regexp-bol end t))
23763 (setq level (org-outline-level)))
23764 (goto-char end)
23765 (skip-chars-forward " \t\r\n\v\f")
23766 (if (or (eobp)
23767 (and (bolp) (looking-at org-outline-regexp)
23768 (<= (org-outline-level) level)))
23769 nil ; Nothing would be swallowed
23770 t))))) ; something would swallow
23772 (define-key org-mode-map "\C-y" 'org-yank)
23774 (defun org-truely-invisible-p ()
23775 "Check if point is at a character currently not visible.
23776 This version does not only check the character property, but also
23777 `visible-mode'."
23778 ;; Early versions of noutline don't have `outline-invisible-p'.
23779 (if (org-bound-and-true-p visible-mode)
23781 (outline-invisible-p)))
23783 (defun org-invisible-p2 ()
23784 "Check if point is at a character currently not visible."
23785 (save-excursion
23786 (if (and (eolp) (not (bobp))) (backward-char 1))
23787 ;; Early versions of noutline don't have `outline-invisible-p'.
23788 (outline-invisible-p)))
23790 (defun org-back-to-heading (&optional invisible-ok)
23791 "Call `outline-back-to-heading', but provide a better error message."
23792 (condition-case nil
23793 (outline-back-to-heading invisible-ok)
23794 (error (error "Before first headline at position %d in buffer %s"
23795 (point) (current-buffer)))))
23797 (defun org-before-first-heading-p ()
23798 "Before first heading?"
23799 (save-excursion
23800 (end-of-line)
23801 (null (re-search-backward org-outline-regexp-bol nil t))))
23803 (defun org-at-heading-p (&optional ignored)
23804 (outline-on-heading-p t))
23805 ;; Compatibility alias with Org versions < 7.8.03
23806 (defalias 'org-on-heading-p 'org-at-heading-p)
23808 (defun org-in-commented-heading-p (&optional no-inheritance)
23809 "Non-nil if point is under a commented heading.
23810 This function also checks ancestors of the current headline,
23811 unless optional argument NO-INHERITANCE is non-nil."
23812 (cond
23813 ((org-before-first-heading-p) nil)
23814 ((let ((headline (nth 4 (org-heading-components))))
23815 (and headline
23816 (let ((case-fold-search nil))
23817 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23818 headline)))))
23819 (no-inheritance nil)
23821 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23823 (defun org-at-comment-p nil
23824 "Is cursor in a commented line?"
23825 (save-excursion
23826 (save-match-data
23827 (beginning-of-line)
23828 (looking-at "^[ \t]*# "))))
23830 (defun org-at-drawer-p nil
23831 "Is cursor at a drawer keyword?"
23832 (save-excursion
23833 (move-beginning-of-line 1)
23834 (looking-at org-drawer-regexp)))
23836 (defun org-at-block-p nil
23837 "Is cursor at a block keyword?"
23838 (save-excursion
23839 (move-beginning-of-line 1)
23840 (looking-at org-block-regexp)))
23842 (defun org-point-at-end-of-empty-headline ()
23843 "If point is at the end of an empty headline, return t, else nil.
23844 If the heading only contains a TODO keyword, it is still still considered
23845 empty."
23846 (and (looking-at "[ \t]*$")
23847 (when org-todo-line-regexp
23848 (save-excursion
23849 (beginning-of-line 1)
23850 (let ((case-fold-search nil))
23851 (looking-at org-todo-line-regexp)
23852 (string= (match-string 3) ""))))))
23854 (defun org-at-heading-or-item-p ()
23855 (or (org-at-heading-p) (org-at-item-p)))
23857 (defun org-at-target-p ()
23858 (or (org-in-regexp org-radio-target-regexp)
23859 (org-in-regexp org-target-regexp)))
23860 ;; Compatibility alias with Org versions < 7.8.03
23861 (defalias 'org-on-target-p 'org-at-target-p)
23863 (defun org-up-heading-all (arg)
23864 "Move to the heading line of which the present line is a subheading.
23865 This function considers both visible and invisible heading lines.
23866 With argument, move up ARG levels."
23867 (if (fboundp 'outline-up-heading-all)
23868 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23869 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23871 (defun org-up-heading-safe ()
23872 "Move to the heading line of which the present line is a subheading.
23873 This version will not throw an error. It will return the level of the
23874 headline found, or nil if no higher level is found.
23876 Also, this function will be a lot faster than `outline-up-heading',
23877 because it relies on stars being the outline starters. This can really
23878 make a significant difference in outlines with very many siblings."
23879 (when (ignore-errors (org-back-to-heading t))
23880 (let ((level-up (1- (funcall outline-level))))
23881 (and (> level-up 0)
23882 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23883 (funcall outline-level)))))
23885 (defun org-first-sibling-p ()
23886 "Is this heading the first child of its parents?"
23887 (interactive)
23888 (let ((re org-outline-regexp-bol)
23889 level l)
23890 (unless (org-at-heading-p t)
23891 (user-error "Not at a heading"))
23892 (setq level (funcall outline-level))
23893 (save-excursion
23894 (if (not (re-search-backward re nil t))
23896 (setq l (funcall outline-level))
23897 (< l level)))))
23899 (defun org-goto-sibling (&optional previous)
23900 "Goto the next sibling, even if it is invisible.
23901 When PREVIOUS is set, go to the previous sibling instead. Returns t
23902 when a sibling was found. When none is found, return nil and don't
23903 move point."
23904 (let ((fun (if previous 're-search-backward 're-search-forward))
23905 (pos (point))
23906 (re org-outline-regexp-bol)
23907 level l)
23908 (when (ignore-errors (org-back-to-heading t))
23909 (setq level (funcall outline-level))
23910 (catch 'exit
23911 (or previous (forward-char 1))
23912 (while (funcall fun re nil t)
23913 (setq l (funcall outline-level))
23914 (when (< l level) (goto-char pos) (throw 'exit nil))
23915 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23916 (goto-char pos)
23917 nil))))
23919 (defun org-show-siblings ()
23920 "Show all siblings of the current headline."
23921 (save-excursion
23922 (while (org-goto-sibling) (org-flag-heading nil)))
23923 (save-excursion
23924 (while (org-goto-sibling 'previous)
23925 (org-flag-heading nil))))
23927 (defun org-goto-first-child ()
23928 "Goto the first child, even if it is invisible.
23929 Return t when a child was found. Otherwise don't move point and
23930 return nil."
23931 (let (level (pos (point)) (re org-outline-regexp-bol))
23932 (when (ignore-errors (org-back-to-heading t))
23933 (setq level (outline-level))
23934 (forward-char 1)
23935 (if (and (re-search-forward re nil t) (> (outline-level) level))
23936 (progn (goto-char (match-beginning 0)) t)
23937 (goto-char pos) nil))))
23939 (defun org-show-hidden-entry ()
23940 "Show an entry where even the heading is hidden."
23941 (save-excursion
23942 (org-show-entry)))
23944 (defun org-flag-heading (flag &optional entry)
23945 "Flag the current heading. FLAG non-nil means make invisible.
23946 When ENTRY is non-nil, show the entire entry."
23947 (save-excursion
23948 (org-back-to-heading t)
23949 ;; Check if we should show the entire entry
23950 (if entry
23951 (progn
23952 (org-show-entry)
23953 (save-excursion
23954 (and (outline-next-heading)
23955 (org-flag-heading nil))))
23956 (outline-flag-region (max (point-min) (1- (point)))
23957 (save-excursion (outline-end-of-heading) (point))
23958 flag))))
23960 (defun org-get-next-sibling ()
23961 "Move to next heading of the same level, and return point.
23962 If there is no such heading, return nil.
23963 This is like outline-next-sibling, but invisible headings are ok."
23964 (let ((level (funcall outline-level)))
23965 (outline-next-heading)
23966 (while (and (not (eobp)) (> (funcall outline-level) level))
23967 (outline-next-heading))
23968 (if (or (eobp) (< (funcall outline-level) level))
23970 (point))))
23972 (defun org-get-last-sibling ()
23973 "Move to previous heading of the same level, and return point.
23974 If there is no such heading, return nil."
23975 (let ((opoint (point))
23976 (level (funcall outline-level)))
23977 (outline-previous-heading)
23978 (when (and (/= (point) opoint) (outline-on-heading-p t))
23979 (while (and (> (funcall outline-level) level)
23980 (not (bobp)))
23981 (outline-previous-heading))
23982 (if (< (funcall outline-level) level)
23984 (point)))))
23986 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23987 "Goto to the end of a subtree."
23988 ;; This contains an exact copy of the original function, but it uses
23989 ;; `org-back-to-heading', to make it work also in invisible
23990 ;; trees. And is uses an invisible-ok argument.
23991 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23992 ;; Furthermore, when used inside Org, finding the end of a large subtree
23993 ;; with many children and grandchildren etc, this can be much faster
23994 ;; than the outline version.
23995 (org-back-to-heading invisible-ok)
23996 (let ((first t)
23997 (level (funcall outline-level)))
23998 (if (and (derived-mode-p 'org-mode) (< level 1000))
23999 ;; A true heading (not a plain list item), in Org-mode
24000 ;; This means we can easily find the end by looking
24001 ;; only for the right number of stars. Using a regexp to do
24002 ;; this is so much faster than using a Lisp loop.
24003 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24004 (forward-char 1)
24005 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24006 ;; something else, do it the slow way
24007 (while (and (not (eobp))
24008 (or first (> (funcall outline-level) level)))
24009 (setq first nil)
24010 (outline-next-heading)))
24011 (unless to-heading
24012 (if (memq (preceding-char) '(?\n ?\^M))
24013 (progn
24014 ;; Go to end of line before heading
24015 (forward-char -1)
24016 (if (memq (preceding-char) '(?\n ?\^M))
24017 ;; leave blank line before heading
24018 (forward-char -1))))))
24019 (point))
24021 (defun org-end-of-meta-data-and-drawers ()
24022 "Jump to the first text after meta data and drawers in the current entry.
24023 This will move over empty lines, lines with planning time stamps,
24024 clocking lines, and drawers."
24025 (org-back-to-heading t)
24026 (let ((end (save-excursion (outline-next-heading) (point)))
24027 (re (concat "\\(" org-drawer-regexp "\\)"
24028 "\\|" "[ \t]*" org-keyword-time-regexp)))
24029 (forward-line 1)
24030 (while (re-search-forward re end t)
24031 (if (not (match-end 1))
24032 ;; empty or planning line
24033 (forward-line 1)
24034 ;; a drawer, find the end
24035 (re-search-forward "^[ \t]*:END:" end 'move)
24036 (forward-line 1)))
24037 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
24038 (point)))
24040 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24041 "Move forward to the ARG'th subheading at same level as this one.
24042 Stop at the first and last subheadings of a superior heading.
24043 Normally this only looks at visible headings, but when INVISIBLE-OK is
24044 non-nil it will also look at invisible ones."
24045 (interactive "p")
24046 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24047 (if (and arg (< arg 0))
24048 (goto-char (point-min))
24049 (outline-next-heading))
24050 (org-at-heading-p)
24051 (let ((level (- (match-end 0) (match-beginning 0) 1))
24052 (f (if (and arg (< arg 0))
24053 're-search-backward
24054 're-search-forward))
24055 (count (if arg (abs arg) 1))
24056 (result (point)))
24057 (while (and (prog1 (> count 0)
24058 (forward-char (if (and arg (< arg 0)) -1 1)))
24059 (funcall f org-outline-regexp-bol nil 'move))
24060 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24061 (cond ((< l level) (setq count 0))
24062 ((and (= l level)
24063 (or invisible-ok
24064 (progn
24065 (goto-char (line-beginning-position))
24066 (not (outline-invisible-p)))))
24067 (setq count (1- count))
24068 (when (eq l level)
24069 (setq result (point)))))))
24070 (goto-char result))
24071 (beginning-of-line 1)))
24073 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24074 "Move backward to the ARG'th subheading at same level as this one.
24075 Stop at the first and last subheadings of a superior heading."
24076 (interactive "p")
24077 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24079 (defun org-next-visible-heading (arg)
24080 "Move to the next visible heading.
24082 This function wraps `outline-next-visible-heading' with
24083 `org-with-limited-levels' in order to skip over inline tasks and
24084 respect customization of `org-odd-levels-only'."
24085 (interactive "p")
24086 (org-with-limited-levels
24087 (outline-next-visible-heading arg)))
24089 (defun org-previous-visible-heading (arg)
24090 "Move to the next visible heading.
24092 This function wraps `outline-previous-visible-heading' with
24093 `org-with-limited-levels' in order to skip over inline tasks and
24094 respect customization of `org-odd-levels-only'."
24095 (interactive "p")
24096 (org-with-limited-levels
24097 (outline-previous-visible-heading arg)))
24099 (defun org-next-block (arg &optional backward block-regexp)
24100 "Jump to the next block.
24101 With a prefix argument ARG, jump forward ARG many source blocks.
24102 When BACKWARD is non-nil, jump to the previous block.
24103 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24104 (interactive "p")
24105 (let ((re (or block-regexp org-block-regexp))
24106 (re-search-fn (or (and backward 're-search-backward)
24107 're-search-forward)))
24108 (if (looking-at re) (forward-char 1))
24109 (condition-case nil
24110 (funcall re-search-fn re nil nil arg)
24111 (error (user-error "No %s code blocks"
24112 (if backward "previous" "further" ))))
24113 (goto-char (match-beginning 0)) (org-show-context)))
24115 (defun org-previous-block (arg &optional block-regexp)
24116 "Jump to the previous block.
24117 With a prefix argument ARG, jump backward ARG many source blocks.
24118 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24119 (interactive "p")
24120 (org-next-block arg t block-regexp))
24122 (defun org-forward-paragraph ()
24123 "Move forward to beginning of next paragraph or equivalent.
24125 The function moves point to the beginning of the next visible
24126 structural element, which can be a paragraph, a table, a list
24127 item, etc. It also provides some special moves for convenience:
24129 - On an affiliated keyword, jump to the beginning of the
24130 relative element.
24131 - On an item or a footnote definition, move to the second
24132 element inside, if any.
24133 - On a table or a property drawer, jump after it.
24134 - On a verse or source block, stop after blank lines."
24135 (interactive)
24136 (when (eobp) (user-error "Cannot move further down"))
24137 (let* ((deactivate-mark nil)
24138 (element (org-element-at-point))
24139 (type (org-element-type element))
24140 (post-affiliated (org-element-property :post-affiliated element))
24141 (contents-begin (org-element-property :contents-begin element))
24142 (contents-end (org-element-property :contents-end element))
24143 (end (let ((end (org-element-property :end element)) (parent element))
24144 (while (and (setq parent (org-element-property :parent parent))
24145 (= (org-element-property :contents-end parent) end))
24146 (setq end (org-element-property :end parent)))
24147 end)))
24148 (cond ((not element)
24149 (skip-chars-forward " \r\t\n")
24150 (or (eobp) (beginning-of-line)))
24151 ;; On affiliated keywords, move to element's beginning.
24152 ((< (point) post-affiliated)
24153 (goto-char post-affiliated))
24154 ;; At a table row, move to the end of the table. Similarly,
24155 ;; at a node property, move to the end of the property
24156 ;; drawer.
24157 ((memq type '(node-property table-row))
24158 (goto-char (org-element-property
24159 :end (org-element-property :parent element))))
24160 ((memq type '(property-drawer table)) (goto-char end))
24161 ;; Consider blank lines as separators in verse and source
24162 ;; blocks to ease editing.
24163 ((memq type '(src-block verse-block))
24164 (when (eq type 'src-block)
24165 (setq contents-end
24166 (save-excursion (goto-char end)
24167 (skip-chars-backward " \r\t\n")
24168 (line-beginning-position))))
24169 (beginning-of-line)
24170 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24171 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24172 (goto-char end)
24173 (skip-chars-forward " \r\t\n")
24174 (if (= (point) contents-end) (goto-char end)
24175 (beginning-of-line))))
24176 ;; With no contents, just skip element.
24177 ((not contents-begin) (goto-char end))
24178 ;; If contents are invisible, skip the element altogether.
24179 ((outline-invisible-p (line-end-position))
24180 (case type
24181 (headline
24182 (org-with-limited-levels (outline-next-visible-heading 1)))
24183 ;; At a plain list, make sure we move to the next item
24184 ;; instead of skipping the whole list.
24185 (plain-list (forward-char)
24186 (org-forward-paragraph))
24187 (otherwise (goto-char end))))
24188 ((>= (point) contents-end) (goto-char end))
24189 ((>= (point) contents-begin)
24190 ;; This can only happen on paragraphs and plain lists.
24191 (case type
24192 (paragraph (goto-char end))
24193 ;; At a plain list, try to move to second element in
24194 ;; first item, if possible.
24195 (plain-list (end-of-line)
24196 (org-forward-paragraph))))
24197 ;; When contents start on the middle of a line (e.g. in
24198 ;; items and footnote definitions), try to reach first
24199 ;; element starting after current line.
24200 ((> (line-end-position) contents-begin)
24201 (end-of-line)
24202 (org-forward-paragraph))
24203 (t (goto-char contents-begin)))))
24205 (defun org-backward-paragraph ()
24206 "Move backward to start of previous paragraph or equivalent.
24208 The function moves point to the beginning of the current
24209 structural element, which can be a paragraph, a table, a list
24210 item, etc., or to the beginning of the previous visible one if
24211 point is already there. It also provides some special moves for
24212 convenience:
24214 - On an affiliated keyword, jump to the first one.
24215 - On a table or a property drawer, move to its beginning.
24216 - On a verse or source block, stop before blank lines."
24217 (interactive)
24218 (when (bobp) (user-error "Cannot move further up"))
24219 (let* ((deactivate-mark nil)
24220 (element (org-element-at-point))
24221 (type (org-element-type element))
24222 (contents-begin (org-element-property :contents-begin element))
24223 (contents-end (org-element-property :contents-end element))
24224 (post-affiliated (org-element-property :post-affiliated element))
24225 (begin (org-element-property :begin element)))
24226 (cond
24227 ((not element) (goto-char (point-min)))
24228 ((= (point) begin)
24229 (backward-char)
24230 (org-backward-paragraph))
24231 ((<= (point) post-affiliated) (goto-char begin))
24232 ((memq type '(node-property table-row))
24233 (goto-char (org-element-property
24234 :post-affiliated (org-element-property :parent element))))
24235 ((memq type '(property-drawer table)) (goto-char begin))
24236 ((memq type '(src-block verse-block))
24237 (when (eq type 'src-block)
24238 (setq contents-begin
24239 (save-excursion (goto-char begin) (forward-line) (point))))
24240 (if (= (point) contents-begin) (goto-char post-affiliated)
24241 ;; Inside a verse block, see blank lines as paragraph
24242 ;; separators.
24243 (let ((origin (point)))
24244 (skip-chars-backward " \r\t\n" contents-begin)
24245 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24246 (skip-chars-forward " \r\t\n" origin)
24247 (if (= (point) origin) (goto-char contents-begin)
24248 (beginning-of-line))))))
24249 ((not contents-begin) (goto-char (or post-affiliated begin)))
24250 ((eq type 'paragraph)
24251 (goto-char contents-begin)
24252 ;; When at first paragraph in an item or a footnote definition,
24253 ;; move directly to beginning of line.
24254 (let ((parent-contents
24255 (org-element-property
24256 :contents-begin (org-element-property :parent element))))
24257 (when (and parent-contents (= parent-contents contents-begin))
24258 (beginning-of-line))))
24259 ;; At the end of a greater element, move to the beginning of the
24260 ;; last element within.
24261 ((>= (point) contents-end)
24262 (goto-char (1- contents-end))
24263 (org-backward-paragraph))
24264 (t (goto-char (or post-affiliated begin))))
24265 ;; Ensure we never leave point invisible.
24266 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24268 (defun org-forward-element ()
24269 "Move forward by one element.
24270 Move to the next element at the same level, when possible."
24271 (interactive)
24272 (cond ((eobp) (user-error "Cannot move further down"))
24273 ((org-with-limited-levels (org-at-heading-p))
24274 (let ((origin (point)))
24275 (goto-char (org-end-of-subtree nil t))
24276 (unless (org-with-limited-levels (org-at-heading-p))
24277 (goto-char origin)
24278 (user-error "Cannot move further down"))))
24280 (let* ((elem (org-element-at-point))
24281 (end (org-element-property :end elem))
24282 (parent (org-element-property :parent elem)))
24283 (cond ((and parent (= (org-element-property :contents-end parent) end))
24284 (goto-char (org-element-property :end parent)))
24285 ((integer-or-marker-p end) (goto-char end))
24286 (t (message "No element at point")))))))
24288 (defun org-backward-element ()
24289 "Move backward by one element.
24290 Move to the previous element at the same level, when possible."
24291 (interactive)
24292 (cond ((bobp) (user-error "Cannot move further up"))
24293 ((org-with-limited-levels (org-at-heading-p))
24294 ;; At a headline, move to the previous one, if any, or stay
24295 ;; here.
24296 (let ((origin (point)))
24297 (org-with-limited-levels (org-backward-heading-same-level 1))
24298 ;; When current headline has no sibling above, move to its
24299 ;; parent.
24300 (when (= (point) origin)
24301 (or (org-with-limited-levels (org-up-heading-safe))
24302 (progn (goto-char origin)
24303 (user-error "Cannot move further up"))))))
24305 (let* ((elem (org-element-at-point))
24306 (beg (org-element-property :begin elem)))
24307 (cond
24308 ;; Move to beginning of current element if point isn't
24309 ;; there already.
24310 ((null beg) (message "No element at point"))
24311 ((/= (point) beg) (goto-char beg))
24312 (t (goto-char beg)
24313 (skip-chars-backward " \r\t\n")
24314 (unless (bobp)
24315 (let ((prev (org-element-at-point)))
24316 (goto-char (org-element-property :begin prev))
24317 (while (and (setq prev (org-element-property :parent prev))
24318 (<= (org-element-property :end prev) beg))
24319 (goto-char (org-element-property :begin prev)))))))))))
24321 (defun org-up-element ()
24322 "Move to upper element."
24323 (interactive)
24324 (if (org-with-limited-levels (org-at-heading-p))
24325 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24326 (let* ((elem (org-element-at-point))
24327 (parent (org-element-property :parent elem)))
24328 (if parent (goto-char (org-element-property :begin parent))
24329 (if (org-with-limited-levels (org-before-first-heading-p))
24330 (user-error "No surrounding element")
24331 (org-with-limited-levels (org-back-to-heading)))))))
24333 (defvar org-element-greater-elements)
24334 (defun org-down-element ()
24335 "Move to inner element."
24336 (interactive)
24337 (let ((element (org-element-at-point)))
24338 (cond
24339 ((memq (org-element-type element) '(plain-list table))
24340 (goto-char (org-element-property :contents-begin element))
24341 (forward-char))
24342 ((memq (org-element-type element) org-element-greater-elements)
24343 ;; If contents are hidden, first disclose them.
24344 (when (outline-invisible-p (line-end-position)) (org-cycle))
24345 (goto-char (or (org-element-property :contents-begin element)
24346 (user-error "No content for this element"))))
24347 (t (user-error "No inner element")))))
24349 (defun org-drag-element-backward ()
24350 "Move backward element at point."
24351 (interactive)
24352 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24353 (let* ((elem (org-element-at-point))
24354 (prev-elem
24355 (save-excursion
24356 (goto-char (org-element-property :begin elem))
24357 (skip-chars-backward " \r\t\n")
24358 (unless (bobp)
24359 (let* ((beg (org-element-property :begin elem))
24360 (prev (org-element-at-point))
24361 (up prev))
24362 (while (and (setq up (org-element-property :parent up))
24363 (<= (org-element-property :end up) beg))
24364 (setq prev up))
24365 prev)))))
24366 ;; Error out if no previous element or previous element is
24367 ;; a parent of the current one.
24368 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24369 (user-error "Cannot drag element backward")
24370 (let ((pos (point)))
24371 (org-element-swap-A-B prev-elem elem)
24372 (goto-char (+ (org-element-property :begin prev-elem)
24373 (- pos (org-element-property :begin elem)))))))))
24375 (defun org-drag-element-forward ()
24376 "Move forward element at point."
24377 (interactive)
24378 (let* ((pos (point))
24379 (elem (org-element-at-point)))
24380 (when (= (point-max) (org-element-property :end elem))
24381 (user-error "Cannot drag element forward"))
24382 (goto-char (org-element-property :end elem))
24383 (let ((next-elem (org-element-at-point)))
24384 (when (or (org-element-nested-p elem next-elem)
24385 (and (eq (org-element-type next-elem) 'headline)
24386 (not (eq (org-element-type elem) 'headline))))
24387 (goto-char pos)
24388 (user-error "Cannot drag element forward"))
24389 ;; Compute new position of point: it's shifted by NEXT-ELEM
24390 ;; body's length (without final blanks) and by the length of
24391 ;; blanks between ELEM and NEXT-ELEM.
24392 (let ((size-next (- (save-excursion
24393 (goto-char (org-element-property :end next-elem))
24394 (skip-chars-backward " \r\t\n")
24395 (forward-line)
24396 ;; Small correction if buffer doesn't end
24397 ;; with a newline character.
24398 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24399 (org-element-property :begin next-elem)))
24400 (size-blank (- (org-element-property :end elem)
24401 (save-excursion
24402 (goto-char (org-element-property :end elem))
24403 (skip-chars-backward " \r\t\n")
24404 (forward-line)
24405 (point)))))
24406 (org-element-swap-A-B elem next-elem)
24407 (goto-char (+ pos size-next size-blank))))))
24409 (defun org-drag-line-forward (arg)
24410 "Drag the line at point ARG lines forward."
24411 (interactive "p")
24412 (dotimes (n (abs arg))
24413 (let ((c (current-column)))
24414 (if (< 0 arg)
24415 (progn
24416 (beginning-of-line 2)
24417 (transpose-lines 1)
24418 (beginning-of-line 0))
24419 (transpose-lines 1)
24420 (beginning-of-line -1))
24421 (org-move-to-column c))))
24423 (defun org-drag-line-backward (arg)
24424 "Drag the line at point ARG lines backward."
24425 (interactive "p")
24426 (org-drag-line-forward (- arg)))
24428 (defun org-mark-element ()
24429 "Put point at beginning of this element, mark at end.
24431 Interactively, if this command is repeated or (in Transient Mark
24432 mode) if the mark is active, it marks the next element after the
24433 ones already marked."
24434 (interactive)
24435 (let (deactivate-mark)
24436 (if (and (org-called-interactively-p 'any)
24437 (or (and (eq last-command this-command) (mark t))
24438 (and transient-mark-mode mark-active)))
24439 (set-mark
24440 (save-excursion
24441 (goto-char (mark))
24442 (goto-char (org-element-property :end (org-element-at-point)))))
24443 (let ((element (org-element-at-point)))
24444 (end-of-line)
24445 (push-mark (org-element-property :end element) t t)
24446 (goto-char (org-element-property :begin element))))))
24448 (defun org-narrow-to-element ()
24449 "Narrow buffer to current element."
24450 (interactive)
24451 (let ((elem (org-element-at-point)))
24452 (cond
24453 ((eq (car elem) 'headline)
24454 (narrow-to-region
24455 (org-element-property :begin elem)
24456 (org-element-property :end elem)))
24457 ((memq (car elem) org-element-greater-elements)
24458 (narrow-to-region
24459 (org-element-property :contents-begin elem)
24460 (org-element-property :contents-end elem)))
24462 (narrow-to-region
24463 (org-element-property :begin elem)
24464 (org-element-property :end elem))))))
24466 (defun org-transpose-element ()
24467 "Transpose current and previous elements, keeping blank lines between.
24468 Point is moved after both elements."
24469 (interactive)
24470 (org-skip-whitespace)
24471 (let ((end (org-element-property :end (org-element-at-point))))
24472 (org-drag-element-backward)
24473 (goto-char end)))
24475 (defun org-unindent-buffer ()
24476 "Un-indent the visible part of the buffer.
24477 Relative indentation (between items, inside blocks, etc.) isn't
24478 modified."
24479 (interactive)
24480 (unless (eq major-mode 'org-mode)
24481 (user-error "Cannot un-indent a buffer not in Org mode"))
24482 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
24483 unindent-tree ; For byte-compiler.
24484 (unindent-tree
24485 (function
24486 (lambda (contents)
24487 (mapc
24488 (lambda (element)
24489 (if (memq (org-element-type element) '(headline section))
24490 (funcall unindent-tree (org-element-contents element))
24491 (save-excursion
24492 (save-restriction
24493 (narrow-to-region
24494 (org-element-property :begin element)
24495 (org-element-property :end element))
24496 (org-do-remove-indentation)))))
24497 (reverse contents))))))
24498 (funcall unindent-tree (org-element-contents parse-tree))))
24500 (defun org-show-subtree ()
24501 "Show everything after this heading at deeper levels."
24502 (interactive)
24503 (outline-flag-region
24504 (point)
24505 (save-excursion
24506 (org-end-of-subtree t t))
24507 nil))
24509 (defun org-show-entry ()
24510 "Show the body directly following this heading.
24511 Show the heading too, if it is currently invisible."
24512 (interactive)
24513 (save-excursion
24514 (ignore-errors
24515 (org-back-to-heading t)
24516 (outline-flag-region
24517 (max (point-min) (1- (point)))
24518 (save-excursion
24519 (if (re-search-forward
24520 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24521 (match-beginning 1)
24522 (point-max)))
24523 nil)
24524 (org-cycle-hide-drawers 'children))))
24526 (defun org-make-options-regexp (kwds &optional extra)
24527 "Make a regular expression for keyword lines.
24528 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24529 when non-nil, is a regexp matching keywords names."
24530 (concat "^[ \t]*#\\+\\("
24531 (regexp-opt kwds)
24532 (and extra (concat (and kwds "\\|") extra))
24533 "\\):[ \t]*\\(.*\\)"))
24535 ;; Make isearch reveal the necessary context
24536 (defun org-isearch-end ()
24537 "Reveal context after isearch exits."
24538 (when isearch-success ; only if search was successful
24539 (if (featurep 'xemacs)
24540 ;; Under XEmacs, the hook is run in the correct place,
24541 ;; we directly show the context.
24542 (org-show-context 'isearch)
24543 ;; In Emacs the hook runs *before* restoring the overlays.
24544 ;; So we have to use a one-time post-command-hook to do this.
24545 ;; (Emacs 22 has a special variable, see function `org-mode')
24546 (unless (and (boundp 'isearch-mode-end-hook-quit)
24547 isearch-mode-end-hook-quit)
24548 ;; Only when the isearch was not quitted.
24549 (org-add-hook 'post-command-hook 'org-isearch-post-command
24550 'append 'local)))))
24552 (defun org-isearch-post-command ()
24553 "Remove self from hook, and show context."
24554 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24555 (org-show-context 'isearch))
24558 ;;;; Integration with and fixes for other packages
24560 ;;; Imenu support
24562 (defvar org-imenu-markers nil
24563 "All markers currently used by Imenu.")
24564 (make-variable-buffer-local 'org-imenu-markers)
24566 (defun org-imenu-new-marker (&optional pos)
24567 "Return a new marker for use by Imenu, and remember the marker."
24568 (let ((m (make-marker)))
24569 (move-marker m (or pos (point)))
24570 (push m org-imenu-markers)
24573 (defun org-imenu-get-tree ()
24574 "Produce the index for Imenu."
24575 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24576 (setq org-imenu-markers nil)
24577 (let* ((n org-imenu-depth)
24578 (re (concat "^" (org-get-limited-outline-regexp)))
24579 (subs (make-vector (1+ n) nil))
24580 (last-level 0)
24581 m level head0 head)
24582 (save-excursion
24583 (save-restriction
24584 (widen)
24585 (goto-char (point-max))
24586 (while (re-search-backward re nil t)
24587 (setq level (org-reduced-level (funcall outline-level)))
24588 (when (and (<= level n)
24589 (looking-at org-complex-heading-regexp)
24590 (setq head0 (org-match-string-no-properties 4)))
24591 (setq head (org-link-display-format head0)
24592 m (org-imenu-new-marker))
24593 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24594 (if (>= level last-level)
24595 (push (cons head m) (aref subs level))
24596 (push (cons head (aref subs (1+ level))) (aref subs level))
24597 (loop for i from (1+ level) to n do (aset subs i nil)))
24598 (setq last-level level)))))
24599 (aref subs 1)))
24601 (eval-after-load "imenu"
24602 '(progn
24603 (add-hook 'imenu-after-jump-hook
24604 (lambda ()
24605 (if (derived-mode-p 'org-mode)
24606 (org-show-context 'org-goto))))))
24608 (defun org-link-display-format (link)
24609 "Replace a link with its the description.
24610 If there is no description, use the link target."
24611 (save-match-data
24612 (if (string-match org-bracket-link-analytic-regexp link)
24613 (replace-match (if (match-end 5)
24614 (match-string 5 link)
24615 (concat (match-string 1 link)
24616 (match-string 3 link)))
24617 nil t link)
24618 link)))
24620 (defun org-toggle-link-display ()
24621 "Toggle the literal or descriptive display of links."
24622 (interactive)
24623 (if org-descriptive-links
24624 (progn (org-remove-from-invisibility-spec '(org-link))
24625 (org-restart-font-lock)
24626 (setq org-descriptive-links nil))
24627 (progn (add-to-invisibility-spec '(org-link))
24628 (org-restart-font-lock)
24629 (setq org-descriptive-links t))))
24631 ;; Speedbar support
24633 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24634 "Overlay marking the agenda restriction line in speedbar.")
24635 (overlay-put org-speedbar-restriction-lock-overlay
24636 'face 'org-agenda-restriction-lock)
24637 (overlay-put org-speedbar-restriction-lock-overlay
24638 'help-echo "Agendas are currently limited to this item.")
24639 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24641 (defun org-speedbar-set-agenda-restriction ()
24642 "Restrict future agenda commands to the location at point in speedbar.
24643 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24644 (interactive)
24645 (require 'org-agenda)
24646 (let (p m tp np dir txt)
24647 (cond
24648 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24649 'org-imenu t))
24650 (setq m (get-text-property p 'org-imenu-marker))
24651 (with-current-buffer (marker-buffer m)
24652 (goto-char m)
24653 (org-agenda-set-restriction-lock 'subtree)))
24654 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24655 'speedbar-function 'speedbar-find-file))
24656 (setq tp (previous-single-property-change
24657 (1+ p) 'speedbar-function)
24658 np (next-single-property-change
24659 tp 'speedbar-function)
24660 dir (speedbar-line-directory)
24661 txt (buffer-substring-no-properties (or tp (point-min))
24662 (or np (point-max))))
24663 (with-current-buffer (find-file-noselect
24664 (let ((default-directory dir))
24665 (expand-file-name txt)))
24666 (unless (derived-mode-p 'org-mode)
24667 (user-error "Cannot restrict to non-Org-mode file"))
24668 (org-agenda-set-restriction-lock 'file)))
24669 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24670 (move-overlay org-speedbar-restriction-lock-overlay
24671 (point-at-bol) (point-at-eol))
24672 (setq current-prefix-arg nil)
24673 (org-agenda-maybe-redo)))
24675 (defvar speedbar-file-key-map)
24676 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24677 (eval-after-load "speedbar"
24678 '(progn
24679 (speedbar-add-supported-extension ".org")
24680 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24681 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24682 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24683 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24684 (add-hook 'speedbar-visiting-tag-hook
24685 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24687 ;;; Fixes and Hacks for problems with other packages
24689 (defun org--flyspell-object-check-p (element)
24690 "Non-nil when Flyspell can check object at point.
24691 ELEMENT is the element at point."
24692 (let ((object (save-excursion
24693 (when (org-looking-at-p "\\>") (backward-char))
24694 (org-element-context element))))
24695 (case (org-element-type object)
24696 ;; Prevent checks in links due to keybinding conflict with
24697 ;; Flyspell.
24698 ((code entity export-snippet inline-babel-call
24699 inline-src-block line-break latex-fragment link macro
24700 statistics-cookie target timestamp verbatim)
24701 nil)
24702 (footnote-reference
24703 ;; Only in inline footnotes, within the definition.
24704 (and (eq (org-element-property :type object) 'inline)
24705 (< (save-excursion
24706 (goto-char (org-element-property :begin object))
24707 (search-forward ":" nil t 2))
24708 (point))))
24709 (otherwise t))))
24711 (defun org-mode-flyspell-verify ()
24712 "Function used for `flyspell-generic-check-word-predicate'."
24713 (if (org-at-heading-p)
24714 ;; At a headline or an inlinetask, check title only. This is
24715 ;; faster than relying on `org-element-at-point'.
24716 (and (save-excursion (beginning-of-line)
24717 (and (let ((case-fold-search t))
24718 (not (looking-at "\\*+ END[ \t]*$")))
24719 (looking-at org-complex-heading-regexp)))
24720 (match-beginning 4)
24721 (>= (point) (match-beginning 4))
24722 (or (not (match-beginning 5))
24723 (< (point) (match-beginning 5))))
24724 (let* ((element (org-element-at-point))
24725 (post-affiliated (org-element-property :post-affiliated element)))
24726 (cond
24727 ;; Ignore checks in all affiliated keywords but captions.
24728 ((< (point) post-affiliated)
24729 (and (save-excursion
24730 (beginning-of-line)
24731 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24732 (> (point) (match-end 0))
24733 (org--flyspell-object-check-p element)))
24734 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24735 ((let ((log (org-log-into-drawer)))
24736 (and log
24737 (let ((drawer (org-element-lineage element '(drawer))))
24738 (and drawer
24739 (eq (compare-strings
24740 log nil nil
24741 (org-element-property :drawer-name drawer) nil nil t)
24742 t)))))
24743 nil)
24745 (case (org-element-type element)
24746 ((comment quote-section) t)
24747 (comment-block
24748 ;; Allow checks between block markers, not on them.
24749 (and (> (line-beginning-position) post-affiliated)
24750 (save-excursion
24751 (end-of-line)
24752 (skip-chars-forward " \r\t\n")
24753 (< (point) (org-element-property :end element)))))
24754 ;; Arbitrary list of keywords where checks are meaningful.
24755 ;; Make sure point is on the value part of the element.
24756 (keyword
24757 (and (member (org-element-property :key element)
24758 '("DESCRIPTION" "TITLE"))
24759 (< (save-excursion
24760 (beginning-of-line) (search-forward ":") (point))
24761 (point))))
24762 ;; Check is globally allowed in paragraphs verse blocks and
24763 ;; table rows (after affiliated keywords) but some objects
24764 ;; must not be affected.
24765 ((paragraph table-row verse-block)
24766 (let ((cbeg (org-element-property :contents-begin element))
24767 (cend (org-element-property :contents-end element)))
24768 (and cbeg (>= (point) cbeg) (< (point) cend)
24769 (org--flyspell-object-check-p element))))))))))
24770 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24772 (defun org-remove-flyspell-overlays-in (beg end)
24773 "Remove flyspell overlays in region."
24774 (and (org-bound-and-true-p flyspell-mode)
24775 (fboundp 'flyspell-delete-region-overlays)
24776 (flyspell-delete-region-overlays beg end)))
24778 (defvar flyspell-delayed-commands)
24779 (eval-after-load "flyspell"
24780 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24782 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24783 (eval-after-load "bookmark"
24784 '(if (boundp 'bookmark-after-jump-hook)
24785 ;; We can use the hook
24786 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24787 ;; Hook not available, use advice
24788 (defadvice bookmark-jump (after org-make-visible activate)
24789 "Make the position visible."
24790 (org-bookmark-jump-unhide))))
24792 ;; Make sure saveplace shows the location if it was hidden
24793 (eval-after-load "saveplace"
24794 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24795 "Make the position visible."
24796 (org-bookmark-jump-unhide)))
24798 ;; Make sure ecb shows the location if it was hidden
24799 (eval-after-load "ecb"
24800 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24801 "Make hierarchy visible when jumping into location from ECB tree buffer."
24802 (if (derived-mode-p 'org-mode)
24803 (org-show-context))))
24805 (defun org-bookmark-jump-unhide ()
24806 "Unhide the current position, to show the bookmark location."
24807 (and (derived-mode-p 'org-mode)
24808 (or (outline-invisible-p)
24809 (save-excursion (goto-char (max (point-min) (1- (point))))
24810 (outline-invisible-p)))
24811 (org-show-context 'bookmark-jump)))
24813 (defun org-mark-jump-unhide ()
24814 "Make the point visible with `org-show-context' after jumping to the mark."
24815 (when (and (derived-mode-p 'org-mode)
24816 (outline-invisible-p))
24817 (org-show-context 'mark-goto)))
24819 (eval-after-load "simple"
24820 '(defadvice pop-to-mark-command (after org-make-visible activate)
24821 "Make the point visible with `org-show-context'."
24822 (org-mark-jump-unhide)))
24824 (eval-after-load "simple"
24825 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24826 "Make the point visible with `org-show-context'."
24827 (org-mark-jump-unhide)))
24829 (eval-after-load "simple"
24830 '(defadvice pop-global-mark (after org-make-visible activate)
24831 "Make the point visible with `org-show-context'."
24832 (org-mark-jump-unhide)))
24834 ;; Make session.el ignore our circular variable
24835 (defvar session-globals-exclude)
24836 (eval-after-load "session"
24837 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24839 ;;;; Finish up
24841 (provide 'org)
24843 (run-hooks 'org-load-hook)
24845 ;;; org.el ends here