Fix ae0f1c56a7934cde23d30e5481510cbe79562fea
[org-mode.git] / lisp / org.el
blobcba8c302a994e659cf859382cfc7d9ce84498623
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 (load "org-loaddefs.el" t t t)
82 (require 'org-macs)
83 (require 'org-compat)
85 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
86 ;; some places -- e.g. see the macro `org-with-limited-levels'.
88 ;; In Org buffers, the value of `outline-regexp' is that of
89 ;; `org-outline-regexp'. The only function still directly relying on
90 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
91 ;; job when `orgstruct-mode' is active.
92 (defvar org-outline-regexp "\\*+ "
93 "Regexp to match Org headlines.")
95 (defvar org-outline-regexp-bol "^\\*+ "
96 "Regexp to match Org headlines.
97 This is similar to `org-outline-regexp' but additionally makes
98 sure that we are at the beginning of the line.")
100 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
101 "Matches a headline, putting stars and text into groups.
102 Stars are put in group 1 and the trimmed body in group 2.")
104 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (org-defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (org-defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-clocktable-shift "org-clock" (dir n))
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-update-time-maybe "org-clock" ())
121 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
122 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
123 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
127 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
128 (declare-function orgtbl-mode "org-table" (&optional arg))
129 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
130 (declare-function org-beamer-mode "ox-beamer" ())
131 (declare-function org-table-blank-field "org-table" ())
132 (declare-function org-table-edit-field "org-table" (arg))
133 (declare-function org-table-insert-row "org-table" (&optional arg))
134 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
135 (declare-function org-table-set-constants "org-table" ())
136 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
137 (declare-function org-id-get-create "org-id" (&optional force))
138 (declare-function org-add-archive-files "org-archive" (files))
139 (declare-function org-id-find-id-file "org-id" (id))
140 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
141 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
142 (declare-function org-agenda-redo "org-agenda" (&optional all))
143 (declare-function org-table-align "org-table" ())
144 (declare-function org-table-begin "org-table" (&optional table-type))
145 (declare-function org-table-end "org-table" (&optional table-type))
146 (declare-function org-table-paste-rectangle "org-table" ())
147 (declare-function org-table-maybe-eval-formula "org-table" ())
148 (declare-function org-table-maybe-recalculate-line "org-table" ())
150 (declare-function org-element--parse-objects "org-element"
151 (beg end acc restriction))
152 (declare-function org-element-at-point "org-element" ())
153 (declare-function org-element-cache-reset "org-element" (&optional all))
154 (declare-function org-element-contents "org-element" (element))
155 (declare-function org-element-context "org-element" (&optional element))
156 (declare-function org-element-interpret-data "org-element"
157 (data &optional parent))
158 (declare-function org-element-map "org-element"
159 (data types fun &optional info first-match no-recursion))
160 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
161 (declare-function org-element-parse-buffer "org-element"
162 (&optional granularity visible-only))
163 (declare-function org-element-property "org-element" (property element))
164 (declare-function org-element-put-property "org-element"
165 (element property value))
166 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
167 (declare-function org-element--parse-objects "org-element"
168 (beg end acc restriction))
169 (declare-function org-element-parse-buffer "org-element"
170 (&optional granularity visible-only))
171 (declare-function org-element-restriction "org-element" (element))
172 (declare-function org-element-type "org-element" (element))
174 (defsubst org-uniquify (list)
175 "Non-destructively remove duplicate elements from LIST."
176 (let ((res (copy-sequence list))) (delete-dups res)))
178 ;; load languages based on value of `org-babel-load-languages'
179 (defvar org-babel-load-languages)
181 ;;;###autoload
182 (defun org-babel-do-load-languages (sym value)
183 "Load the languages defined in `org-babel-load-languages'."
184 (set-default sym value)
185 (mapc (lambda (pair)
186 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
187 (if active
188 (progn
189 (require (intern (concat "ob-" lang))))
190 (progn
191 (funcall 'fmakunbound
192 (intern (concat "org-babel-execute:" lang)))
193 (funcall 'fmakunbound
194 (intern (concat "org-babel-expand-body:" lang)))))))
195 org-babel-load-languages))
197 ;;;###autoload
198 (defun org-babel-load-file (file &optional compile)
199 "Load Emacs Lisp source code blocks in the Org-mode FILE.
200 This function exports the source code using `org-babel-tangle'
201 and then loads the resulting file using `load-file'. With prefix
202 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
203 file to byte-code before it is loaded."
204 (interactive "fFile to load: \nP")
205 (let* ((age (lambda (file)
206 (float-time
207 (time-subtract (current-time)
208 (nth 5 (or (file-attributes (file-truename file))
209 (file-attributes file)))))))
210 (base-name (file-name-sans-extension file))
211 (exported-file (concat base-name ".el")))
212 ;; tangle if the org-mode file is newer than the elisp file
213 (unless (and (file-exists-p exported-file)
214 (> (funcall age file) (funcall age exported-file)))
215 (setq exported-file
216 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
217 (message "%s %s"
218 (if compile
219 (progn (byte-compile-file exported-file 'load)
220 "Compiled and loaded")
221 (progn (load-file exported-file) "Loaded"))
222 exported-file)))
224 (defcustom org-babel-load-languages '((emacs-lisp . t))
225 "Languages which can be evaluated in Org-mode buffers.
226 This list can be used to load support for any of the languages
227 below, note that each language will depend on a different set of
228 system executables and/or Emacs modes. When a language is
229 \"loaded\", then code blocks in that language can be evaluated
230 with `org-babel-execute-src-block' bound by default to C-c
231 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
232 be set to remove code block evaluation from the C-c C-c
233 keybinding. By default only Emacs Lisp (which has no
234 requirements) is loaded."
235 :group 'org-babel
236 :set 'org-babel-do-load-languages
237 :version "24.1"
238 :type '(alist :tag "Babel Languages"
239 :key-type
240 (choice
241 (const :tag "Awk" awk)
242 (const :tag "C" C)
243 (const :tag "R" R)
244 (const :tag "Asymptote" asymptote)
245 (const :tag "Calc" calc)
246 (const :tag "Clojure" clojure)
247 (const :tag "CSS" css)
248 (const :tag "Ditaa" ditaa)
249 (const :tag "Dot" dot)
250 (const :tag "Emacs Lisp" emacs-lisp)
251 (const :tag "Fortran" fortran)
252 (const :tag "Gnuplot" gnuplot)
253 (const :tag "Haskell" haskell)
254 (const :tag "IO" io)
255 (const :tag "J" J)
256 (const :tag "Java" java)
257 (const :tag "Javascript" js)
258 (const :tag "LaTeX" latex)
259 (const :tag "Ledger" ledger)
260 (const :tag "Lilypond" lilypond)
261 (const :tag "Lisp" lisp)
262 (const :tag "Makefile" makefile)
263 (const :tag "Maxima" maxima)
264 (const :tag "Matlab" matlab)
265 (const :tag "Mscgen" mscgen)
266 (const :tag "Ocaml" ocaml)
267 (const :tag "Octave" octave)
268 (const :tag "Org" org)
269 (const :tag "Perl" perl)
270 (const :tag "Pico Lisp" picolisp)
271 (const :tag "PlantUML" plantuml)
272 (const :tag "Python" python)
273 (const :tag "Ruby" ruby)
274 (const :tag "Sass" sass)
275 (const :tag "Scala" scala)
276 (const :tag "Scheme" scheme)
277 (const :tag "Screen" screen)
278 (const :tag "Shell Script" sh)
279 (const :tag "Shen" shen)
280 (const :tag "Sql" sql)
281 (const :tag "Sqlite" sqlite)
282 (const :tag "ebnf2ps" ebnf2ps))
283 :value-type (boolean :tag "Activate" :value t)))
285 ;;;; Customization variables
286 (defcustom org-clone-delete-id nil
287 "Remove ID property of clones of a subtree.
288 When non-nil, clones of a subtree don't inherit the ID property.
289 Otherwise they inherit the ID property with a new unique
290 identifier."
291 :type 'boolean
292 :version "24.1"
293 :group 'org-id)
295 ;;; Version
296 (org-check-version)
298 ;;;###autoload
299 (defun org-version (&optional here full message)
300 "Show the org-mode version in the echo area.
301 With prefix argument HERE, insert it at point.
302 When FULL is non-nil, use a verbose version string.
303 When MESSAGE is non-nil, display a message with the version."
304 (interactive "P")
305 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
306 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
307 (load-suffixes (list ".el"))
308 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
309 (org-trash (or
310 (and (fboundp 'org-release) (fboundp 'org-git-version))
311 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
312 (load-suffixes save-load-suffixes)
313 (org-version (org-release))
314 (git-version (org-git-version))
315 (version (format "Org-mode version %s (%s @ %s)"
316 org-version
317 git-version
318 (if org-install-dir
319 (if (string= org-dir org-install-dir)
320 org-install-dir
321 (concat "mixed installation! " org-install-dir " and " org-dir))
322 "org-loaddefs.el can not be found!")))
323 (version1 (if full version org-version)))
324 (if (org-called-interactively-p 'interactive)
325 (if here
326 (insert version)
327 (message version))
328 (if message (message version1))
329 version1)))
331 (defconst org-version (org-version))
334 ;;; Syntax Constants
336 ;;;; Block
338 (defconst org-block-regexp
339 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
340 "Regular expression for hiding blocks.")
342 (defconst org-dblock-start-re
343 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
344 "Matches the start line of a dynamic block, with parameters.")
346 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
347 "Matches the end of a dynamic block.")
349 ;;;; Clock and Planning
351 (defconst org-clock-string "CLOCK:"
352 "String used as prefix for timestamps clocking work hours on an item.")
354 (defconst org-closed-string "CLOSED:"
355 "String used as the prefix for timestamps logging closing a TODO entry.")
357 (defconst org-deadline-string "DEADLINE:"
358 "String to mark deadline entries.
359 A deadline is this string, followed by a time stamp. Should be a word,
360 terminated by a colon. You can insert a schedule keyword and
361 a timestamp with \\[org-deadline].")
363 (defconst org-scheduled-string "SCHEDULED:"
364 "String to mark scheduled TODO entries.
365 A schedule is this string, followed by a time stamp. Should be a word,
366 terminated by a colon. You can insert a schedule keyword and
367 a timestamp with \\[org-schedule].")
369 (defconst org-planning-or-clock-line-re
370 (concat "^[ \t]*"
371 (regexp-opt
372 (list org-clock-string org-closed-string org-deadline-string
373 org-scheduled-string)
375 "Matches a line with planning or clock info.
376 Matched keyword is in group 1.")
378 ;;;; Drawer
380 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
381 "Matches first or last line of a hidden block.
382 Group 1 contains drawer's name or \"END\".")
384 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
385 "Regular expression matching the first line of a property drawer.")
387 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
388 "Regular expression matching the last line of a property drawer.")
390 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
391 "Regular expression matching the first line of a clock drawer.")
393 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
394 "Regular expression matching the last line of a clock drawer.")
396 (defconst org-property-drawer-re
397 (concat "\\(" org-property-start-re "\\)[^\000]*?\\("
398 org-property-end-re "\\)\n?")
399 "Matches an entire property drawer.")
401 (defconst org-clock-drawer-re
402 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
403 org-clock-drawer-end-re "\\)\n?")
404 "Matches an entire clock drawer.")
406 ;;;; Headline
408 (defconst org-heading-keyword-regexp-format
409 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
410 "Printf format for a regexp matching a headline with some keyword.
411 This regexp will match the headline of any node which has the
412 exact keyword that is put into the format. The keyword isn't in
413 any group by default, but the stars and the body are.")
415 (defconst org-heading-keyword-maybe-regexp-format
416 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
417 "Printf format for a regexp matching a headline, possibly with some keyword.
418 This regexp can match any headline with the specified keyword, or
419 without a keyword. The keyword isn't in any group by default,
420 but the stars and the body are.")
422 (defconst org-archive-tag "ARCHIVE"
423 "The tag that marks a subtree as archived.
424 An archived subtree does not open during visibility cycling, and does
425 not contribute to the agenda listings.")
427 (defconst org-comment-string "COMMENT"
428 "Entries starting with this keyword will never be exported.
429 An entry can be toggled between COMMENT and normal with
430 \\[org-toggle-comment].")
432 (defconst org-quote-string "QUOTE"
433 "Entries starting with this keyword will be exported in fixed-width font.
434 Quoting applies only to the text in the entry following the headline, and does
435 not extend beyond the next headline, even if that is lower level.
436 An entry can be toggled between QUOTE and normal with
437 \\[org-toggle-fixed-width-section].")
439 ;;;; LaTeX Environments and Fragments
441 (defconst org-latex-regexps
442 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
443 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
444 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
445 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
446 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
447 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
448 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
449 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
450 "Regular expressions for matching embedded LaTeX.")
452 ;;;; Node Property
454 (defconst org-effort-property "Effort"
455 "The property that is being used to keep track of effort estimates.
456 Effort estimates given in this property need to have the format H:MM.")
458 ;;;; Table
460 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
461 "Detect an org-type or table-type table.")
463 (defconst org-table-line-regexp "^[ \t]*|"
464 "Detect an org-type table line.")
466 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
467 "Detect an org-type table line.")
469 (defconst org-table-hline-regexp "^[ \t]*|-"
470 "Detect an org-type table hline.")
472 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
473 "Detect a table-type table hline.")
475 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
476 "Detect the first line outside a table when searching from within it.
477 This works for both table types.")
479 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
480 "Detect a #+TBLFM line.")
482 ;;;; Timestamp
484 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
485 "Regular expression for fast time stamp matching.")
487 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
488 "Regular expression for fast time stamp matching.")
490 (defconst org-ts-regexp0
491 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
492 "Regular expression matching time strings for analysis.
493 This one does not require the space after the date, so it can be used
494 on a string that terminates immediately after the date.")
496 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
497 "Regular expression matching time strings for analysis.")
499 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
500 "Regular expression matching time stamps, with groups.")
502 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
503 "Regular expression matching time stamps (also [..]), with groups.")
505 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
506 "Regular expression matching a time stamp range.")
508 (defconst org-tr-regexp-both
509 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
510 "Regular expression matching a time stamp range.")
512 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
513 org-ts-regexp "\\)?")
514 "Regular expression matching a time stamp or time stamp range.")
516 (defconst org-tsr-regexp-both
517 (concat org-ts-regexp-both "\\(--?-?"
518 org-ts-regexp-both "\\)?")
519 "Regular expression matching a time stamp or time stamp range.
520 The time stamps may be either active or inactive.")
522 (defconst org-repeat-re
523 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
524 "Regular expression for specifying repeated events.
525 After a match, group 1 contains the repeat expression.")
527 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
528 "Formats for `format-time-string' which are used for time stamps.")
531 ;;; The custom variables
533 (defgroup org nil
534 "Outline-based notes management and organizer."
535 :tag "Org"
536 :group 'outlines
537 :group 'calendar)
539 (defcustom org-mode-hook nil
540 "Mode hook for Org-mode, run after the mode was turned on."
541 :group 'org
542 :type 'hook)
544 (defcustom org-load-hook nil
545 "Hook that is run after org.el has been loaded."
546 :group 'org
547 :type 'hook)
549 (defcustom org-log-buffer-setup-hook nil
550 "Hook that is run after an Org log buffer is created."
551 :group 'org
552 :version "24.1"
553 :type 'hook)
555 (defvar org-modules) ; defined below
556 (defvar org-modules-loaded nil
557 "Have the modules been loaded already?")
559 (defun org-load-modules-maybe (&optional force)
560 "Load all extensions listed in `org-modules'."
561 (when (or force (not org-modules-loaded))
562 (mapc (lambda (ext)
563 (condition-case nil (require ext)
564 (error (message "Problems while trying to load feature `%s'" ext))))
565 org-modules)
566 (setq org-modules-loaded t)))
568 (defun org-set-modules (var value)
569 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
570 (set var value)
571 (when (featurep 'org)
572 (org-load-modules-maybe 'force)
573 (org-element-cache-reset 'all)))
575 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
576 "Modules that should always be loaded together with org.el.
578 If a description starts with <C>, the file is not part of Emacs
579 and loading it will require that you have downloaded and properly
580 installed the Org mode distribution.
582 You can also use this system to load external packages (i.e. neither Org
583 core modules, nor modules from the CONTRIB directory). Just add symbols
584 to the end of the list. If the package is called org-xyz.el, then you need
585 to add the symbol `xyz', and the package must have a call to:
587 \(provide 'org-xyz)
589 For export specific modules, see also `org-export-backends'."
590 :group 'org
591 :set 'org-set-modules
592 :version "24.4"
593 :package-version '(Org . "8.0")
594 :type
595 '(set :greedy t
596 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
597 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
598 (const :tag " crypt: Encryption of subtrees" org-crypt)
599 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
600 (const :tag " docview: Links to doc-view buffers" org-docview)
601 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
602 (const :tag " habit: Track your consistency with habits" org-habit)
603 (const :tag " id: Global IDs for identifying entries" org-id)
604 (const :tag " info: Links to Info nodes" org-info)
605 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
606 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
607 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
608 (const :tag " mouse: Additional mouse support" org-mouse)
609 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
610 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
611 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
613 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
614 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
615 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
616 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
617 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
618 (const :tag "C collector: Collect properties into tables" org-collector)
619 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
620 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
621 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
622 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
623 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
624 (const :tag "C eval: Include command output as text" org-eval)
625 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
626 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
627 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
628 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
629 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
630 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
631 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
632 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
633 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
634 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
635 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
636 (const :tag "C mew: Links to Mew folders/messages" org-mew)
637 (const :tag "C mtags: Support for muse-like tags" org-mtags)
638 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
639 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
640 (const :tag "C registry: A registry for Org-mode links" org-registry)
641 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
642 (const :tag "C secretary: Team management with org-mode" org-secretary)
643 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
644 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
645 (const :tag "C track: Keep up with Org-mode development" org-track)
646 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
647 (const :tag "C vm: Links to VM folders/messages" org-vm)
648 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
649 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
650 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
652 (defvar org-export--registered-backends) ; From ox.el.
653 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
654 (declare-function org-export-backend-name "ox" (backend))
655 (defcustom org-export-backends '(ascii html icalendar latex)
656 "List of export back-ends that should be always available.
658 If a description starts with <C>, the file is not part of Emacs
659 and loading it will require that you have downloaded and properly
660 installed the Org mode distribution.
662 Unlike to `org-modules', libraries in this list will not be
663 loaded along with Org, but only once the export framework is
664 needed.
666 This variable needs to be set before org.el is loaded. If you
667 need to make a change while Emacs is running, use the customize
668 interface or run the following code, where VAL stands for the new
669 value of the variable, after updating it:
671 \(progn
672 \(setq org-export--registered-backends
673 \(org-remove-if-not
674 \(lambda (backend)
675 \(let ((name (org-export-backend-name backend)))
676 \(or (memq name val)
677 \(catch 'parentp
678 \(dolist (b val)
679 \(and (org-export-derived-backend-p b name)
680 \(throw 'parentp t)))))))
681 org-export--registered-backends))
682 \(let ((new-list (mapcar 'org-export-backend-name
683 org-export--registered-backends)))
684 \(dolist (backend val)
685 \(cond
686 \((not (load (format \"ox-%s\" backend) t t))
687 \(message \"Problems while trying to load export back-end `%s'\"
688 backend))
689 \((not (memq backend new-list)) (push backend new-list))))
690 \(set-default 'org-export-backends new-list)))
692 Adding a back-end to this list will also pull the back-end it
693 depends on, if any."
694 :group 'org
695 :group 'org-export
696 :version "24.4"
697 :package-version '(Org . "8.0")
698 :initialize 'custom-initialize-set
699 :set (lambda (var val)
700 (if (not (featurep 'ox)) (set-default var val)
701 ;; Any back-end not required anymore (not present in VAL and not
702 ;; a parent of any back-end in the new value) is removed from the
703 ;; list of registered back-ends.
704 (setq org-export--registered-backends
705 (org-remove-if-not
706 (lambda (backend)
707 (let ((name (org-export-backend-name backend)))
708 (or (memq name val)
709 (catch 'parentp
710 (dolist (b val)
711 (and (org-export-derived-backend-p b name)
712 (throw 'parentp t)))))))
713 org-export--registered-backends))
714 ;; Now build NEW-LIST of both new back-ends and required
715 ;; parents.
716 (let ((new-list (mapcar 'org-export-backend-name
717 org-export--registered-backends)))
718 (dolist (backend val)
719 (cond
720 ((not (load (format "ox-%s" backend) t t))
721 (message "Problems while trying to load export back-end `%s'"
722 backend))
723 ((not (memq backend new-list)) (push backend new-list))))
724 ;; Set VAR to that list with fixed dependencies.
725 (set-default var new-list))))
726 :type '(set :greedy t
727 (const :tag " ascii Export buffer to ASCII format" ascii)
728 (const :tag " beamer Export buffer to Beamer presentation" beamer)
729 (const :tag " html Export buffer to HTML format" html)
730 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
731 (const :tag " latex Export buffer to LaTeX format" latex)
732 (const :tag " man Export buffer to MAN format" man)
733 (const :tag " md Export buffer to Markdown format" md)
734 (const :tag " odt Export buffer to ODT format" odt)
735 (const :tag " org Export buffer to Org format" org)
736 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
737 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
738 (const :tag "C deck Export buffer to deck.js presentations" deck)
739 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
740 (const :tag "C groff Export buffer to Groff format" groff)
741 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
742 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
743 (const :tag "C s5 Export buffer to s5 presentations" s5)
744 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
746 (eval-after-load 'ox
747 '(mapc
748 (lambda (backend)
749 (condition-case nil (require (intern (format "ox-%s" backend)))
750 (error (message "Problems while trying to load export back-end `%s'"
751 backend))))
752 org-export-backends))
754 (defcustom org-support-shift-select nil
755 "Non-nil means make shift-cursor commands select text when possible.
757 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
758 start selecting a region, or enlarge regions started in this way.
759 In Org-mode, in special contexts, these same keys are used for
760 other purposes, important enough to compete with shift selection.
761 Org tries to balance these needs by supporting `shift-select-mode'
762 outside these special contexts, under control of this variable.
764 The default of this variable is nil, to avoid confusing behavior. Shifted
765 cursor keys will then execute Org commands in the following contexts:
766 - on a headline, changing TODO state (left/right) and priority (up/down)
767 - on a time stamp, changing the time
768 - in a plain list item, changing the bullet type
769 - in a property definition line, switching between allowed values
770 - in the BEGIN line of a clock table (changing the time block).
771 Outside these contexts, the commands will throw an error.
773 When this variable is t and the cursor is not in a special
774 context, Org-mode will support shift-selection for making and
775 enlarging regions. To make this more effective, the bullet
776 cycling will no longer happen anywhere in an item line, but only
777 if the cursor is exactly on the bullet.
779 If you set this variable to the symbol `always', then the keys
780 will not be special in headlines, property lines, and item lines,
781 to make shift selection work there as well. If this is what you
782 want, you can use the following alternative commands: `C-c C-t'
783 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
784 can be used to switch TODO sets, `C-c -' to cycle item bullet
785 types, and properties can be edited by hand or in column view.
787 However, when the cursor is on a timestamp, shift-cursor commands
788 will still edit the time stamp - this is just too good to give up.
790 XEmacs user should have this variable set to nil, because
791 `shift-select-mode' is in Emacs 23 or later only."
792 :group 'org
793 :type '(choice
794 (const :tag "Never" nil)
795 (const :tag "When outside special context" t)
796 (const :tag "Everywhere except timestamps" always)))
798 (defcustom org-loop-over-headlines-in-active-region nil
799 "Shall some commands act upon headlines in the active region?
801 When set to `t', some commands will be performed in all headlines
802 within the active region.
804 When set to `start-level', some commands will be performed in all
805 headlines within the active region, provided that these headlines
806 are of the same level than the first one.
808 When set to a string, those commands will be performed on the
809 matching headlines within the active region. Such string must be
810 a tags/property/todo match as it is used in the agenda tags view.
812 The list of commands is: `org-schedule', `org-deadline',
813 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
814 `org-archive-to-archive-sibling'. The archiving commands skip
815 already archived entries."
816 :type '(choice (const :tag "Don't loop" nil)
817 (const :tag "All headlines in active region" t)
818 (const :tag "In active region, headlines at the same level than the first one" start-level)
819 (string :tag "Tags/Property/Todo matcher"))
820 :version "24.1"
821 :group 'org-todo
822 :group 'org-archive)
824 (defgroup org-startup nil
825 "Options concerning startup of Org-mode."
826 :tag "Org Startup"
827 :group 'org)
829 (defcustom org-startup-folded t
830 "Non-nil means entering Org-mode will switch to OVERVIEW.
831 This can also be configured on a per-file basis by adding one of
832 the following lines anywhere in the buffer:
834 #+STARTUP: fold (or `overview', this is equivalent)
835 #+STARTUP: nofold (or `showall', this is equivalent)
836 #+STARTUP: content
837 #+STARTUP: showeverything
839 By default, this option is ignored when Org opens agenda files
840 for the first time. If you want the agenda to honor the startup
841 option, set `org-agenda-inhibit-startup' to nil."
842 :group 'org-startup
843 :type '(choice
844 (const :tag "nofold: show all" nil)
845 (const :tag "fold: overview" t)
846 (const :tag "content: all headlines" content)
847 (const :tag "show everything, even drawers" showeverything)))
849 (defcustom org-startup-truncated t
850 "Non-nil means entering Org-mode will set `truncate-lines'.
851 This is useful since some lines containing links can be very long and
852 uninteresting. Also tables look terrible when wrapped."
853 :group 'org-startup
854 :type 'boolean)
856 (defcustom org-startup-indented nil
857 "Non-nil means turn on `org-indent-mode' on startup.
858 This can also be configured on a per-file basis by adding one of
859 the following lines anywhere in the buffer:
861 #+STARTUP: indent
862 #+STARTUP: noindent"
863 :group 'org-structure
864 :type '(choice
865 (const :tag "Not" nil)
866 (const :tag "Globally (slow on startup in large files)" t)))
868 (defcustom org-use-sub-superscripts t
869 "Non-nil means interpret \"_\" and \"^\" for display.
871 If you want to control how Org exports those characters, see
872 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
873 used to be an alias for `org-export-with-sub-superscripts' in
874 Org <8.0, it is not anymore.
876 When this option is turned on, you can use TeX-like syntax for
877 sub- and superscripts within the buffer. Several characters after
878 \"_\" or \"^\" will be considered as a single item - so grouping
879 with {} is normally not needed. For example, the following things
880 will be parsed as single sub- or superscripts:
882 10^24 or 10^tau several digits will be considered 1 item.
883 10^-12 or 10^-tau a leading sign with digits or a word
884 x^2-y^3 will be read as x^2 - y^3, because items are
885 terminated by almost any nonword/nondigit char.
886 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
888 Still, ambiguity is possible. So when in doubt, use {} to enclose
889 the sub/superscript. If you set this variable to the symbol `{}',
890 the braces are *required* in order to trigger interpretations as
891 sub/superscript. This can be helpful in documents that need \"_\"
892 frequently in plain text."
893 :group 'org-startup
894 :version "24.4"
895 :package-version '(Org . "8.0")
896 :type '(choice
897 (const :tag "Always interpret" t)
898 (const :tag "Only with braces" {})
899 (const :tag "Never interpret" nil)))
901 (defcustom org-startup-with-beamer-mode nil
902 "Non-nil means turn on `org-beamer-mode' on startup.
903 This can also be configured on a per-file basis by adding one of
904 the following lines anywhere in the buffer:
906 #+STARTUP: beamer"
907 :group 'org-startup
908 :version "24.1"
909 :type 'boolean)
911 (defcustom org-startup-align-all-tables nil
912 "Non-nil means align all tables when visiting a file.
913 This is useful when the column width in tables is forced with <N> cookies
914 in table fields. Such tables will look correct only after the first re-align.
915 This can also be configured on a per-file basis by adding one of
916 the following lines anywhere in the buffer:
917 #+STARTUP: align
918 #+STARTUP: noalign"
919 :group 'org-startup
920 :type 'boolean)
922 (defcustom org-startup-with-inline-images nil
923 "Non-nil means show inline images when loading a new Org file.
924 This can also be configured on a per-file basis by adding one of
925 the following lines anywhere in the buffer:
926 #+STARTUP: inlineimages
927 #+STARTUP: noinlineimages"
928 :group 'org-startup
929 :version "24.1"
930 :type 'boolean)
932 (defcustom org-startup-with-latex-preview nil
933 "Non-nil means preview LaTeX fragments when loading a new Org file.
935 This can also be configured on a per-file basis by adding one of
936 the following lines anywhere in the buffer:
937 #+STARTUP: latexpreview
938 #+STARTUP: nolatexpreview"
939 :group 'org-startup
940 :version "24.4"
941 :package-version '(Org . "8.0")
942 :type 'boolean)
944 (defcustom org-insert-mode-line-in-empty-file nil
945 "Non-nil means insert the first line setting Org-mode in empty files.
946 When the function `org-mode' is called interactively in an empty file, this
947 normally means that the file name does not automatically trigger Org-mode.
948 To ensure that the file will always be in Org-mode in the future, a
949 line enforcing Org-mode will be inserted into the buffer, if this option
950 has been set."
951 :group 'org-startup
952 :type 'boolean)
954 (defcustom org-replace-disputed-keys nil
955 "Non-nil means use alternative key bindings for some keys.
956 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
957 These keys are also used by other packages like shift-selection-mode'
958 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
959 If you want to use Org-mode together with one of these other modes,
960 or more generally if you would like to move some Org-mode commands to
961 other keys, set this variable and configure the keys with the variable
962 `org-disputed-keys'.
964 This option is only relevant at load-time of Org-mode, and must be set
965 *before* org.el is loaded. Changing it requires a restart of Emacs to
966 become effective."
967 :group 'org-startup
968 :type 'boolean)
970 (defcustom org-use-extra-keys nil
971 "Non-nil means use extra key sequence definitions for certain commands.
972 This happens automatically if you run XEmacs or if `window-system'
973 is nil. This variable lets you do the same manually. You must
974 set it before loading org.
976 Example: on Carbon Emacs 22 running graphically, with an external
977 keyboard on a Powerbook, the default way of setting M-left might
978 not work for either Alt or ESC. Setting this variable will make
979 it work for ESC."
980 :group 'org-startup
981 :type 'boolean)
983 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
985 (defcustom org-disputed-keys
986 '(([(shift up)] . [(meta p)])
987 ([(shift down)] . [(meta n)])
988 ([(shift left)] . [(meta -)])
989 ([(shift right)] . [(meta +)])
990 ([(control shift right)] . [(meta shift +)])
991 ([(control shift left)] . [(meta shift -)]))
992 "Keys for which Org-mode and other modes compete.
993 This is an alist, cars are the default keys, second element specifies
994 the alternative to use when `org-replace-disputed-keys' is t.
996 Keys can be specified in any syntax supported by `define-key'.
997 The value of this option takes effect only at Org-mode's startup,
998 therefore you'll have to restart Emacs to apply it after changing."
999 :group 'org-startup
1000 :type 'alist)
1002 (defun org-key (key)
1003 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1004 Or return the original if not disputed.
1005 Also apply the translations defined in `org-xemacs-key-equivalents'."
1006 (when org-replace-disputed-keys
1007 (let* ((nkey (key-description key))
1008 (x (org-find-if (lambda (x)
1009 (equal (key-description (car x)) nkey))
1010 org-disputed-keys)))
1011 (setq key (if x (cdr x) key))))
1012 (when (featurep 'xemacs)
1013 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1014 key)
1016 (defun org-find-if (predicate seq)
1017 (catch 'exit
1018 (while seq
1019 (if (funcall predicate (car seq))
1020 (throw 'exit (car seq))
1021 (pop seq)))))
1023 (defun org-defkey (keymap key def)
1024 "Define a key, possibly translated, as returned by `org-key'."
1025 (define-key keymap (org-key key) def))
1027 (defcustom org-ellipsis nil
1028 "The ellipsis to use in the Org-mode outline.
1029 When nil, just use the standard three dots.
1030 When a string, use that string instead.
1031 When a face, use the standard 3 dots, but with the specified face.
1032 The change affects only Org-mode (which will then use its own display table).
1033 Changing this requires executing `M-x org-mode RET' in a buffer to become
1034 effective."
1035 :group 'org-startup
1036 :type '(choice (const :tag "Default" nil)
1037 (face :tag "Face" :value org-warning)
1038 (string :tag "String" :value "...#")))
1040 (defvar org-display-table nil
1041 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1043 (defgroup org-keywords nil
1044 "Keywords in Org-mode."
1045 :tag "Org Keywords"
1046 :group 'org)
1048 (defcustom org-closed-keep-when-no-todo nil
1049 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1050 :group 'org-todo
1051 :group 'org-keywords
1052 :version "24.4"
1053 :package-version '(Org . "8.0")
1054 :type 'boolean)
1056 (defgroup org-structure nil
1057 "Options concerning the general structure of Org-mode files."
1058 :tag "Org Structure"
1059 :group 'org)
1061 (defgroup org-reveal-location nil
1062 "Options about how to make context of a location visible."
1063 :tag "Org Reveal Location"
1064 :group 'org-structure)
1066 (defconst org-context-choice
1067 '(choice
1068 (const :tag "Always" t)
1069 (const :tag "Never" nil)
1070 (repeat :greedy t :tag "Individual contexts"
1071 (cons
1072 (choice :tag "Context"
1073 (const agenda)
1074 (const org-goto)
1075 (const occur-tree)
1076 (const tags-tree)
1077 (const link-search)
1078 (const mark-goto)
1079 (const bookmark-jump)
1080 (const isearch)
1081 (const default))
1082 (boolean))))
1083 "Contexts for the reveal options.")
1085 (defcustom org-show-hierarchy-above '((default . t))
1086 "Non-nil means show full hierarchy when revealing a location.
1087 Org-mode often shows locations in an org-mode file which might have
1088 been invisible before. When this is set, the hierarchy of headings
1089 above the exposed location is shown.
1090 Turning this off for example for sparse trees makes them very compact.
1091 Instead of t, this can also be an alist specifying this option for different
1092 contexts. Valid contexts are
1093 agenda when exposing an entry from the agenda
1094 org-goto when using the command `org-goto' on key C-c C-j
1095 occur-tree when using the command `org-occur' on key C-c /
1096 tags-tree when constructing a sparse tree based on tags matches
1097 link-search when exposing search matches associated with a link
1098 mark-goto when exposing the jump goal of a mark
1099 bookmark-jump when exposing a bookmark location
1100 isearch when exiting from an incremental search
1101 default default for all contexts not set explicitly"
1102 :group 'org-reveal-location
1103 :type org-context-choice)
1105 (defcustom org-show-following-heading '((default . nil))
1106 "Non-nil means show following heading when revealing a location.
1107 Org-mode often shows locations in an org-mode file which might have
1108 been invisible before. When this is set, the heading following the
1109 match is shown.
1110 Turning this off for example for sparse trees makes them very compact,
1111 but makes it harder to edit the location of the match. In such a case,
1112 use the command \\[org-reveal] to show more context.
1113 Instead of t, this can also be an alist specifying this option for different
1114 contexts. See `org-show-hierarchy-above' for valid contexts."
1115 :group 'org-reveal-location
1116 :type org-context-choice)
1118 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
1119 "Non-nil means show all sibling heading when revealing a location.
1120 Org-mode often shows locations in an org-mode file which might have
1121 been invisible before. When this is set, the sibling of the current entry
1122 heading are all made visible. If `org-show-hierarchy-above' is t,
1123 the same happens on each level of the hierarchy above the current entry.
1125 By default this is on for the isearch context, off for all other contexts.
1126 Turning this off for example for sparse trees makes them very compact,
1127 but makes it harder to edit the location of the match. In such a case,
1128 use the command \\[org-reveal] to show more context.
1129 Instead of t, this can also be an alist specifying this option for different
1130 contexts. See `org-show-hierarchy-above' for valid contexts."
1131 :group 'org-reveal-location
1132 :type org-context-choice
1133 :version "24.4"
1134 :package-version '(Org . "8.0"))
1136 (defcustom org-show-entry-below '((default . nil))
1137 "Non-nil means show the entry below a headline when revealing a location.
1138 Org-mode often shows locations in an org-mode file which might have
1139 been invisible before. When this is set, the text below the headline that is
1140 exposed is also shown.
1142 By default this is off for all contexts.
1143 Instead of t, this can also be an alist specifying this option for different
1144 contexts. See `org-show-hierarchy-above' for valid contexts."
1145 :group 'org-reveal-location
1146 :type org-context-choice)
1148 (defcustom org-indirect-buffer-display 'other-window
1149 "How should indirect tree buffers be displayed?
1150 This applies to indirect buffers created with the commands
1151 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1152 Valid values are:
1153 current-window Display in the current window
1154 other-window Just display in another window.
1155 dedicated-frame Create one new frame, and re-use it each time.
1156 new-frame Make a new frame each time. Note that in this case
1157 previously-made indirect buffers are kept, and you need to
1158 kill these buffers yourself."
1159 :group 'org-structure
1160 :group 'org-agenda-windows
1161 :type '(choice
1162 (const :tag "In current window" current-window)
1163 (const :tag "In current frame, other window" other-window)
1164 (const :tag "Each time a new frame" new-frame)
1165 (const :tag "One dedicated frame" dedicated-frame)))
1167 (defcustom org-use-speed-commands nil
1168 "Non-nil means activate single letter commands at beginning of a headline.
1169 This may also be a function to test for appropriate locations where speed
1170 commands should be active.
1172 For example, to activate speed commands when the point is on any
1173 star at the beginning of the headline, you can do this:
1175 (setq org-use-speed-commands
1176 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1177 :group 'org-structure
1178 :type '(choice
1179 (const :tag "Never" nil)
1180 (const :tag "At beginning of headline stars" t)
1181 (function)))
1183 (defcustom org-speed-commands-user nil
1184 "Alist of additional speed commands.
1185 This list will be checked before `org-speed-commands-default'
1186 when the variable `org-use-speed-commands' is non-nil
1187 and when the cursor is at the beginning of a headline.
1188 The car if each entry is a string with a single letter, which must
1189 be assigned to `self-insert-command' in the global map.
1190 The cdr is either a command to be called interactively, a function
1191 to be called, or a form to be evaluated.
1192 An entry that is just a list with a single string will be interpreted
1193 as a descriptive headline that will be added when listing the speed
1194 commands in the Help buffer using the `?' speed command."
1195 :group 'org-structure
1196 :type '(repeat :value ("k" . ignore)
1197 (choice :value ("k" . ignore)
1198 (list :tag "Descriptive Headline" (string :tag "Headline"))
1199 (cons :tag "Letter and Command"
1200 (string :tag "Command letter")
1201 (choice
1202 (function)
1203 (sexp))))))
1205 (defcustom org-bookmark-names-plist
1206 '(:last-capture "org-capture-last-stored"
1207 :last-refile "org-refile-last-stored"
1208 :last-capture-marker "org-capture-last-stored-marker")
1209 "Names for bookmarks automatically set by some Org commands.
1210 This can provide strings as names for a number of bookmarks Org sets
1211 automatically. The following keys are currently implemented:
1212 :last-capture
1213 :last-capture-marker
1214 :last-refile
1215 When a key does not show up in the property list, the corresponding bookmark
1216 is not set."
1217 :group 'org-structure
1218 :type 'plist)
1220 (defgroup org-cycle nil
1221 "Options concerning visibility cycling in Org-mode."
1222 :tag "Org Cycle"
1223 :group 'org-structure)
1225 (defcustom org-cycle-skip-children-state-if-no-children t
1226 "Non-nil means skip CHILDREN state in entries that don't have any."
1227 :group 'org-cycle
1228 :type 'boolean)
1230 (defcustom org-cycle-max-level nil
1231 "Maximum level which should still be subject to visibility cycling.
1232 Levels higher than this will, for cycling, be treated as text, not a headline.
1233 When `org-odd-levels-only' is set, a value of N in this variable actually
1234 means 2N-1 stars as the limiting headline.
1235 When nil, cycle all levels.
1236 Note that the limiting level of cycling is also influenced by
1237 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1238 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1239 than its value."
1240 :group 'org-cycle
1241 :type '(choice
1242 (const :tag "No limit" nil)
1243 (integer :tag "Maximum level")))
1245 (defcustom org-hide-block-startup nil
1246 "Non-nil means entering Org-mode will fold all blocks.
1247 This can also be set in on a per-file basis with
1249 #+STARTUP: hideblocks
1250 #+STARTUP: showblocks"
1251 :group 'org-startup
1252 :group 'org-cycle
1253 :type 'boolean)
1255 (defcustom org-cycle-global-at-bob nil
1256 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1257 This makes it possible to do global cycling without having to use S-TAB or
1258 \\[universal-argument] TAB. For this special case to work, the first line
1259 of the buffer must not be a headline -- it may be empty or some other text.
1260 When used in this way, `org-cycle-hook' is disabled temporarily to make
1261 sure the cursor stays at the beginning of the buffer. When this option is
1262 nil, don't do anything special at the beginning of the buffer."
1263 :group 'org-cycle
1264 :type 'boolean)
1266 (defcustom org-cycle-level-after-item/entry-creation t
1267 "Non-nil means cycle entry level or item indentation in new empty entries.
1269 When the cursor is at the end of an empty headline, i.e., with only stars
1270 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1271 and then all possible ancestor states, before returning to the original state.
1272 This makes data entry extremely fast: M-RET to create a new headline,
1273 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1275 When the cursor is at the end of an empty plain list item, one TAB will
1276 make it a subitem, two or more tabs will back up to make this an item
1277 higher up in the item hierarchy."
1278 :group 'org-cycle
1279 :type 'boolean)
1281 (defcustom org-cycle-emulate-tab t
1282 "Where should `org-cycle' emulate TAB.
1283 nil Never
1284 white Only in completely white lines
1285 whitestart Only at the beginning of lines, before the first non-white char
1286 t Everywhere except in headlines
1287 exc-hl-bol Everywhere except at the start of a headline
1288 If TAB is used in a place where it does not emulate TAB, the current subtree
1289 visibility is cycled."
1290 :group 'org-cycle
1291 :type '(choice (const :tag "Never" nil)
1292 (const :tag "Only in completely white lines" white)
1293 (const :tag "Before first char in a line" whitestart)
1294 (const :tag "Everywhere except in headlines" t)
1295 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1297 (defcustom org-cycle-separator-lines 2
1298 "Number of empty lines needed to keep an empty line between collapsed trees.
1299 If you leave an empty line between the end of a subtree and the following
1300 headline, this empty line is hidden when the subtree is folded.
1301 Org-mode will leave (exactly) one empty line visible if the number of
1302 empty lines is equal or larger to the number given in this variable.
1303 So the default 2 means at least 2 empty lines after the end of a subtree
1304 are needed to produce free space between a collapsed subtree and the
1305 following headline.
1307 If the number is negative, and the number of empty lines is at least -N,
1308 all empty lines are shown.
1310 Special case: when 0, never leave empty lines in collapsed view."
1311 :group 'org-cycle
1312 :type 'integer)
1313 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1315 (defcustom org-pre-cycle-hook nil
1316 "Hook that is run before visibility cycling is happening.
1317 The function(s) in this hook must accept a single argument which indicates
1318 the new state that will be set right after running this hook. The
1319 argument is a symbol. Before a global state change, it can have the values
1320 `overview', `content', or `all'. Before a local state change, it can have
1321 the values `folded', `children', or `subtree'."
1322 :group 'org-cycle
1323 :type 'hook)
1325 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1326 org-cycle-hide-drawers
1327 org-cycle-hide-inline-tasks
1328 org-cycle-show-empty-lines
1329 org-optimize-window-after-visibility-change)
1330 "Hook that is run after `org-cycle' has changed the buffer visibility.
1331 The function(s) in this hook must accept a single argument which indicates
1332 the new state that was set by the most recent `org-cycle' command. The
1333 argument is a symbol. After a global state change, it can have the values
1334 `overview', `contents', or `all'. After a local state change, it can have
1335 the values `folded', `children', or `subtree'."
1336 :group 'org-cycle
1337 :type 'hook)
1339 (defgroup org-edit-structure nil
1340 "Options concerning structure editing in Org-mode."
1341 :tag "Org Edit Structure"
1342 :group 'org-structure)
1344 (defcustom org-odd-levels-only nil
1345 "Non-nil means skip even levels and only use odd levels for the outline.
1346 This has the effect that two stars are being added/taken away in
1347 promotion/demotion commands. It also influences how levels are
1348 handled by the exporters.
1349 Changing it requires restart of `font-lock-mode' to become effective
1350 for fontification also in regions already fontified.
1351 You may also set this on a per-file basis by adding one of the following
1352 lines to the buffer:
1354 #+STARTUP: odd
1355 #+STARTUP: oddeven"
1356 :group 'org-edit-structure
1357 :group 'org-appearance
1358 :type 'boolean)
1360 (defcustom org-adapt-indentation t
1361 "Non-nil means adapt indentation to outline node level.
1363 When this variable is set, Org assumes that you write outlines by
1364 indenting text in each node to align with the headline (after the stars).
1365 The following issues are influenced by this variable:
1367 - When this is set and the *entire* text in an entry is indented, the
1368 indentation is increased by one space in a demotion command, and
1369 decreased by one in a promotion command. If any line in the entry
1370 body starts with text at column 0, indentation is not changed at all.
1372 - Property drawers and planning information is inserted indented when
1373 this variable s set. When nil, they will not be indented.
1375 - TAB indents a line relative to context. The lines below a headline
1376 will be indented when this variable is set.
1378 Note that this is all about true indentation, by adding and removing
1379 space characters. See also `org-indent.el' which does level-dependent
1380 indentation in a virtual way, i.e. at display time in Emacs."
1381 :group 'org-edit-structure
1382 :type 'boolean)
1384 (defcustom org-special-ctrl-a/e nil
1385 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1387 When t, `C-a' will bring back the cursor to the beginning of the
1388 headline text, i.e. after the stars and after a possible TODO
1389 keyword. In an item, this will be the position after bullet and
1390 check-box, if any. When the cursor is already at that position,
1391 another `C-a' will bring it to the beginning of the line.
1393 `C-e' will jump to the end of the headline, ignoring the presence
1394 of tags in the headline. A second `C-e' will then jump to the
1395 true end of the line, after any tags. This also means that, when
1396 this variable is non-nil, `C-e' also will never jump beyond the
1397 end of the heading of a folded section, i.e. not after the
1398 ellipses.
1400 When set to the symbol `reversed', the first `C-a' or `C-e' works
1401 normally, going to the true line boundary first. Only a directly
1402 following, identical keypress will bring the cursor to the
1403 special positions.
1405 This may also be a cons cell where the behavior for `C-a' and
1406 `C-e' is set separately."
1407 :group 'org-edit-structure
1408 :type '(choice
1409 (const :tag "off" nil)
1410 (const :tag "on: after stars/bullet and before tags first" t)
1411 (const :tag "reversed: true line boundary first" reversed)
1412 (cons :tag "Set C-a and C-e separately"
1413 (choice :tag "Special C-a"
1414 (const :tag "off" nil)
1415 (const :tag "on: after stars/bullet first" t)
1416 (const :tag "reversed: before stars/bullet first" reversed))
1417 (choice :tag "Special C-e"
1418 (const :tag "off" nil)
1419 (const :tag "on: before tags first" t)
1420 (const :tag "reversed: after tags first" reversed)))))
1421 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1423 (defcustom org-special-ctrl-k nil
1424 "Non-nil means `C-k' will behave specially in headlines.
1425 When nil, `C-k' will call the default `kill-line' command.
1426 When t, the following will happen while the cursor is in the headline:
1428 - When the cursor is at the beginning of a headline, kill the entire
1429 line and possible the folded subtree below the line.
1430 - When in the middle of the headline text, kill the headline up to the tags.
1431 - When after the headline text, kill the tags."
1432 :group 'org-edit-structure
1433 :type 'boolean)
1435 (defcustom org-ctrl-k-protect-subtree nil
1436 "Non-nil means, do not delete a hidden subtree with C-k.
1437 When set to the symbol `error', simply throw an error when C-k is
1438 used to kill (part-of) a headline that has hidden text behind it.
1439 Any other non-nil value will result in a query to the user, if it is
1440 OK to kill that hidden subtree. When nil, kill without remorse."
1441 :group 'org-edit-structure
1442 :version "24.1"
1443 :type '(choice
1444 (const :tag "Do not protect hidden subtrees" nil)
1445 (const :tag "Protect hidden subtrees with a security query" t)
1446 (const :tag "Never kill a hidden subtree with C-k" error)))
1448 (defcustom org-special-ctrl-o t
1449 "Non-nil means, make `C-o' insert a row in tables."
1450 :group 'org-edit-structure
1451 :type 'boolean)
1453 (defcustom org-catch-invisible-edits nil
1454 "Check if in invisible region before inserting or deleting a character.
1455 Valid values are:
1457 nil Do not check, so just do invisible edits.
1458 error Throw an error and do nothing.
1459 show Make point visible, and do the requested edit.
1460 show-and-error Make point visible, then throw an error and abort the edit.
1461 smart Make point visible, and do insertion/deletion if it is
1462 adjacent to visible text and the change feels predictable.
1463 Never delete a previously invisible character or add in the
1464 middle or right after an invisible region. Basically, this
1465 allows insertion and backward-delete right before ellipses.
1466 FIXME: maybe in this case we should not even show?"
1467 :group 'org-edit-structure
1468 :version "24.1"
1469 :type '(choice
1470 (const :tag "Do not check" nil)
1471 (const :tag "Throw error when trying to edit" error)
1472 (const :tag "Unhide, but do not do the edit" show-and-error)
1473 (const :tag "Show invisible part and do the edit" show)
1474 (const :tag "Be smart and do the right thing" smart)))
1476 (defcustom org-yank-folded-subtrees t
1477 "Non-nil means when yanking subtrees, fold them.
1478 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1479 it starts with a heading and all other headings in it are either children
1480 or siblings, then fold all the subtrees. However, do this only if no
1481 text after the yank would be swallowed into a folded tree by this action."
1482 :group 'org-edit-structure
1483 :type 'boolean)
1485 (defcustom org-yank-adjusted-subtrees nil
1486 "Non-nil means when yanking subtrees, adjust the level.
1487 With this setting, `org-paste-subtree' is used to insert the subtree, see
1488 this function for details."
1489 :group 'org-edit-structure
1490 :type 'boolean)
1492 (defcustom org-M-RET-may-split-line '((default . t))
1493 "Non-nil means M-RET will split the line at the cursor position.
1494 When nil, it will go to the end of the line before making a
1495 new line.
1496 You may also set this option in a different way for different
1497 contexts. Valid contexts are:
1499 headline when creating a new headline
1500 item when creating a new item
1501 table in a table field
1502 default the value to be used for all contexts not explicitly
1503 customized"
1504 :group 'org-structure
1505 :group 'org-table
1506 :type '(choice
1507 (const :tag "Always" t)
1508 (const :tag "Never" nil)
1509 (repeat :greedy t :tag "Individual contexts"
1510 (cons
1511 (choice :tag "Context"
1512 (const headline)
1513 (const item)
1514 (const table)
1515 (const default))
1516 (boolean)))))
1519 (defcustom org-insert-heading-respect-content nil
1520 "Non-nil means insert new headings after the current subtree.
1521 When nil, the new heading is created directly after the current line.
1522 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1523 this variable on for the duration of the command."
1524 :group 'org-structure
1525 :type 'boolean)
1527 (defcustom org-blank-before-new-entry '((heading . auto)
1528 (plain-list-item . auto))
1529 "Should `org-insert-heading' leave a blank line before new heading/item?
1530 The value is an alist, with `heading' and `plain-list-item' as CAR,
1531 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1532 which case Org will look at the surrounding headings/items and try to
1533 make an intelligent decision whether to insert a blank line or not.
1535 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1536 the setting here is ignored and no empty line is inserted to avoid breaking
1537 the list structure."
1538 :group 'org-edit-structure
1539 :type '(list
1540 (cons (const heading)
1541 (choice (const :tag "Never" nil)
1542 (const :tag "Always" t)
1543 (const :tag "Auto" auto)))
1544 (cons (const plain-list-item)
1545 (choice (const :tag "Never" nil)
1546 (const :tag "Always" t)
1547 (const :tag "Auto" auto)))))
1549 (defcustom org-insert-heading-hook nil
1550 "Hook being run after inserting a new heading."
1551 :group 'org-edit-structure
1552 :type 'hook)
1554 (defcustom org-enable-fixed-width-editor t
1555 "Non-nil means lines starting with \":\" are treated as fixed-width.
1556 This currently only means they are never auto-wrapped.
1557 When nil, such lines will be treated like ordinary lines.
1558 See also the QUOTE keyword."
1559 :group 'org-edit-structure
1560 :type 'boolean)
1562 (defcustom org-goto-auto-isearch t
1563 "Non-nil means typing characters in `org-goto' starts incremental search.
1564 When nil, you can use these keybindings to navigate the buffer:
1566 q Quit the org-goto interface
1567 n Go to the next visible heading
1568 p Go to the previous visible heading
1569 f Go one heading forward on same level
1570 b Go one heading backward on same level
1571 u Go one heading up"
1572 :group 'org-edit-structure
1573 :type 'boolean)
1575 (defgroup org-sparse-trees nil
1576 "Options concerning sparse trees in Org-mode."
1577 :tag "Org Sparse Trees"
1578 :group 'org-structure)
1580 (defcustom org-highlight-sparse-tree-matches t
1581 "Non-nil means highlight all matches that define a sparse tree.
1582 The highlights will automatically disappear the next time the buffer is
1583 changed by an edit command."
1584 :group 'org-sparse-trees
1585 :type 'boolean)
1587 (defcustom org-remove-highlights-with-change t
1588 "Non-nil means any change to the buffer will remove temporary highlights.
1589 Such highlights are created by `org-occur' and `org-clock-display'.
1590 When nil, `C-c C-c needs to be used to get rid of the highlights.
1591 The highlights created by `org-preview-latex-fragment' always need
1592 `C-c C-c' to be removed."
1593 :group 'org-sparse-trees
1594 :group 'org-time
1595 :type 'boolean)
1598 (defcustom org-occur-hook '(org-first-headline-recenter)
1599 "Hook that is run after `org-occur' has constructed a sparse tree.
1600 This can be used to recenter the window to show as much of the structure
1601 as possible."
1602 :group 'org-sparse-trees
1603 :type 'hook)
1605 (defgroup org-imenu-and-speedbar nil
1606 "Options concerning imenu and speedbar in Org-mode."
1607 :tag "Org Imenu and Speedbar"
1608 :group 'org-structure)
1610 (defcustom org-imenu-depth 2
1611 "The maximum level for Imenu access to Org-mode headlines.
1612 This also applied for speedbar access."
1613 :group 'org-imenu-and-speedbar
1614 :type 'integer)
1616 (defgroup org-table nil
1617 "Options concerning tables in Org-mode."
1618 :tag "Org Table"
1619 :group 'org)
1621 (defcustom org-enable-table-editor 'optimized
1622 "Non-nil means lines starting with \"|\" are handled by the table editor.
1623 When nil, such lines will be treated like ordinary lines.
1625 When equal to the symbol `optimized', the table editor will be optimized to
1626 do the following:
1627 - Automatic overwrite mode in front of whitespace in table fields.
1628 This makes the structure of the table stay in tact as long as the edited
1629 field does not exceed the column width.
1630 - Minimize the number of realigns. Normally, the table is aligned each time
1631 TAB or RET are pressed to move to another field. With optimization this
1632 happens only if changes to a field might have changed the column width.
1633 Optimization requires replacing the functions `self-insert-command',
1634 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1635 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1636 very good at guessing when a re-align will be necessary, but you can always
1637 force one with \\[org-ctrl-c-ctrl-c].
1639 If you would like to use the optimized version in Org-mode, but the
1640 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1642 This variable can be used to turn on and off the table editor during a session,
1643 but in order to toggle optimization, a restart is required.
1645 See also the variable `org-table-auto-blank-field'."
1646 :group 'org-table
1647 :type '(choice
1648 (const :tag "off" nil)
1649 (const :tag "on" t)
1650 (const :tag "on, optimized" optimized)))
1652 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1653 (version<= emacs-version "24.1"))
1654 "Non-nil means cluster self-insert commands for undo when possible.
1655 If this is set, then, like in the Emacs command loop, 20 consecutive
1656 characters will be undone together.
1657 This is configurable, because there is some impact on typing performance."
1658 :group 'org-table
1659 :type 'boolean)
1661 (defcustom org-table-tab-recognizes-table.el t
1662 "Non-nil means TAB will automatically notice a table.el table.
1663 When it sees such a table, it moves point into it and - if necessary -
1664 calls `table-recognize-table'."
1665 :group 'org-table-editing
1666 :type 'boolean)
1668 (defgroup org-link nil
1669 "Options concerning links in Org-mode."
1670 :tag "Org Link"
1671 :group 'org)
1673 (defvar org-link-abbrev-alist-local nil
1674 "Buffer-local version of `org-link-abbrev-alist', which see.
1675 The value of this is taken from the #+LINK lines.")
1676 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1678 (defcustom org-link-abbrev-alist nil
1679 "Alist of link abbreviations.
1680 The car of each element is a string, to be replaced at the start of a link.
1681 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1682 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1684 [[linkkey:tag][description]]
1686 The 'linkkey' must be a word word, starting with a letter, followed
1687 by letters, numbers, '-' or '_'.
1689 If REPLACE is a string, the tag will simply be appended to create the link.
1690 If the string contains \"%s\", the tag will be inserted there. If the string
1691 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1692 at that point (see the function `url-hexify-string'). If the string contains
1693 the specifier \"%(my-function)\", then the custom function `my-function' will
1694 be invoked: this function takes the tag as its only argument and must return
1695 a string.
1697 REPLACE may also be a function that will be called with the tag as the
1698 only argument to create the link, which should be returned as a string.
1700 See the manual for examples."
1701 :group 'org-link
1702 :type '(repeat
1703 (cons
1704 (string :tag "Protocol")
1705 (choice
1706 (string :tag "Format")
1707 (function)))))
1709 (defcustom org-descriptive-links t
1710 "Non-nil means Org will display descriptive links.
1711 E.g. [[http://orgmode.org][Org website]] will be displayed as
1712 \"Org Website\", hiding the link itself and just displaying its
1713 description. When set to `nil', Org will display the full links
1714 literally.
1716 You can interactively set the value of this variable by calling
1717 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1718 :group 'org-link
1719 :type 'boolean)
1721 (defcustom org-link-file-path-type 'adaptive
1722 "How the path name in file links should be stored.
1723 Valid values are:
1725 relative Relative to the current directory, i.e. the directory of the file
1726 into which the link is being inserted.
1727 absolute Absolute path, if possible with ~ for home directory.
1728 noabbrev Absolute path, no abbreviation of home directory.
1729 adaptive Use relative path for files in the current directory and sub-
1730 directories of it. For other files, use an absolute path."
1731 :group 'org-link
1732 :type '(choice
1733 (const relative)
1734 (const absolute)
1735 (const noabbrev)
1736 (const adaptive)))
1738 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1739 "Types of links that should be activated in Org-mode files.
1740 This is a list of symbols, each leading to the activation of a certain link
1741 type. In principle, it does not hurt to turn on most link types - there may
1742 be a small gain when turning off unused link types. The types are:
1744 bracket The recommended [[link][description]] or [[link]] links with hiding.
1745 angle Links in angular brackets that may contain whitespace like
1746 <bbdb:Carsten Dominik>.
1747 plain Plain links in normal text, no whitespace, like http://google.com.
1748 radio Text that is matched by a radio target, see manual for details.
1749 tag Tag settings in a headline (link to tag search).
1750 date Time stamps (link to calendar).
1751 footnote Footnote labels.
1753 Changing this variable requires a restart of Emacs to become effective."
1754 :group 'org-link
1755 :type '(set :greedy t
1756 (const :tag "Double bracket links" bracket)
1757 (const :tag "Angular bracket links" angle)
1758 (const :tag "Plain text links" plain)
1759 (const :tag "Radio target matches" radio)
1760 (const :tag "Tags" tag)
1761 (const :tag "Timestamps" date)
1762 (const :tag "Footnotes" footnote)))
1764 (defcustom org-make-link-description-function nil
1765 "Function to use for generating link descriptions from links.
1766 When nil, the link location will be used. This function must take
1767 two parameters: the first one is the link, the second one is the
1768 description generated by `org-insert-link'. The function should
1769 return the description to use."
1770 :group 'org-link
1771 :type '(choice (const nil) (function)))
1773 (defgroup org-link-store nil
1774 "Options concerning storing links in Org-mode."
1775 :tag "Org Store Link"
1776 :group 'org-link)
1778 (defcustom org-url-hexify-p t
1779 "When non-nil, hexify URL when creating a link."
1780 :type 'boolean
1781 :version "24.3"
1782 :group 'org-link-store)
1784 (defcustom org-email-link-description-format "Email %c: %.30s"
1785 "Format of the description part of a link to an email or usenet message.
1786 The following %-escapes will be replaced by corresponding information:
1788 %F full \"From\" field
1789 %f name, taken from \"From\" field, address if no name
1790 %T full \"To\" field
1791 %t first name in \"To\" field, address if no name
1792 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1793 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1794 %s subject
1795 %d date
1796 %m message-id.
1798 You may use normal field width specification between the % and the letter.
1799 This is for example useful to limit the length of the subject.
1801 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1802 :group 'org-link-store
1803 :type 'string)
1805 (defcustom org-from-is-user-regexp
1806 (let (r1 r2)
1807 (when (and user-mail-address (not (string= user-mail-address "")))
1808 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1809 (when (and user-full-name (not (string= user-full-name "")))
1810 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1811 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1812 "Regexp matched against the \"From:\" header of an email or usenet message.
1813 It should match if the message is from the user him/herself."
1814 :group 'org-link-store
1815 :type 'regexp)
1817 (defcustom org-context-in-file-links t
1818 "Non-nil means file links from `org-store-link' contain context.
1819 A search string will be added to the file name with :: as separator and
1820 used to find the context when the link is activated by the command
1821 `org-open-at-point'. When this option is t, the entire active region
1822 will be placed in the search string of the file link. If set to a
1823 positive integer, only the first n lines of context will be stored.
1825 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1826 negates this setting for the duration of the command."
1827 :group 'org-link-store
1828 :type '(choice boolean integer))
1830 (defcustom org-keep-stored-link-after-insertion nil
1831 "Non-nil means keep link in list for entire session.
1833 The command `org-store-link' adds a link pointing to the current
1834 location to an internal list. These links accumulate during a session.
1835 The command `org-insert-link' can be used to insert links into any
1836 Org-mode file (offering completion for all stored links). When this
1837 option is nil, every link which has been inserted once using \\[org-insert-link]
1838 will be removed from the list, to make completing the unused links
1839 more efficient."
1840 :group 'org-link-store
1841 :type 'boolean)
1843 (defgroup org-link-follow nil
1844 "Options concerning following links in Org-mode."
1845 :tag "Org Follow Link"
1846 :group 'org-link)
1848 (defcustom org-link-translation-function nil
1849 "Function to translate links with different syntax to Org syntax.
1850 This can be used to translate links created for example by the Planner
1851 or emacs-wiki packages to Org syntax.
1852 The function must accept two parameters, a TYPE containing the link
1853 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1854 which is everything after the link protocol. It should return a cons
1855 with possibly modified values of type and path.
1856 Org contains a function for this, so if you set this variable to
1857 `org-translate-link-from-planner', you should be able follow many
1858 links created by planner."
1859 :group 'org-link-follow
1860 :type '(choice (const nil) (function)))
1862 (defcustom org-follow-link-hook nil
1863 "Hook that is run after a link has been followed."
1864 :group 'org-link-follow
1865 :type 'hook)
1867 (defcustom org-tab-follows-link nil
1868 "Non-nil means on links TAB will follow the link.
1869 Needs to be set before org.el is loaded.
1870 This really should not be used, it does not make sense, and the
1871 implementation is bad."
1872 :group 'org-link-follow
1873 :type 'boolean)
1875 (defcustom org-return-follows-link nil
1876 "Non-nil means on links RET will follow the link.
1877 In tables, the special behavior of RET has precedence."
1878 :group 'org-link-follow
1879 :type 'boolean)
1881 (defcustom org-mouse-1-follows-link
1882 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1883 "Non-nil means mouse-1 on a link will follow the link.
1884 A longer mouse click will still set point. Does not work on XEmacs.
1885 Needs to be set before org.el is loaded."
1886 :group 'org-link-follow
1887 :version "24.4"
1888 :package-version '(Org . "8.3")
1889 :type '(choice
1890 (const :tag "A double click follows the link" double)
1891 (const :tag "Unconditionally follow the link with mouse-1" t)
1892 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1894 (defcustom org-mark-ring-length 4
1895 "Number of different positions to be recorded in the ring.
1896 Changing this requires a restart of Emacs to work correctly."
1897 :group 'org-link-follow
1898 :type 'integer)
1900 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1901 "Non-nil means internal links in Org files must exactly match a headline.
1902 When nil, the link search tries to match a phrase with all words
1903 in the search text."
1904 :group 'org-link-follow
1905 :version "24.1"
1906 :type '(choice
1907 (const :tag "Use fuzzy text search" nil)
1908 (const :tag "Match only exact headline" t)
1909 (const :tag "Match exact headline or query to create it"
1910 query-to-create)))
1912 (defcustom org-link-frame-setup
1913 '((vm . vm-visit-folder-other-frame)
1914 (vm-imap . vm-visit-imap-folder-other-frame)
1915 (gnus . org-gnus-no-new-news)
1916 (file . find-file-other-window)
1917 (wl . wl-other-frame))
1918 "Setup the frame configuration for following links.
1919 When following a link with Emacs, it may often be useful to display
1920 this link in another window or frame. This variable can be used to
1921 set this up for the different types of links.
1922 For VM, use any of
1923 `vm-visit-folder'
1924 `vm-visit-folder-other-window'
1925 `vm-visit-folder-other-frame'
1926 For Gnus, use any of
1927 `gnus'
1928 `gnus-other-frame'
1929 `org-gnus-no-new-news'
1930 For FILE, use any of
1931 `find-file'
1932 `find-file-other-window'
1933 `find-file-other-frame'
1934 For Wanderlust use any of
1935 `wl'
1936 `wl-other-frame'
1937 For the calendar, use the variable `calendar-setup'.
1938 For BBDB, it is currently only possible to display the matches in
1939 another window."
1940 :group 'org-link-follow
1941 :type '(list
1942 (cons (const vm)
1943 (choice
1944 (const vm-visit-folder)
1945 (const vm-visit-folder-other-window)
1946 (const vm-visit-folder-other-frame)))
1947 (cons (const vm-imap)
1948 (choice
1949 (const vm-visit-imap-folder)
1950 (const vm-visit-imap-folder-other-window)
1951 (const vm-visit-imap-folder-other-frame)))
1952 (cons (const gnus)
1953 (choice
1954 (const gnus)
1955 (const gnus-other-frame)
1956 (const org-gnus-no-new-news)))
1957 (cons (const file)
1958 (choice
1959 (const find-file)
1960 (const find-file-other-window)
1961 (const find-file-other-frame)))
1962 (cons (const wl)
1963 (choice
1964 (const wl)
1965 (const wl-other-frame)))))
1967 (defcustom org-display-internal-link-with-indirect-buffer nil
1968 "Non-nil means use indirect buffer to display infile links.
1969 Activating internal links (from one location in a file to another location
1970 in the same file) normally just jumps to the location. When the link is
1971 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1972 is displayed in
1973 another window. When this option is set, the other window actually displays
1974 an indirect buffer clone of the current buffer, to avoid any visibility
1975 changes to the current buffer."
1976 :group 'org-link-follow
1977 :type 'boolean)
1979 (defcustom org-open-non-existing-files nil
1980 "Non-nil means `org-open-file' will open non-existing files.
1981 When nil, an error will be generated.
1982 This variable applies only to external applications because they
1983 might choke on non-existing files. If the link is to a file that
1984 will be opened in Emacs, the variable is ignored."
1985 :group 'org-link-follow
1986 :type 'boolean)
1988 (defcustom org-open-directory-means-index-dot-org nil
1989 "Non-nil means a link to a directory really means to index.org.
1990 When nil, following a directory link will run dired or open a finder/explorer
1991 window on that directory."
1992 :group 'org-link-follow
1993 :type 'boolean)
1995 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1996 "Function and arguments to call for following mailto links.
1997 This is a list with the first element being a Lisp function, and the
1998 remaining elements being arguments to the function. In string arguments,
1999 %a will be replaced by the address, and %s will be replaced by the subject
2000 if one was given like in <mailto:arthur@galaxy.org::this subject>."
2001 :group 'org-link-follow
2002 :type '(choice
2003 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
2004 (const :tag "compose-mail" (compose-mail "%a" "%s"))
2005 (const :tag "message-mail" (message-mail "%a" "%s"))
2006 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
2008 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2009 "Non-nil means ask for confirmation before executing shell links.
2010 Shell links can be dangerous: just think about a link
2012 [[shell:rm -rf ~/*][Google Search]]
2014 This link would show up in your Org-mode document as \"Google Search\",
2015 but really it would remove your entire home directory.
2016 Therefore we advise against setting this variable to nil.
2017 Just change it to `y-or-n-p' if you want to confirm with a
2018 single keystroke rather than having to type \"yes\"."
2019 :group 'org-link-follow
2020 :type '(choice
2021 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2022 (const :tag "with y-or-n (faster)" y-or-n-p)
2023 (const :tag "no confirmation (dangerous)" nil)))
2024 (put 'org-confirm-shell-link-function
2025 'safe-local-variable
2026 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2028 (defcustom org-confirm-shell-link-not-regexp ""
2029 "A regexp to skip confirmation for shell links."
2030 :group 'org-link-follow
2031 :version "24.1"
2032 :type 'regexp)
2034 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2035 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2036 Elisp links can be dangerous: just think about a link
2038 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2040 This link would show up in your Org-mode document as \"Google Search\",
2041 but really it would remove your entire home directory.
2042 Therefore we advise against setting this variable to nil.
2043 Just change it to `y-or-n-p' if you want to confirm with a
2044 single keystroke rather than having to type \"yes\"."
2045 :group 'org-link-follow
2046 :type '(choice
2047 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2048 (const :tag "with y-or-n (faster)" y-or-n-p)
2049 (const :tag "no confirmation (dangerous)" nil)))
2050 (put 'org-confirm-shell-link-function
2051 'safe-local-variable
2052 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2054 (defcustom org-confirm-elisp-link-not-regexp ""
2055 "A regexp to skip confirmation for Elisp links."
2056 :group 'org-link-follow
2057 :version "24.1"
2058 :type 'regexp)
2060 (defconst org-file-apps-defaults-gnu
2061 '((remote . emacs)
2062 (system . mailcap)
2063 (t . mailcap))
2064 "Default file applications on a UNIX or GNU/Linux system.
2065 See `org-file-apps'.")
2067 (defconst org-file-apps-defaults-macosx
2068 '((remote . emacs)
2069 (t . "open %s")
2070 (system . "open %s")
2071 ("ps.gz" . "gv %s")
2072 ("eps.gz" . "gv %s")
2073 ("dvi" . "xdvi %s")
2074 ("fig" . "xfig %s"))
2075 "Default file applications on a MacOS X system.
2076 The system \"open\" is known as a default, but we use X11 applications
2077 for some files for which the OS does not have a good default.
2078 See `org-file-apps'.")
2080 (defconst org-file-apps-defaults-windowsnt
2081 (list
2082 '(remote . emacs)
2083 (cons t
2084 (list (if (featurep 'xemacs)
2085 'mswindows-shell-execute
2086 'w32-shell-execute)
2087 "open" 'file))
2088 (cons 'system
2089 (list (if (featurep 'xemacs)
2090 'mswindows-shell-execute
2091 'w32-shell-execute)
2092 "open" 'file)))
2093 "Default file applications on a Windows NT system.
2094 The system \"open\" is used for most files.
2095 See `org-file-apps'.")
2097 (defcustom org-file-apps
2098 '((auto-mode . emacs)
2099 ("\\.mm\\'" . default)
2100 ("\\.x?html?\\'" . default)
2101 ("\\.pdf\\'" . default))
2102 "External applications for opening `file:path' items in a document.
2103 Org-mode uses system defaults for different file types, but
2104 you can use this variable to set the application for a given file
2105 extension. The entries in this list are cons cells where the car identifies
2106 files and the cdr the corresponding command. Possible values for the
2107 file identifier are
2108 \"string\" A string as a file identifier can be interpreted in different
2109 ways, depending on its contents:
2111 - Alphanumeric characters only:
2112 Match links with this file extension.
2113 Example: (\"pdf\" . \"evince %s\")
2114 to open PDFs with evince.
2116 - Regular expression: Match links where the
2117 filename matches the regexp. If you want to
2118 use groups here, use shy groups.
2120 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2121 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2122 to open *.html and *.xhtml with firefox.
2124 - Regular expression which contains (non-shy) groups:
2125 Match links where the whole link, including \"::\", and
2126 anything after that, matches the regexp.
2127 In a custom command string, %1, %2, etc. are replaced with
2128 the parts of the link that were matched by the groups.
2129 For backwards compatibility, if a command string is given
2130 that does not use any of the group matches, this case is
2131 handled identically to the second one (i.e. match against
2132 file name only).
2133 In a custom lisp form, you can access the group matches with
2134 (match-string n link).
2136 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2137 to open [[file:document.pdf::5]] with evince at page 5.
2139 `directory' Matches a directory
2140 `remote' Matches a remote file, accessible through tramp or efs.
2141 Remote files most likely should be visited through Emacs
2142 because external applications cannot handle such paths.
2143 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2144 so all files Emacs knows how to handle. Using this with
2145 command `emacs' will open most files in Emacs. Beware that this
2146 will also open html files inside Emacs, unless you add
2147 (\"html\" . default) to the list as well.
2148 t Default for files not matched by any of the other options.
2149 `system' The system command to open files, like `open' on Windows
2150 and Mac OS X, and mailcap under GNU/Linux. This is the command
2151 that will be selected if you call `C-c C-o' with a double
2152 \\[universal-argument] \\[universal-argument] prefix.
2154 Possible values for the command are:
2155 `emacs' The file will be visited by the current Emacs process.
2156 `default' Use the default application for this file type, which is the
2157 association for t in the list, most likely in the system-specific
2158 part.
2159 This can be used to overrule an unwanted setting in the
2160 system-specific variable.
2161 `system' Use the system command for opening files, like \"open\".
2162 This command is specified by the entry whose car is `system'.
2163 Most likely, the system-specific version of this variable
2164 does define this command, but you can overrule/replace it
2165 here.
2166 string A command to be executed by a shell; %s will be replaced
2167 by the path to the file.
2168 sexp A Lisp form which will be evaluated. The file path will
2169 be available in the Lisp variable `file'.
2170 For more examples, see the system specific constants
2171 `org-file-apps-defaults-macosx'
2172 `org-file-apps-defaults-windowsnt'
2173 `org-file-apps-defaults-gnu'."
2174 :group 'org-link-follow
2175 :type '(repeat
2176 (cons (choice :value ""
2177 (string :tag "Extension")
2178 (const :tag "System command to open files" system)
2179 (const :tag "Default for unrecognized files" t)
2180 (const :tag "Remote file" remote)
2181 (const :tag "Links to a directory" directory)
2182 (const :tag "Any files that have Emacs modes"
2183 auto-mode))
2184 (choice :value ""
2185 (const :tag "Visit with Emacs" emacs)
2186 (const :tag "Use default" default)
2187 (const :tag "Use the system command" system)
2188 (string :tag "Command")
2189 (sexp :tag "Lisp form")))))
2191 (defcustom org-doi-server-url "http://dx.doi.org/"
2192 "The URL of the DOI server."
2193 :type 'string
2194 :version "24.3"
2195 :group 'org-link-follow)
2197 (defgroup org-refile nil
2198 "Options concerning refiling entries in Org-mode."
2199 :tag "Org Refile"
2200 :group 'org)
2202 (defcustom org-directory "~/org"
2203 "Directory with org files.
2204 This is just a default location to look for Org files. There is no need
2205 at all to put your files into this directory. It is only used in the
2206 following situations:
2208 1. When a capture template specifies a target file that is not an
2209 absolute path. The path will then be interpreted relative to
2210 `org-directory'
2211 2. When a capture note is filed away in an interactive way (when exiting the
2212 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2213 with `org-directory' as the default path."
2214 :group 'org-refile
2215 :group 'org-capture
2216 :type 'directory)
2218 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2219 "Default target for storing notes.
2220 Used as a fall back file for org-capture.el, for templates that
2221 do not specify a target file."
2222 :group 'org-refile
2223 :group 'org-capture
2224 :type '(choice
2225 (const :tag "Default from remember-data-file" nil)
2226 file))
2228 (defcustom org-goto-interface 'outline
2229 "The default interface to be used for `org-goto'.
2230 Allowed values are:
2231 outline The interface shows an outline of the relevant file
2232 and the correct heading is found by moving through
2233 the outline or by searching with incremental search.
2234 outline-path-completion Headlines in the current buffer are offered via
2235 completion. This is the interface also used by
2236 the refile command."
2237 :group 'org-refile
2238 :type '(choice
2239 (const :tag "Outline" outline)
2240 (const :tag "Outline-path-completion" outline-path-completion)))
2242 (defcustom org-goto-max-level 5
2243 "Maximum target level when running `org-goto' with refile interface."
2244 :group 'org-refile
2245 :type 'integer)
2247 (defcustom org-reverse-note-order nil
2248 "Non-nil means store new notes at the beginning of a file or entry.
2249 When nil, new notes will be filed to the end of a file or entry.
2250 This can also be a list with cons cells of regular expressions that
2251 are matched against file names, and values."
2252 :group 'org-capture
2253 :group 'org-refile
2254 :type '(choice
2255 (const :tag "Reverse always" t)
2256 (const :tag "Reverse never" nil)
2257 (repeat :tag "By file name regexp"
2258 (cons regexp boolean))))
2260 (defcustom org-log-refile nil
2261 "Information to record when a task is refiled.
2263 Possible values are:
2265 nil Don't add anything
2266 time Add a time stamp to the task
2267 note Prompt for a note and add it with template `org-log-note-headings'
2269 This option can also be set with on a per-file-basis with
2271 #+STARTUP: nologrefile
2272 #+STARTUP: logrefile
2273 #+STARTUP: lognoterefile
2275 You can have local logging settings for a subtree by setting the LOGGING
2276 property to one or more of these keywords.
2278 When bulk-refiling from the agenda, the value `note' is forbidden and
2279 will temporarily be changed to `time'."
2280 :group 'org-refile
2281 :group 'org-progress
2282 :version "24.1"
2283 :type '(choice
2284 (const :tag "No logging" nil)
2285 (const :tag "Record timestamp" time)
2286 (const :tag "Record timestamp with note." note)))
2288 (defcustom org-refile-targets nil
2289 "Targets for refiling entries with \\[org-refile].
2290 This is a list of cons cells. Each cell contains:
2291 - a specification of the files to be considered, either a list of files,
2292 or a symbol whose function or variable value will be used to retrieve
2293 a file name or a list of file names. If you use `org-agenda-files' for
2294 that, all agenda files will be scanned for targets. Nil means consider
2295 headings in the current buffer.
2296 - A specification of how to find candidate refile targets. This may be
2297 any of:
2298 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2299 This tag has to be present in all target headlines, inheritance will
2300 not be considered.
2301 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2302 todo keyword.
2303 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2304 headlines that are refiling targets.
2305 - a cons cell (:level . N). Any headline of level N is considered a target.
2306 Note that, when `org-odd-levels-only' is set, level corresponds to
2307 order in hierarchy, not to the number of stars.
2308 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2309 Note that, when `org-odd-levels-only' is set, level corresponds to
2310 order in hierarchy, not to the number of stars.
2312 Each element of this list generates a set of possible targets.
2313 The union of these sets is presented (with completion) to
2314 the user by `org-refile'.
2316 You can set the variable `org-refile-target-verify-function' to a function
2317 to verify each headline found by the simple criteria above.
2319 When this variable is nil, all top-level headlines in the current buffer
2320 are used, equivalent to the value `((nil . (:level . 1))'."
2321 :group 'org-refile
2322 :type '(repeat
2323 (cons
2324 (choice :value org-agenda-files
2325 (const :tag "All agenda files" org-agenda-files)
2326 (const :tag "Current buffer" nil)
2327 (function) (variable) (file))
2328 (choice :tag "Identify target headline by"
2329 (cons :tag "Specific tag" (const :value :tag) (string))
2330 (cons :tag "TODO keyword" (const :value :todo) (string))
2331 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2332 (cons :tag "Level number" (const :value :level) (integer))
2333 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2335 (defcustom org-refile-target-verify-function nil
2336 "Function to verify if the headline at point should be a refile target.
2337 The function will be called without arguments, with point at the
2338 beginning of the headline. It should return t and leave point
2339 where it is if the headline is a valid target for refiling.
2341 If the target should not be selected, the function must return nil.
2342 In addition to this, it may move point to a place from where the search
2343 should be continued. For example, the function may decide that the entire
2344 subtree of the current entry should be excluded and move point to the end
2345 of the subtree."
2346 :group 'org-refile
2347 :type '(choice
2348 (const nil)
2349 (function)))
2351 (defcustom org-refile-use-cache nil
2352 "Non-nil means cache refile targets to speed up the process.
2353 The cache for a particular file will be updated automatically when
2354 the buffer has been killed, or when any of the marker used for flagging
2355 refile targets no longer points at a live buffer.
2356 If you have added new entries to a buffer that might themselves be targets,
2357 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2358 find that easier, `C-u C-u C-u C-c C-w'."
2359 :group 'org-refile
2360 :version "24.1"
2361 :type 'boolean)
2363 (defcustom org-refile-use-outline-path nil
2364 "Non-nil means provide refile targets as paths.
2365 So a level 3 headline will be available as level1/level2/level3.
2367 When the value is `file', also include the file name (without directory)
2368 into the path. In this case, you can also stop the completion after
2369 the file name, to get entries inserted as top level in the file.
2371 When `full-file-path', include the full file path."
2372 :group 'org-refile
2373 :type '(choice
2374 (const :tag "Not" nil)
2375 (const :tag "Yes" t)
2376 (const :tag "Start with file name" file)
2377 (const :tag "Start with full file path" full-file-path)))
2379 (defcustom org-outline-path-complete-in-steps t
2380 "Non-nil means complete the outline path in hierarchical steps.
2381 When Org-mode uses the refile interface to select an outline path
2382 \(see variable `org-refile-use-outline-path'), the completion of
2383 the path can be done is a single go, or if can be done in steps down
2384 the headline hierarchy. Going in steps is probably the best if you
2385 do not use a special completion package like `ido' or `icicles'.
2386 However, when using these packages, going in one step can be very
2387 fast, while still showing the whole path to the entry."
2388 :group 'org-refile
2389 :type 'boolean)
2391 (defcustom org-refile-allow-creating-parent-nodes nil
2392 "Non-nil means allow to create new nodes as refile targets.
2393 New nodes are then created by adding \"/new node name\" to the completion
2394 of an existing node. When the value of this variable is `confirm',
2395 new node creation must be confirmed by the user (recommended).
2396 When nil, the completion must match an existing entry.
2398 Note that, if the new heading is not seen by the criteria
2399 listed in `org-refile-targets', multiple instances of the same
2400 heading would be created by trying again to file under the new
2401 heading."
2402 :group 'org-refile
2403 :type '(choice
2404 (const :tag "Never" nil)
2405 (const :tag "Always" t)
2406 (const :tag "Prompt for confirmation" confirm)))
2408 (defcustom org-refile-active-region-within-subtree nil
2409 "Non-nil means also refile active region within a subtree.
2411 By default `org-refile' doesn't allow refiling regions if they
2412 don't contain a set of subtrees, but it might be convenient to
2413 do so sometimes: in that case, the first line of the region is
2414 converted to a headline before refiling."
2415 :group 'org-refile
2416 :version "24.1"
2417 :type 'boolean)
2419 (defgroup org-todo nil
2420 "Options concerning TODO items in Org-mode."
2421 :tag "Org TODO"
2422 :group 'org)
2424 (defgroup org-progress nil
2425 "Options concerning Progress logging in Org-mode."
2426 :tag "Org Progress"
2427 :group 'org-time)
2429 (defvar org-todo-interpretation-widgets
2430 '((:tag "Sequence (cycling hits every state)" sequence)
2431 (:tag "Type (cycling directly to DONE)" type))
2432 "The available interpretation symbols for customizing `org-todo-keywords'.
2433 Interested libraries should add to this list.")
2435 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2436 "List of TODO entry keyword sequences and their interpretation.
2437 \\<org-mode-map>This is a list of sequences.
2439 Each sequence starts with a symbol, either `sequence' or `type',
2440 indicating if the keywords should be interpreted as a sequence of
2441 action steps, or as different types of TODO items. The first
2442 keywords are states requiring action - these states will select a headline
2443 for inclusion into the global TODO list Org-mode produces. If one of
2444 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2445 signify that no further action is necessary. If \"|\" is not found,
2446 the last keyword is treated as the only DONE state of the sequence.
2448 The command \\[org-todo] cycles an entry through these states, and one
2449 additional state where no keyword is present. For details about this
2450 cycling, see the manual.
2452 TODO keywords and interpretation can also be set on a per-file basis with
2453 the special #+SEQ_TODO and #+TYP_TODO lines.
2455 Each keyword can optionally specify a character for fast state selection
2456 \(in combination with the variable `org-use-fast-todo-selection')
2457 and specifiers for state change logging, using the same syntax that
2458 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2459 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2460 indicates to record a time stamp each time this state is selected.
2462 Each keyword may also specify if a timestamp or a note should be
2463 recorded when entering or leaving the state, by adding additional
2464 characters in the parenthesis after the keyword. This looks like this:
2465 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2466 record only the time of the state change. With X and Y being either
2467 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2468 Y when leaving the state if and only if the *target* state does not
2469 define X. You may omit any of the fast-selection key or X or /Y,
2470 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2472 For backward compatibility, this variable may also be just a list
2473 of keywords. In this case the interpretation (sequence or type) will be
2474 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2475 :group 'org-todo
2476 :group 'org-keywords
2477 :type '(choice
2478 (repeat :tag "Old syntax, just keywords"
2479 (string :tag "Keyword"))
2480 (repeat :tag "New syntax"
2481 (cons
2482 (choice
2483 :tag "Interpretation"
2484 ;;Quick and dirty way to see
2485 ;;`org-todo-interpretations'. This takes the
2486 ;;place of item arguments
2487 :convert-widget
2488 (lambda (widget)
2489 (widget-put widget
2490 :args (mapcar
2491 #'(lambda (x)
2492 (widget-convert
2493 (cons 'const x)))
2494 org-todo-interpretation-widgets))
2495 widget))
2496 (repeat
2497 (string :tag "Keyword"))))))
2499 (defvar org-todo-keywords-1 nil
2500 "All TODO and DONE keywords active in a buffer.")
2501 (make-variable-buffer-local 'org-todo-keywords-1)
2502 (defvar org-todo-keywords-for-agenda nil)
2503 (defvar org-done-keywords-for-agenda nil)
2504 (defvar org-todo-keyword-alist-for-agenda nil)
2505 (defvar org-tag-alist-for-agenda nil
2506 "Alist of all tags from all agenda files.")
2507 (defvar org-tag-groups-alist-for-agenda nil
2508 "Alist of all groups tags from all current agenda files.")
2509 (defvar org-tag-groups-alist nil)
2510 (make-variable-buffer-local 'org-tag-groups-alist)
2511 (defvar org-agenda-contributing-files nil)
2512 (defvar org-not-done-keywords nil)
2513 (make-variable-buffer-local 'org-not-done-keywords)
2514 (defvar org-done-keywords nil)
2515 (make-variable-buffer-local 'org-done-keywords)
2516 (defvar org-todo-heads nil)
2517 (make-variable-buffer-local 'org-todo-heads)
2518 (defvar org-todo-sets nil)
2519 (make-variable-buffer-local 'org-todo-sets)
2520 (defvar org-todo-log-states nil)
2521 (make-variable-buffer-local 'org-todo-log-states)
2522 (defvar org-todo-kwd-alist nil)
2523 (make-variable-buffer-local 'org-todo-kwd-alist)
2524 (defvar org-todo-key-alist nil)
2525 (make-variable-buffer-local 'org-todo-key-alist)
2526 (defvar org-todo-key-trigger nil)
2527 (make-variable-buffer-local 'org-todo-key-trigger)
2529 (defcustom org-todo-interpretation 'sequence
2530 "Controls how TODO keywords are interpreted.
2531 This variable is in principle obsolete and is only used for
2532 backward compatibility, if the interpretation of todo keywords is
2533 not given already in `org-todo-keywords'. See that variable for
2534 more information."
2535 :group 'org-todo
2536 :group 'org-keywords
2537 :type '(choice (const sequence)
2538 (const type)))
2540 (defcustom org-use-fast-todo-selection t
2541 "Non-nil means use the fast todo selection scheme with C-c C-t.
2542 This variable describes if and under what circumstances the cycling
2543 mechanism for TODO keywords will be replaced by a single-key, direct
2544 selection scheme.
2546 When nil, fast selection is never used.
2548 When the symbol `prefix', it will be used when `org-todo' is called
2549 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2550 `C-u t' in an agenda buffer.
2552 When t, fast selection is used by default. In this case, the prefix
2553 argument forces cycling instead.
2555 In all cases, the special interface is only used if access keys have
2556 actually been assigned by the user, i.e. if keywords in the configuration
2557 are followed by a letter in parenthesis, like TODO(t)."
2558 :group 'org-todo
2559 :type '(choice
2560 (const :tag "Never" nil)
2561 (const :tag "By default" t)
2562 (const :tag "Only with C-u C-c C-t" prefix)))
2564 (defcustom org-provide-todo-statistics t
2565 "Non-nil means update todo statistics after insert and toggle.
2566 ALL-HEADLINES means update todo statistics by including headlines
2567 with no TODO keyword as well, counting them as not done.
2568 A list of TODO keywords means the same, but skip keywords that are
2569 not in this list.
2571 When this is set, todo statistics is updated in the parent of the
2572 current entry each time a todo state is changed."
2573 :group 'org-todo
2574 :type '(choice
2575 (const :tag "Yes, only for TODO entries" t)
2576 (const :tag "Yes, including all entries" all-headlines)
2577 (repeat :tag "Yes, for TODOs in this list"
2578 (string :tag "TODO keyword"))
2579 (other :tag "No TODO statistics" nil)))
2581 (defcustom org-hierarchical-todo-statistics t
2582 "Non-nil means TODO statistics covers just direct children.
2583 When nil, all entries in the subtree are considered.
2584 This has only an effect if `org-provide-todo-statistics' is set.
2585 To set this to nil for only a single subtree, use a COOKIE_DATA
2586 property and include the word \"recursive\" into the value."
2587 :group 'org-todo
2588 :type 'boolean)
2590 (defcustom org-after-todo-state-change-hook nil
2591 "Hook which is run after the state of a TODO item was changed.
2592 The new state (a string with a TODO keyword, or nil) is available in the
2593 Lisp variable `org-state'."
2594 :group 'org-todo
2595 :type 'hook)
2597 (defvar org-blocker-hook nil
2598 "Hook for functions that are allowed to block a state change.
2600 Functions in this hook should not modify the buffer.
2601 Each function gets as its single argument a property list,
2602 see `org-trigger-hook' for more information about this list.
2604 If any of the functions in this hook returns nil, the state change
2605 is blocked.")
2607 (defvar org-trigger-hook nil
2608 "Hook for functions that are triggered by a state change.
2610 Each function gets as its single argument a property list with at
2611 least the following elements:
2613 (:type type-of-change :position pos-at-entry-start
2614 :from old-state :to new-state)
2616 Depending on the type, more properties may be present.
2618 This mechanism is currently implemented for:
2620 TODO state changes
2621 ------------------
2622 :type todo-state-change
2623 :from previous state (keyword as a string), or nil, or a symbol
2624 'todo' or 'done', to indicate the general type of state.
2625 :to new state, like in :from")
2627 (defcustom org-enforce-todo-dependencies nil
2628 "Non-nil means undone TODO entries will block switching the parent to DONE.
2629 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2630 be blocked if any prior sibling is not yet done.
2631 Finally, if the parent is blocked because of ordered siblings of its own,
2632 the child will also be blocked."
2633 :set (lambda (var val)
2634 (set var val)
2635 (if val
2636 (add-hook 'org-blocker-hook
2637 'org-block-todo-from-children-or-siblings-or-parent)
2638 (remove-hook 'org-blocker-hook
2639 'org-block-todo-from-children-or-siblings-or-parent)))
2640 :group 'org-todo
2641 :type 'boolean)
2643 (defcustom org-enforce-todo-checkbox-dependencies nil
2644 "Non-nil means unchecked boxes will block switching the parent to DONE.
2645 When this is nil, checkboxes have no influence on switching TODO states.
2646 When non-nil, you first need to check off all check boxes before the TODO
2647 entry can be switched to DONE.
2648 This variable needs to be set before org.el is loaded, and you need to
2649 restart Emacs after a change to make the change effective. The only way
2650 to change is while Emacs is running is through the customize interface."
2651 :set (lambda (var val)
2652 (set var val)
2653 (if val
2654 (add-hook 'org-blocker-hook
2655 'org-block-todo-from-checkboxes)
2656 (remove-hook 'org-blocker-hook
2657 'org-block-todo-from-checkboxes)))
2658 :group 'org-todo
2659 :type 'boolean)
2661 (defcustom org-treat-insert-todo-heading-as-state-change nil
2662 "Non-nil means inserting a TODO heading is treated as state change.
2663 So when the command \\[org-insert-todo-heading] is used, state change
2664 logging will apply if appropriate. When nil, the new TODO item will
2665 be inserted directly, and no logging will take place."
2666 :group 'org-todo
2667 :type 'boolean)
2669 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2670 "Non-nil means switching TODO states with S-cursor counts as state change.
2671 This is the default behavior. However, setting this to nil allows a
2672 convenient way to select a TODO state and bypass any logging associated
2673 with that."
2674 :group 'org-todo
2675 :type 'boolean)
2677 (defcustom org-todo-state-tags-triggers nil
2678 "Tag changes that should be triggered by TODO state changes.
2679 This is a list. Each entry is
2681 (state-change (tag . flag) .......)
2683 State-change can be a string with a state, and empty string to indicate the
2684 state that has no TODO keyword, or it can be one of the symbols `todo'
2685 or `done', meaning any not-done or done state, respectively."
2686 :group 'org-todo
2687 :group 'org-tags
2688 :type '(repeat
2689 (cons (choice :tag "When changing to"
2690 (const :tag "Not-done state" todo)
2691 (const :tag "Done state" done)
2692 (string :tag "State"))
2693 (repeat
2694 (cons :tag "Tag action"
2695 (string :tag "Tag")
2696 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2698 (defcustom org-log-done nil
2699 "Information to record when a task moves to the DONE state.
2701 Possible values are:
2703 nil Don't add anything, just change the keyword
2704 time Add a time stamp to the task
2705 note Prompt for a note and add it with template `org-log-note-headings'
2707 This option can also be set with on a per-file-basis with
2709 #+STARTUP: nologdone
2710 #+STARTUP: logdone
2711 #+STARTUP: lognotedone
2713 You can have local logging settings for a subtree by setting the LOGGING
2714 property to one or more of these keywords."
2715 :group 'org-todo
2716 :group 'org-progress
2717 :type '(choice
2718 (const :tag "No logging" nil)
2719 (const :tag "Record CLOSED timestamp" time)
2720 (const :tag "Record CLOSED timestamp with note." note)))
2722 ;; Normalize old uses of org-log-done.
2723 (cond
2724 ((eq org-log-done t) (setq org-log-done 'time))
2725 ((and (listp org-log-done) (memq 'done org-log-done))
2726 (setq org-log-done 'note)))
2728 (defcustom org-log-reschedule nil
2729 "Information to record when the scheduling date of a tasks is modified.
2731 Possible values are:
2733 nil Don't add anything, just change the date
2734 time Add a time stamp to the task
2735 note Prompt for a note and add it with template `org-log-note-headings'
2737 This option can also be set with on a per-file-basis with
2739 #+STARTUP: nologreschedule
2740 #+STARTUP: logreschedule
2741 #+STARTUP: lognotereschedule"
2742 :group 'org-todo
2743 :group 'org-progress
2744 :type '(choice
2745 (const :tag "No logging" nil)
2746 (const :tag "Record timestamp" time)
2747 (const :tag "Record timestamp with note." note)))
2749 (defcustom org-log-redeadline nil
2750 "Information to record when the deadline date of a tasks is modified.
2752 Possible values are:
2754 nil Don't add anything, just change the date
2755 time Add a time stamp to the task
2756 note Prompt for a note and add it with template `org-log-note-headings'
2758 This option can also be set with on a per-file-basis with
2760 #+STARTUP: nologredeadline
2761 #+STARTUP: logredeadline
2762 #+STARTUP: lognoteredeadline
2764 You can have local logging settings for a subtree by setting the LOGGING
2765 property to one or more of these keywords."
2766 :group 'org-todo
2767 :group 'org-progress
2768 :type '(choice
2769 (const :tag "No logging" nil)
2770 (const :tag "Record timestamp" time)
2771 (const :tag "Record timestamp with note." note)))
2773 (defcustom org-log-note-clock-out nil
2774 "Non-nil means record a note when clocking out of an item.
2775 This can also be configured on a per-file basis by adding one of
2776 the following lines anywhere in the buffer:
2778 #+STARTUP: lognoteclock-out
2779 #+STARTUP: nolognoteclock-out"
2780 :group 'org-todo
2781 :group 'org-progress
2782 :type 'boolean)
2784 (defcustom org-log-done-with-time t
2785 "Non-nil means the CLOSED time stamp will contain date and time.
2786 When nil, only the date will be recorded."
2787 :group 'org-progress
2788 :type 'boolean)
2790 (defcustom org-log-note-headings
2791 '((done . "CLOSING NOTE %t")
2792 (state . "State %-12s from %-12S %t")
2793 (note . "Note taken on %t")
2794 (reschedule . "Rescheduled from %S on %t")
2795 (delschedule . "Not scheduled, was %S on %t")
2796 (redeadline . "New deadline from %S on %t")
2797 (deldeadline . "Removed deadline, was %S on %t")
2798 (refile . "Refiled on %t")
2799 (clock-out . ""))
2800 "Headings for notes added to entries.
2801 The value is an alist, with the car being a symbol indicating the note
2802 context, and the cdr is the heading to be used. The heading may also be the
2803 empty string.
2804 %t in the heading will be replaced by a time stamp.
2805 %T will be an active time stamp instead the default inactive one
2806 %d will be replaced by a short-format time stamp.
2807 %D will be replaced by an active short-format time stamp.
2808 %s will be replaced by the new TODO state, in double quotes.
2809 %S will be replaced by the old TODO state, in double quotes.
2810 %u will be replaced by the user name.
2811 %U will be replaced by the full user name.
2813 In fact, it is not a good idea to change the `state' entry, because
2814 agenda log mode depends on the format of these entries."
2815 :group 'org-todo
2816 :group 'org-progress
2817 :type '(list :greedy t
2818 (cons (const :tag "Heading when closing an item" done) string)
2819 (cons (const :tag
2820 "Heading when changing todo state (todo sequence only)"
2821 state) string)
2822 (cons (const :tag "Heading when just taking a note" note) string)
2823 (cons (const :tag "Heading when rescheduling" reschedule) string)
2824 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2825 (cons (const :tag "Heading when changing deadline" redeadline) string)
2826 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2827 (cons (const :tag "Heading when refiling" refile) string)
2828 (cons (const :tag "Heading when clocking out" clock-out) string)))
2830 (unless (assq 'note org-log-note-headings)
2831 (push '(note . "%t") org-log-note-headings))
2833 (defcustom org-log-into-drawer nil
2834 "Non-nil means insert state change notes and time stamps into a drawer.
2835 When nil, state changes notes will be inserted after the headline and
2836 any scheduling and clock lines, but not inside a drawer.
2838 The value of this variable should be the name of the drawer to use.
2839 LOGBOOK is proposed as the default drawer for this purpose, you can
2840 also set this to a string to define the drawer of your choice.
2842 A value of t is also allowed, representing \"LOGBOOK\".
2844 A value of t or nil can also be set with on a per-file-basis with
2846 #+STARTUP: logdrawer
2847 #+STARTUP: nologdrawer
2849 If this variable is set, `org-log-state-notes-insert-after-drawers'
2850 will be ignored.
2852 You can set the property LOG_INTO_DRAWER to overrule this setting for
2853 a subtree."
2854 :group 'org-todo
2855 :group 'org-progress
2856 :type '(choice
2857 (const :tag "Not into a drawer" nil)
2858 (const :tag "LOGBOOK" t)
2859 (string :tag "Other")))
2861 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2863 (defun org-log-into-drawer ()
2864 "Return the value of `org-log-into-drawer', but let properties overrule.
2865 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2866 used instead of the default value."
2867 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2868 (cond
2869 ((not p) org-log-into-drawer)
2870 ((equal p "nil") nil)
2871 ((equal p "t") "LOGBOOK")
2872 (t p))))
2874 (defcustom org-log-state-notes-insert-after-drawers nil
2875 "Non-nil means insert state change notes after any drawers in entry.
2876 Only the drawers that *immediately* follow the headline and the
2877 deadline/scheduled line are skipped.
2878 When nil, insert notes right after the heading and perhaps the line
2879 with deadline/scheduling if present.
2881 This variable will have no effect if `org-log-into-drawer' is
2882 set."
2883 :group 'org-todo
2884 :group 'org-progress
2885 :type 'boolean)
2887 (defcustom org-log-states-order-reversed t
2888 "Non-nil means the latest state note will be directly after heading.
2889 When nil, the state change notes will be ordered according to time.
2891 This option can also be set with on a per-file-basis with
2893 #+STARTUP: logstatesreversed
2894 #+STARTUP: nologstatesreversed"
2895 :group 'org-todo
2896 :group 'org-progress
2897 :type 'boolean)
2899 (defcustom org-todo-repeat-to-state nil
2900 "The TODO state to which a repeater should return the repeating task.
2901 By default this is the first task in a TODO sequence, or the previous state
2902 in a TODO_TYP set. But you can specify another task here.
2903 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2904 :group 'org-todo
2905 :version "24.1"
2906 :type '(choice (const :tag "Head of sequence" nil)
2907 (string :tag "Specific state")))
2909 (defcustom org-log-repeat 'time
2910 "Non-nil means record moving through the DONE state when triggering repeat.
2911 An auto-repeating task is immediately switched back to TODO when
2912 marked DONE. If you are not logging state changes (by adding \"@\"
2913 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2914 record a closing note, there will be no record of the task moving
2915 through DONE. This variable forces taking a note anyway.
2917 nil Don't force a record
2918 time Record a time stamp
2919 note Prompt for a note and add it with template `org-log-note-headings'
2921 This option can also be set with on a per-file-basis with
2923 #+STARTUP: nologrepeat
2924 #+STARTUP: logrepeat
2925 #+STARTUP: lognoterepeat
2927 You can have local logging settings for a subtree by setting the LOGGING
2928 property to one or more of these keywords."
2929 :group 'org-todo
2930 :group 'org-progress
2931 :type '(choice
2932 (const :tag "Don't force a record" nil)
2933 (const :tag "Force recording the DONE state" time)
2934 (const :tag "Force recording a note with the DONE state" note)))
2937 (defgroup org-priorities nil
2938 "Priorities in Org-mode."
2939 :tag "Org Priorities"
2940 :group 'org-todo)
2942 (defcustom org-enable-priority-commands t
2943 "Non-nil means priority commands are active.
2944 When nil, these commands will be disabled, so that you never accidentally
2945 set a priority."
2946 :group 'org-priorities
2947 :type 'boolean)
2949 (defcustom org-highest-priority ?A
2950 "The highest priority of TODO items. A character like ?A, ?B etc.
2951 Must have a smaller ASCII number than `org-lowest-priority'."
2952 :group 'org-priorities
2953 :type 'character)
2955 (defcustom org-lowest-priority ?C
2956 "The lowest priority of TODO items. A character like ?A, ?B etc.
2957 Must have a larger ASCII number than `org-highest-priority'."
2958 :group 'org-priorities
2959 :type 'character)
2961 (defcustom org-default-priority ?B
2962 "The default priority of TODO items.
2963 This is the priority an item gets if no explicit priority is given.
2964 When starting to cycle on an empty priority the first step in the cycle
2965 depends on `org-priority-start-cycle-with-default'. The resulting first
2966 step priority must not exceed the range from `org-highest-priority' to
2967 `org-lowest-priority' which means that `org-default-priority' has to be
2968 in this range exclusive or inclusive the range boundaries. Else the
2969 first step refuses to set the default and the second will fall back
2970 to (depending on the command used) the highest or lowest priority."
2971 :group 'org-priorities
2972 :type 'character)
2974 (defcustom org-priority-start-cycle-with-default t
2975 "Non-nil means start with default priority when starting to cycle.
2976 When this is nil, the first step in the cycle will be (depending on the
2977 command used) one higher or lower than the default priority.
2978 See also `org-default-priority'."
2979 :group 'org-priorities
2980 :type 'boolean)
2982 (defcustom org-get-priority-function nil
2983 "Function to extract the priority from a string.
2984 The string is normally the headline. If this is nil Org computes the
2985 priority from the priority cookie like [#A] in the headline. It returns
2986 an integer, increasing by 1000 for each priority level.
2987 The user can set a different function here, which should take a string
2988 as an argument and return the numeric priority."
2989 :group 'org-priorities
2990 :version "24.1"
2991 :type '(choice
2992 (const nil)
2993 (function)))
2995 (defgroup org-time nil
2996 "Options concerning time stamps and deadlines in Org-mode."
2997 :tag "Org Time"
2998 :group 'org)
3000 (defcustom org-insert-labeled-timestamps-at-point nil
3001 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
3002 When nil, these labeled time stamps are forces into the second line of an
3003 entry, just after the headline. When scheduling from the global TODO list,
3004 the time stamp will always be forced into the second line."
3005 :group 'org-time
3006 :type 'boolean)
3008 (defcustom org-time-stamp-rounding-minutes '(0 5)
3009 "Number of minutes to round time stamps to.
3010 These are two values, the first applies when first creating a time stamp.
3011 The second applies when changing it with the commands `S-up' and `S-down'.
3012 When changing the time stamp, this means that it will change in steps
3013 of N minutes, as given by the second value.
3015 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3016 numbers should be factors of 60, so for example 5, 10, 15.
3018 When this is larger than 1, you can still force an exact time stamp by using
3019 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3020 and by using a prefix arg to `S-up/down' to specify the exact number
3021 of minutes to shift."
3022 :group 'org-time
3023 :get #'(lambda (var) ; Make sure both elements are there
3024 (if (integerp (default-value var))
3025 (list (default-value var) 5)
3026 (default-value var)))
3027 :type '(list
3028 (integer :tag "when inserting times")
3029 (integer :tag "when modifying times")))
3031 ;; Normalize old customizations of this variable.
3032 (when (integerp org-time-stamp-rounding-minutes)
3033 (setq org-time-stamp-rounding-minutes
3034 (list org-time-stamp-rounding-minutes
3035 org-time-stamp-rounding-minutes)))
3037 (defcustom org-display-custom-times nil
3038 "Non-nil means overlay custom formats over all time stamps.
3039 The formats are defined through the variable `org-time-stamp-custom-formats'.
3040 To turn this on on a per-file basis, insert anywhere in the file:
3041 #+STARTUP: customtime"
3042 :group 'org-time
3043 :set 'set-default
3044 :type 'sexp)
3045 (make-variable-buffer-local 'org-display-custom-times)
3047 (defcustom org-time-stamp-custom-formats
3048 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3049 "Custom formats for time stamps. See `format-time-string' for the syntax.
3050 These are overlaid over the default ISO format if the variable
3051 `org-display-custom-times' is set. Time like %H:%M should be at the
3052 end of the second format. The custom formats are also honored by export
3053 commands, if custom time display is turned on at the time of export."
3054 :group 'org-time
3055 :type 'sexp)
3057 (defun org-time-stamp-format (&optional long inactive)
3058 "Get the right format for a time string."
3059 (let ((f (if long (cdr org-time-stamp-formats)
3060 (car org-time-stamp-formats))))
3061 (if inactive
3062 (concat "[" (substring f 1 -1) "]")
3063 f)))
3065 (defcustom org-time-clocksum-format
3066 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3067 "The format string used when creating CLOCKSUM lines.
3068 This is also used when Org mode generates a time duration.
3070 The value can be a single format string containing two
3071 %-sequences, which will be filled with the number of hours and
3072 minutes in that order.
3074 Alternatively, the value can be a plist associating any of the
3075 keys :years, :months, :weeks, :days, :hours or :minutes with
3076 format strings. The time duration is formatted using only the
3077 time components that are needed and concatenating the results.
3078 If a time unit in absent, it falls back to the next smallest
3079 unit.
3081 The keys :require-years, :require-months, :require-days,
3082 :require-weeks, :require-hours, :require-minutes are also
3083 meaningful. A non-nil value for these keys indicates that the
3084 corresponding time component should always be included, even if
3085 its value is 0.
3088 For example,
3090 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3091 :require-minutes t)
3093 means durations longer than a day will be expressed in days,
3094 hours and minutes, and durations less than a day will always be
3095 expressed in hours and minutes (even for durations less than an
3096 hour).
3098 The value
3100 \(:days \"%dd\" :minutes \"%dm\")
3102 means durations longer than a day will be expressed in days and
3103 minutes, and durations less than a day will be expressed entirely
3104 in minutes (even for durations longer than an hour)."
3105 :group 'org-time
3106 :group 'org-clock
3107 :version "24.4"
3108 :package-version '(Org . "8.0")
3109 :type '(choice (string :tag "Format string")
3110 (set :tag "Plist"
3111 (group :inline t (const :tag "Years" :years)
3112 (string :tag "Format string"))
3113 (group :inline t
3114 (const :tag "Always show years" :require-years)
3115 (const t))
3116 (group :inline t (const :tag "Months" :months)
3117 (string :tag "Format string"))
3118 (group :inline t
3119 (const :tag "Always show months" :require-months)
3120 (const t))
3121 (group :inline t (const :tag "Weeks" :weeks)
3122 (string :tag "Format string"))
3123 (group :inline t
3124 (const :tag "Always show weeks" :require-weeks)
3125 (const t))
3126 (group :inline t (const :tag "Days" :days)
3127 (string :tag "Format string"))
3128 (group :inline t
3129 (const :tag "Always show days" :require-days)
3130 (const t))
3131 (group :inline t (const :tag "Hours" :hours)
3132 (string :tag "Format string"))
3133 (group :inline t
3134 (const :tag "Always show hours" :require-hours)
3135 (const t))
3136 (group :inline t (const :tag "Minutes" :minutes)
3137 (string :tag "Format string"))
3138 (group :inline t
3139 (const :tag "Always show minutes" :require-minutes)
3140 (const t)))))
3142 (defcustom org-time-clocksum-use-fractional nil
3143 "When non-nil, \\[org-clock-display] uses fractional times.
3144 See `org-time-clocksum-format' for more on time clock formats."
3145 :group 'org-time
3146 :group 'org-clock
3147 :version "24.3"
3148 :type 'boolean)
3150 (defcustom org-time-clocksum-use-effort-durations nil
3151 "When non-nil, \\[org-clock-display] uses effort durations.
3152 E.g. by default, one day is considered to be a 8 hours effort,
3153 so a task that has been clocked for 16 hours will be displayed
3154 as during 2 days in the clock display or in the clocktable.
3156 See `org-effort-durations' on how to set effort durations
3157 and `org-time-clocksum-format' for more on time clock formats."
3158 :group 'org-time
3159 :group 'org-clock
3160 :version "24.4"
3161 :package-version '(Org . "8.0")
3162 :type 'boolean)
3164 (defcustom org-time-clocksum-fractional-format "%.2f"
3165 "The format string used when creating CLOCKSUM lines,
3166 or when Org mode generates a time duration, if
3167 `org-time-clocksum-use-fractional' is enabled.
3169 The value can be a single format string containing one
3170 %-sequence, which will be filled with the number of hours as
3171 a float.
3173 Alternatively, the value can be a plist associating any of the
3174 keys :years, :months, :weeks, :days, :hours or :minutes with
3175 a format string. The time duration is formatted using the
3176 largest time unit which gives a non-zero integer part. If all
3177 specified formats have zero integer part, the smallest time unit
3178 is used."
3179 :group 'org-time
3180 :type '(choice (string :tag "Format string")
3181 (set (group :inline t (const :tag "Years" :years)
3182 (string :tag "Format string"))
3183 (group :inline t (const :tag "Months" :months)
3184 (string :tag "Format string"))
3185 (group :inline t (const :tag "Weeks" :weeks)
3186 (string :tag "Format string"))
3187 (group :inline t (const :tag "Days" :days)
3188 (string :tag "Format string"))
3189 (group :inline t (const :tag "Hours" :hours)
3190 (string :tag "Format string"))
3191 (group :inline t (const :tag "Minutes" :minutes)
3192 (string :tag "Format string")))))
3194 (defcustom org-deadline-warning-days 14
3195 "Number of days before expiration during which a deadline becomes active.
3196 This variable governs the display in sparse trees and in the agenda.
3197 When 0 or negative, it means use this number (the absolute value of it)
3198 even if a deadline has a different individual lead time specified.
3200 Custom commands can set this variable in the options section."
3201 :group 'org-time
3202 :group 'org-agenda-daily/weekly
3203 :type 'integer)
3205 (defcustom org-scheduled-delay-days 0
3206 "Number of days before a scheduled item becomes active.
3207 This variable governs the display in sparse trees and in the agenda.
3208 The default value (i.e. 0) means: don't delay scheduled item.
3209 When negative, it means use this number (the absolute value of it)
3210 even if a scheduled item has a different individual delay time
3211 specified.
3213 Custom commands can set this variable in the options section."
3214 :group 'org-time
3215 :group 'org-agenda-daily/weekly
3216 :version "24.4"
3217 :package-version '(Org . "8.0")
3218 :type 'integer)
3220 (defcustom org-read-date-prefer-future t
3221 "Non-nil means assume future for incomplete date input from user.
3222 This affects the following situations:
3223 1. The user gives a month but not a year.
3224 For example, if it is April and you enter \"feb 2\", this will be read
3225 as Feb 2, *next* year. \"May 5\", however, will be this year.
3226 2. The user gives a day, but no month.
3227 For example, if today is the 15th, and you enter \"3\", Org-mode will
3228 read this as the third of *next* month. However, if you enter \"17\",
3229 it will be considered as *this* month.
3231 If you set this variable to the symbol `time', then also the following
3232 will work:
3234 3. If the user gives a time.
3235 If the time is before now, it will be interpreted as tomorrow.
3237 Currently none of this works for ISO week specifications.
3239 When this option is nil, the current day, month and year will always be
3240 used as defaults.
3242 See also `org-agenda-jump-prefer-future'."
3243 :group 'org-time
3244 :type '(choice
3245 (const :tag "Never" nil)
3246 (const :tag "Check month and day" t)
3247 (const :tag "Check month, day, and time" time)))
3249 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3250 "Should the agenda jump command prefer the future for incomplete dates?
3251 The default is to do the same as configured in `org-read-date-prefer-future'.
3252 But you can also set a deviating value here.
3253 This may t or nil, or the symbol `org-read-date-prefer-future'."
3254 :group 'org-agenda
3255 :group 'org-time
3256 :version "24.1"
3257 :type '(choice
3258 (const :tag "Use org-read-date-prefer-future"
3259 org-read-date-prefer-future)
3260 (const :tag "Never" nil)
3261 (const :tag "Always" t)))
3263 (defcustom org-read-date-force-compatible-dates t
3264 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3266 Depending on the system Emacs is running on, certain dates cannot
3267 be represented with the type used internally to represent time.
3268 Dates between 1970-1-1 and 2038-1-1 can always be represented
3269 correctly. Some systems allow for earlier dates, some for later,
3270 some for both. One way to find out it to insert any date into an
3271 Org buffer, putting the cursor on the year and hitting S-up and
3272 S-down to test the range.
3274 When this variable is set to t, the date/time prompt will not let
3275 you specify dates outside the 1970-2037 range, so it is certain that
3276 these dates will work in whatever version of Emacs you are
3277 running, and also that you can move a file from one Emacs implementation
3278 to another. WHenever Org is forcing the year for you, it will display
3279 a message and beep.
3281 When this variable is nil, Org will check if the date is
3282 representable in the specific Emacs implementation you are using.
3283 If not, it will force a year, usually the current year, and beep
3284 to remind you. Currently this setting is not recommended because
3285 the likelihood that you will open your Org files in an Emacs that
3286 has limited date range is not negligible.
3288 A workaround for this problem is to use diary sexp dates for time
3289 stamps outside of this range."
3290 :group 'org-time
3291 :version "24.1"
3292 :type 'boolean)
3294 (defcustom org-read-date-display-live t
3295 "Non-nil means display current interpretation of date prompt live.
3296 This display will be in an overlay, in the minibuffer."
3297 :group 'org-time
3298 :type 'boolean)
3300 (defcustom org-read-date-popup-calendar t
3301 "Non-nil means pop up a calendar when prompting for a date.
3302 In the calendar, the date can be selected with mouse-1. However, the
3303 minibuffer will also be active, and you can simply enter the date as well.
3304 When nil, only the minibuffer will be available."
3305 :group 'org-time
3306 :type 'boolean)
3307 (org-defvaralias 'org-popup-calendar-for-date-prompt
3308 'org-read-date-popup-calendar)
3310 (make-obsolete-variable
3311 'org-read-date-minibuffer-setup-hook
3312 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3313 (defcustom org-read-date-minibuffer-setup-hook nil
3314 "Hook to be used to set up keys for the date/time interface.
3315 Add key definitions to `minibuffer-local-map', which will be a
3316 temporary copy.
3318 WARNING: This option is obsolete, you should use
3319 `org-read-date-minibuffer-local-map' to set up keys."
3320 :group 'org-time
3321 :type 'hook)
3323 (defcustom org-extend-today-until 0
3324 "The hour when your day really ends. Must be an integer.
3325 This has influence for the following applications:
3326 - When switching the agenda to \"today\". It it is still earlier than
3327 the time given here, the day recognized as TODAY is actually yesterday.
3328 - When a date is read from the user and it is still before the time given
3329 here, the current date and time will be assumed to be yesterday, 23:59.
3330 Also, timestamps inserted in capture templates follow this rule.
3332 IMPORTANT: This is a feature whose implementation is and likely will
3333 remain incomplete. Really, it is only here because past midnight seems to
3334 be the favorite working time of John Wiegley :-)"
3335 :group 'org-time
3336 :type 'integer)
3338 (defcustom org-use-effective-time nil
3339 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3340 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3341 \"effective time\" of any timestamps between midnight and 8am will be
3342 23:59 of the previous day."
3343 :group 'org-time
3344 :version "24.1"
3345 :type 'boolean)
3347 (defcustom org-use-last-clock-out-time-as-effective-time nil
3348 "When non-nil, use the last clock out time for `org-todo'.
3349 Note that this option has precedence over the combined use of
3350 `org-use-effective-time' and `org-extend-today-until'."
3351 :group 'org-time
3352 :version "24.4"
3353 :package-version '(Org . "8.0")
3354 :type 'boolean)
3356 (defcustom org-edit-timestamp-down-means-later nil
3357 "Non-nil means S-down will increase the time in a time stamp.
3358 When nil, S-up will increase."
3359 :group 'org-time
3360 :type 'boolean)
3362 (defcustom org-calendar-follow-timestamp-change t
3363 "Non-nil means make the calendar window follow timestamp changes.
3364 When a timestamp is modified and the calendar window is visible, it will be
3365 moved to the new date."
3366 :group 'org-time
3367 :type 'boolean)
3369 (defgroup org-tags nil
3370 "Options concerning tags in Org-mode."
3371 :tag "Org Tags"
3372 :group 'org)
3374 (defcustom org-tag-alist nil
3375 "List of tags allowed in Org-mode files.
3376 When this list is nil, Org-mode will base TAG input on what is already in the
3377 buffer.
3378 The value of this variable is an alist, the car of each entry must be a
3379 keyword as a string, the cdr may be a character that is used to select
3380 that tag through the fast-tag-selection interface.
3381 See the manual for details."
3382 :group 'org-tags
3383 :type '(repeat
3384 (choice
3385 (cons (string :tag "Tag name")
3386 (character :tag "Access char"))
3387 (list :tag "Start radio group"
3388 (const :startgroup)
3389 (option (string :tag "Group description")))
3390 (list :tag "Group tags delimiter"
3391 (const :grouptags))
3392 (list :tag "End radio group"
3393 (const :endgroup)
3394 (option (string :tag "Group description")))
3395 (const :tag "New line" (:newline)))))
3397 (defcustom org-tag-persistent-alist nil
3398 "List of tags that will always appear in all Org-mode files.
3399 This is in addition to any in buffer settings or customizations
3400 of `org-tag-alist'.
3401 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3402 The value of this variable is an alist, the car of each entry must be a
3403 keyword as a string, the cdr may be a character that is used to select
3404 that tag through the fast-tag-selection interface.
3405 See the manual for details.
3406 To disable these tags on a per-file basis, insert anywhere in the file:
3407 #+STARTUP: noptag"
3408 :group 'org-tags
3409 :type '(repeat
3410 (choice
3411 (cons (string :tag "Tag name")
3412 (character :tag "Access char"))
3413 (const :tag "Start radio group" (:startgroup))
3414 (const :tag "Group tags delimiter" (:grouptags))
3415 (const :tag "End radio group" (:endgroup))
3416 (const :tag "New line" (:newline)))))
3418 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3419 "If non-nil, always offer completion for all tags of all agenda files.
3420 Instead of customizing this variable directly, you might want to
3421 set it locally for capture buffers, because there no list of
3422 tags in that file can be created dynamically (there are none).
3424 (add-hook 'org-capture-mode-hook
3425 (lambda ()
3426 (set (make-local-variable
3427 'org-complete-tags-always-offer-all-agenda-tags)
3428 t)))"
3429 :group 'org-tags
3430 :version "24.1"
3431 :type 'boolean)
3433 (defvar org-file-tags nil
3434 "List of tags that can be inherited by all entries in the file.
3435 The tags will be inherited if the variable `org-use-tag-inheritance'
3436 says they should be.
3437 This variable is populated from #+FILETAGS lines.")
3439 (defcustom org-use-fast-tag-selection 'auto
3440 "Non-nil means use fast tag selection scheme.
3441 This is a special interface to select and deselect tags with single keys.
3442 When nil, fast selection is never used.
3443 When the symbol `auto', fast selection is used if and only if selection
3444 characters for tags have been configured, either through the variable
3445 `org-tag-alist' or through a #+TAGS line in the buffer.
3446 When t, fast selection is always used and selection keys are assigned
3447 automatically if necessary."
3448 :group 'org-tags
3449 :type '(choice
3450 (const :tag "Always" t)
3451 (const :tag "Never" nil)
3452 (const :tag "When selection characters are configured" auto)))
3454 (defcustom org-fast-tag-selection-single-key nil
3455 "Non-nil means fast tag selection exits after first change.
3456 When nil, you have to press RET to exit it.
3457 During fast tag selection, you can toggle this flag with `C-c'.
3458 This variable can also have the value `expert'. In this case, the window
3459 displaying the tags menu is not even shown, until you press C-c again."
3460 :group 'org-tags
3461 :type '(choice
3462 (const :tag "No" nil)
3463 (const :tag "Yes" t)
3464 (const :tag "Expert" expert)))
3466 (defvar org-fast-tag-selection-include-todo nil
3467 "Non-nil means fast tags selection interface will also offer TODO states.
3468 This is an undocumented feature, you should not rely on it.")
3470 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3471 "The column to which tags should be indented in a headline.
3472 If this number is positive, it specifies the column. If it is negative,
3473 it means that the tags should be flushright to that column. For example,
3474 -80 works well for a normal 80 character screen.
3475 When 0, place tags directly after headline text, with only one space in
3476 between."
3477 :group 'org-tags
3478 :type 'integer)
3480 (defcustom org-auto-align-tags t
3481 "Non-nil keeps tags aligned when modifying headlines.
3482 Some operations (i.e. demoting) change the length of a headline and
3483 therefore shift the tags around. With this option turned on, after
3484 each such operation the tags are again aligned to `org-tags-column'."
3485 :group 'org-tags
3486 :type 'boolean)
3488 (defcustom org-use-tag-inheritance t
3489 "Non-nil means tags in levels apply also for sublevels.
3490 When nil, only the tags directly given in a specific line apply there.
3491 This may also be a list of tags that should be inherited, or a regexp that
3492 matches tags that should be inherited. Additional control is possible
3493 with the variable `org-tags-exclude-from-inheritance' which gives an
3494 explicit list of tags to be excluded from inheritance, even if the value of
3495 `org-use-tag-inheritance' would select it for inheritance.
3497 If this option is t, a match early-on in a tree can lead to a large
3498 number of matches in the subtree when constructing the agenda or creating
3499 a sparse tree. If you only want to see the first match in a tree during
3500 a search, check out the variable `org-tags-match-list-sublevels'."
3501 :group 'org-tags
3502 :type '(choice
3503 (const :tag "Not" nil)
3504 (const :tag "Always" t)
3505 (repeat :tag "Specific tags" (string :tag "Tag"))
3506 (regexp :tag "Tags matched by regexp")))
3508 (defcustom org-tags-exclude-from-inheritance nil
3509 "List of tags that should never be inherited.
3510 This is a way to exclude a few tags from inheritance. For way to do
3511 the opposite, to actively allow inheritance for selected tags,
3512 see the variable `org-use-tag-inheritance'."
3513 :group 'org-tags
3514 :type '(repeat (string :tag "Tag")))
3516 (defun org-tag-inherit-p (tag)
3517 "Check if TAG is one that should be inherited."
3518 (cond
3519 ((member tag org-tags-exclude-from-inheritance) nil)
3520 ((eq org-use-tag-inheritance t) t)
3521 ((not org-use-tag-inheritance) nil)
3522 ((stringp org-use-tag-inheritance)
3523 (string-match org-use-tag-inheritance tag))
3524 ((listp org-use-tag-inheritance)
3525 (member tag org-use-tag-inheritance))
3526 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3528 (defcustom org-tags-match-list-sublevels t
3529 "Non-nil means list also sublevels of headlines matching a search.
3530 This variable applies to tags/property searches, and also to stuck
3531 projects because this search is based on a tags match as well.
3533 When set to the symbol `indented', sublevels are indented with
3534 leading dots.
3536 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3537 the sublevels of a headline matching a tag search often also match
3538 the same search. Listing all of them can create very long lists.
3539 Setting this variable to nil causes subtrees of a match to be skipped.
3541 This variable is semi-obsolete and probably should always be true. It
3542 is better to limit inheritance to certain tags using the variables
3543 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3544 :group 'org-tags
3545 :type '(choice
3546 (const :tag "No, don't list them" nil)
3547 (const :tag "Yes, do list them" t)
3548 (const :tag "List them, indented with leading dots" indented)))
3550 (defcustom org-tags-sort-function nil
3551 "When set, tags are sorted using this function as a comparator."
3552 :group 'org-tags
3553 :type '(choice
3554 (const :tag "No sorting" nil)
3555 (const :tag "Alphabetical" string<)
3556 (const :tag "Reverse alphabetical" string>)
3557 (function :tag "Custom function" nil)))
3559 (defvar org-tags-history nil
3560 "History of minibuffer reads for tags.")
3561 (defvar org-last-tags-completion-table nil
3562 "The last used completion table for tags.")
3563 (defvar org-after-tags-change-hook nil
3564 "Hook that is run after the tags in a line have changed.")
3566 (defgroup org-properties nil
3567 "Options concerning properties in Org-mode."
3568 :tag "Org Properties"
3569 :group 'org)
3571 (defcustom org-property-format "%-10s %s"
3572 "How property key/value pairs should be formatted by `indent-line'.
3573 When `indent-line' hits a property definition, it will format the line
3574 according to this format, mainly to make sure that the values are
3575 lined-up with respect to each other."
3576 :group 'org-properties
3577 :type 'string)
3579 (defcustom org-properties-postprocess-alist nil
3580 "Alist of properties and functions to adjust inserted values.
3581 Elements of this alist must be of the form
3583 ([string] [function])
3585 where [string] must be a property name and [function] must be a
3586 lambda expression: this lambda expression must take one argument,
3587 the value to adjust, and return the new value as a string.
3589 For example, this element will allow the property \"Remaining\"
3590 to be updated wrt the relation between the \"Effort\" property
3591 and the clock summary:
3593 ((\"Remaining\" (lambda(value)
3594 (let ((clocksum (org-clock-sum-current-item))
3595 (effort (org-duration-string-to-minutes
3596 (org-entry-get (point) \"Effort\"))))
3597 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3598 :group 'org-properties
3599 :version "24.1"
3600 :type '(alist :key-type (string :tag "Property")
3601 :value-type (function :tag "Function")))
3603 (defcustom org-use-property-inheritance nil
3604 "Non-nil means properties apply also for sublevels.
3606 This setting is chiefly used during property searches. Turning it on can
3607 cause significant overhead when doing a search, which is why it is not
3608 on by default.
3610 When nil, only the properties directly given in the current entry count.
3611 When t, every property is inherited. The value may also be a list of
3612 properties that should have inheritance, or a regular expression matching
3613 properties that should be inherited.
3615 However, note that some special properties use inheritance under special
3616 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3617 and the properties ending in \"_ALL\" when they are used as descriptor
3618 for valid values of a property.
3620 Note for programmers:
3621 When querying an entry with `org-entry-get', you can control if inheritance
3622 should be used. By default, `org-entry-get' looks only at the local
3623 properties. You can request inheritance by setting the inherit argument
3624 to t (to force inheritance) or to `selective' (to respect the setting
3625 in this variable)."
3626 :group 'org-properties
3627 :type '(choice
3628 (const :tag "Not" nil)
3629 (const :tag "Always" t)
3630 (repeat :tag "Specific properties" (string :tag "Property"))
3631 (regexp :tag "Properties matched by regexp")))
3633 (defun org-property-inherit-p (property)
3634 "Check if PROPERTY is one that should be inherited."
3635 (cond
3636 ((eq org-use-property-inheritance t) t)
3637 ((not org-use-property-inheritance) nil)
3638 ((stringp org-use-property-inheritance)
3639 (string-match org-use-property-inheritance property))
3640 ((listp org-use-property-inheritance)
3641 (member property org-use-property-inheritance))
3642 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3644 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3645 "The default column format, if no other format has been defined.
3646 This variable can be set on the per-file basis by inserting a line
3648 #+COLUMNS: %25ITEM ....."
3649 :group 'org-properties
3650 :type 'string)
3652 (defcustom org-columns-ellipses ".."
3653 "The ellipses to be used when a field in column view is truncated.
3654 When this is the empty string, as many characters as possible are shown,
3655 but then there will be no visual indication that the field has been truncated.
3656 When this is a string of length N, the last N characters of a truncated
3657 field are replaced by this string. If the column is narrower than the
3658 ellipses string, only part of the ellipses string will be shown."
3659 :group 'org-properties
3660 :type 'string)
3662 (defcustom org-columns-modify-value-for-display-function nil
3663 "Function that modifies values for display in column view.
3664 For example, it can be used to cut out a certain part from a time stamp.
3665 The function must take 2 arguments:
3667 column-title The title of the column (*not* the property name)
3668 value The value that should be modified.
3670 The function should return the value that should be displayed,
3671 or nil if the normal value should be used."
3672 :group 'org-properties
3673 :type '(choice (const nil) (function)))
3675 (defconst org-global-properties-fixed
3676 '(("VISIBILITY_ALL" . "folded children content all")
3677 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3678 "List of property/value pairs that can be inherited by any entry.
3680 These are fixed values, for the preset properties. The user variable
3681 that can be used to add to this list is `org-global-properties'.
3683 The entries in this list are cons cells where the car is a property
3684 name and cdr is a string with the value. If the value represents
3685 multiple items like an \"_ALL\" property, separate the items by
3686 spaces.")
3688 (defcustom org-global-properties nil
3689 "List of property/value pairs that can be inherited by any entry.
3691 This list will be combined with the constant `org-global-properties-fixed'.
3693 The entries in this list are cons cells where the car is a property
3694 name and cdr is a string with the value.
3696 You can set buffer-local values for the same purpose in the variable
3697 `org-file-properties' this by adding lines like
3699 #+PROPERTY: NAME VALUE"
3700 :group 'org-properties
3701 :type '(repeat
3702 (cons (string :tag "Property")
3703 (string :tag "Value"))))
3705 (defvar org-file-properties nil
3706 "List of property/value pairs that can be inherited by any entry.
3707 Valid for the current buffer.
3708 This variable is populated from #+PROPERTY lines.")
3709 (make-variable-buffer-local 'org-file-properties)
3711 (defgroup org-agenda nil
3712 "Options concerning agenda views in Org-mode."
3713 :tag "Org Agenda"
3714 :group 'org)
3716 (defvar org-category nil
3717 "Variable used by org files to set a category for agenda display.
3718 Such files should use a file variable to set it, for example
3720 # -*- mode: org; org-category: \"ELisp\"
3722 or contain a special line
3724 #+CATEGORY: ELisp
3726 If the file does not specify a category, then file's base name
3727 is used instead.")
3728 (make-variable-buffer-local 'org-category)
3729 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3731 (defcustom org-agenda-files nil
3732 "The files to be used for agenda display.
3733 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3734 \\[org-remove-file]. You can also use customize to edit the list.
3736 If an entry is a directory, all files in that directory that are matched by
3737 `org-agenda-file-regexp' will be part of the file list.
3739 If the value of the variable is not a list but a single file name, then
3740 the list of agenda files is actually stored and maintained in that file, one
3741 agenda file per line. In this file paths can be given relative to
3742 `org-directory'. Tilde expansion and environment variable substitution
3743 are also made."
3744 :group 'org-agenda
3745 :type '(choice
3746 (repeat :tag "List of files and directories" file)
3747 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3749 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3750 "Regular expression to match files for `org-agenda-files'.
3751 If any element in the list in that variable contains a directory instead
3752 of a normal file, all files in that directory that are matched by this
3753 regular expression will be included."
3754 :group 'org-agenda
3755 :type 'regexp)
3757 (defcustom org-agenda-text-search-extra-files nil
3758 "List of extra files to be searched by text search commands.
3759 These files will be searched in addition to the agenda files by the
3760 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3761 Note that these files will only be searched for text search commands,
3762 not for the other agenda views like todo lists, tag searches or the weekly
3763 agenda. This variable is intended to list notes and possibly archive files
3764 that should also be searched by these two commands.
3765 In fact, if the first element in the list is the symbol `agenda-archives',
3766 then all archive files of all agenda files will be added to the search
3767 scope."
3768 :group 'org-agenda
3769 :type '(set :greedy t
3770 (const :tag "Agenda Archives" agenda-archives)
3771 (repeat :inline t (file))))
3773 (org-defvaralias 'org-agenda-multi-occur-extra-files
3774 'org-agenda-text-search-extra-files)
3776 (defcustom org-agenda-skip-unavailable-files nil
3777 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3778 A nil value means to remove them, after a query, from the list."
3779 :group 'org-agenda
3780 :type 'boolean)
3782 (defcustom org-calendar-to-agenda-key [?c]
3783 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3784 The command `org-calendar-goto-agenda' will be bound to this key. The
3785 default is the character `c' because then `c' can be used to switch back and
3786 forth between agenda and calendar."
3787 :group 'org-agenda
3788 :type 'sexp)
3790 (defcustom org-calendar-insert-diary-entry-key [?i]
3791 "The key to be installed in `calendar-mode-map' for adding diary entries.
3792 This option is irrelevant until `org-agenda-diary-file' has been configured
3793 to point to an Org-mode file. When that is the case, the command
3794 `org-agenda-diary-entry' will be bound to the key given here, by default
3795 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3796 if you want to continue doing this, you need to change this to a different
3797 key."
3798 :group 'org-agenda
3799 :type 'sexp)
3801 (defcustom org-agenda-diary-file 'diary-file
3802 "File to which to add new entries with the `i' key in agenda and calendar.
3803 When this is the symbol `diary-file', the functionality in the Emacs
3804 calendar will be used to add entries to the `diary-file'. But when this
3805 points to a file, `org-agenda-diary-entry' will be used instead."
3806 :group 'org-agenda
3807 :type '(choice
3808 (const :tag "The standard Emacs diary file" diary-file)
3809 (file :tag "Special Org file diary entries")))
3811 (eval-after-load "calendar"
3812 '(progn
3813 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3814 'org-calendar-goto-agenda)
3815 (add-hook 'calendar-mode-hook
3816 (lambda ()
3817 (unless (eq org-agenda-diary-file 'diary-file)
3818 (define-key calendar-mode-map
3819 org-calendar-insert-diary-entry-key
3820 'org-agenda-diary-entry))))))
3822 (defgroup org-latex nil
3823 "Options for embedding LaTeX code into Org-mode."
3824 :tag "Org LaTeX"
3825 :group 'org)
3827 (defcustom org-format-latex-options
3828 '(:foreground default :background default :scale 1.0
3829 :html-foreground "Black" :html-background "Transparent"
3830 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3831 "Options for creating images from LaTeX fragments.
3832 This is a property list with the following properties:
3833 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3834 `default' means use the foreground of the default face.
3835 `auto' means use the foreground from the text face.
3836 :background the background color, or \"Transparent\".
3837 `default' means use the background of the default face.
3838 `auto' means use the background from the text face.
3839 :scale a scaling factor for the size of the images, to get more pixels
3840 :html-foreground, :html-background, :html-scale
3841 the same numbers for HTML export.
3842 :matchers a list indicating which matchers should be used to
3843 find LaTeX fragments. Valid members of this list are:
3844 \"begin\" find environments
3845 \"$1\" find single characters surrounded by $.$
3846 \"$\" find math expressions surrounded by $...$
3847 \"$$\" find math expressions surrounded by $$....$$
3848 \"\\(\" find math expressions surrounded by \\(...\\)
3849 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3850 :group 'org-latex
3851 :type 'plist)
3853 (defcustom org-format-latex-signal-error t
3854 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3855 When nil, just push out a message."
3856 :group 'org-latex
3857 :version "24.1"
3858 :type 'boolean)
3860 (defcustom org-latex-to-mathml-jar-file nil
3861 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3862 Use this to specify additional executable file say a jar file.
3864 When using MathToWeb as the converter, specify the full-path to
3865 your mathtoweb.jar file."
3866 :group 'org-latex
3867 :version "24.1"
3868 :type '(choice
3869 (const :tag "None" nil)
3870 (file :tag "JAR file" :must-match t)))
3872 (defcustom org-latex-to-mathml-convert-command nil
3873 "Command to convert LaTeX fragments to MathML.
3874 Replace format-specifiers in the command as noted below and use
3875 `shell-command' to convert LaTeX to MathML.
3876 %j: Executable file in fully expanded form as specified by
3877 `org-latex-to-mathml-jar-file'.
3878 %I: Input LaTeX file in fully expanded form
3879 %o: Output MathML file
3880 This command is used by `org-create-math-formula'.
3882 When using MathToWeb as the converter, set this to
3883 \"java -jar %j -unicode -force -df %o %I\"."
3884 :group 'org-latex
3885 :version "24.1"
3886 :type '(choice
3887 (const :tag "None" nil)
3888 (string :tag "\nShell command")))
3890 (defcustom org-latex-create-formula-image-program 'dvipng
3891 "Program to convert LaTeX fragments with.
3893 dvipng Process the LaTeX fragments to dvi file, then convert
3894 dvi files to png files using dvipng.
3895 This will also include processing of non-math environments.
3896 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3897 to convert pdf files to png files"
3898 :group 'org-latex
3899 :version "24.1"
3900 :type '(choice
3901 (const :tag "dvipng" dvipng)
3902 (const :tag "imagemagick" imagemagick)))
3904 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3905 "Path to store latex preview images.
3906 A relative path here creates many directories relative to the
3907 processed org files paths. An absolute path puts all preview
3908 images at the same place."
3909 :group 'org-latex
3910 :version "24.3"
3911 :type 'string)
3913 (defun org-format-latex-mathml-available-p ()
3914 "Return t if `org-latex-to-mathml-convert-command' is usable."
3915 (save-match-data
3916 (when (and (boundp 'org-latex-to-mathml-convert-command)
3917 org-latex-to-mathml-convert-command)
3918 (let ((executable (car (split-string
3919 org-latex-to-mathml-convert-command))))
3920 (when (executable-find executable)
3921 (if (string-match
3922 "%j" org-latex-to-mathml-convert-command)
3923 (file-readable-p org-latex-to-mathml-jar-file)
3924 t))))))
3926 (defcustom org-format-latex-header "\\documentclass{article}
3927 \\usepackage[usenames]{color}
3928 \[PACKAGES]
3929 \[DEFAULT-PACKAGES]
3930 \\pagestyle{empty} % do not remove
3931 % The settings below are copied from fullpage.sty
3932 \\setlength{\\textwidth}{\\paperwidth}
3933 \\addtolength{\\textwidth}{-3cm}
3934 \\setlength{\\oddsidemargin}{1.5cm}
3935 \\addtolength{\\oddsidemargin}{-2.54cm}
3936 \\setlength{\\evensidemargin}{\\oddsidemargin}
3937 \\setlength{\\textheight}{\\paperheight}
3938 \\addtolength{\\textheight}{-\\headheight}
3939 \\addtolength{\\textheight}{-\\headsep}
3940 \\addtolength{\\textheight}{-\\footskip}
3941 \\addtolength{\\textheight}{-3cm}
3942 \\setlength{\\topmargin}{1.5cm}
3943 \\addtolength{\\topmargin}{-2.54cm}"
3944 "The document header used for processing LaTeX fragments.
3945 It is imperative that this header make sure that no page number
3946 appears on the page. The package defined in the variables
3947 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3948 will either replace the placeholder \"[PACKAGES]\" in this
3949 header, or they will be appended."
3950 :group 'org-latex
3951 :type 'string)
3953 (defun org-set-packages-alist (var val)
3954 "Set the packages alist and make sure it has 3 elements per entry."
3955 (set var (mapcar (lambda (x)
3956 (if (and (consp x) (= (length x) 2))
3957 (list (car x) (nth 1 x) t)
3959 val)))
3961 (defun org-get-packages-alist (var)
3962 "Get the packages alist and make sure it has 3 elements per entry."
3963 (mapcar (lambda (x)
3964 (if (and (consp x) (= (length x) 2))
3965 (list (car x) (nth 1 x) t)
3967 (default-value var)))
3969 (defcustom org-latex-default-packages-alist
3970 '(("AUTO" "inputenc" t)
3971 ("T1" "fontenc" t)
3972 ("" "fixltx2e" nil)
3973 ("" "graphicx" t)
3974 ("" "longtable" nil)
3975 ("" "float" nil)
3976 ("" "wrapfig" nil)
3977 ("" "rotating" nil)
3978 ("normalem" "ulem" t)
3979 ("" "amsmath" t)
3980 ("" "textcomp" t)
3981 ("" "marvosym" t)
3982 ("" "wasysym" t)
3983 ("" "amssymb" t)
3984 ("" "hyperref" nil)
3985 "\\tolerance=1000")
3986 "Alist of default packages to be inserted in the header.
3988 Change this only if one of the packages here causes an
3989 incompatibility with another package you are using.
3991 The packages in this list are needed by one part or another of
3992 Org mode to function properly:
3994 - inputenc, fontenc: for basic font and character selection
3995 - fixltx2e: Important patches of LaTeX itself
3996 - graphicx: for including images
3997 - longtable: For multipage tables
3998 - float, wrapfig: for figure placement
3999 - rotating: for sideways figures and tables
4000 - ulem: for underline and strike-through
4001 - amsmath: for subscript and superscript and math environments
4002 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4003 for interpreting the entities in `org-entities'. You can skip
4004 some of these packages if you don't use any of their symbols.
4005 - hyperref: for cross references
4007 Therefore you should not modify this variable unless you know
4008 what you are doing. The one reason to change it anyway is that
4009 you might be loading some other package that conflicts with one
4010 of the default packages. Each cell is of the format
4011 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
4012 the package also needs to be included when compiling LaTeX
4013 snippets into images for inclusion into non-LaTeX output."
4014 :group 'org-latex
4015 :group 'org-export-latex
4016 :set 'org-set-packages-alist
4017 :get 'org-get-packages-alist
4018 :version "24.1"
4019 :type '(repeat
4020 (choice
4021 (list :tag "options/package pair"
4022 (string :tag "options")
4023 (string :tag "package")
4024 (boolean :tag "Snippet"))
4025 (string :tag "A line of LaTeX"))))
4027 (defcustom org-latex-packages-alist nil
4028 "Alist of packages to be inserted in every LaTeX header.
4030 These will be inserted after `org-latex-default-packages-alist'.
4031 Each cell is of the format:
4033 \(\"options\" \"package\" snippet-flag)
4035 SNIPPET-FLAG, when t, indicates that this package is also needed
4036 when turning LaTeX snippets into images for inclusion into
4037 non-LaTeX output.
4039 Make sure that you only list packages here which:
4041 - you want in every file
4042 - do not conflict with the setup in `org-format-latex-header'.
4043 - do not conflict with the default packages in
4044 `org-latex-default-packages-alist'."
4045 :group 'org-latex
4046 :group 'org-export-latex
4047 :set 'org-set-packages-alist
4048 :get 'org-get-packages-alist
4049 :type '(repeat
4050 (choice
4051 (list :tag "options/package pair"
4052 (string :tag "options")
4053 (string :tag "package")
4054 (boolean :tag "Snippet"))
4055 (string :tag "A line of LaTeX"))))
4057 (defgroup org-appearance nil
4058 "Settings for Org-mode appearance."
4059 :tag "Org Appearance"
4060 :group 'org)
4062 (defcustom org-level-color-stars-only nil
4063 "Non-nil means fontify only the stars in each headline.
4064 When nil, the entire headline is fontified.
4065 Changing it requires restart of `font-lock-mode' to become effective
4066 also in regions already fontified."
4067 :group 'org-appearance
4068 :type 'boolean)
4070 (defcustom org-hide-leading-stars nil
4071 "Non-nil means hide the first N-1 stars in a headline.
4072 This works by using the face `org-hide' for these stars. This
4073 face is white for a light background, and black for a dark
4074 background. You may have to customize the face `org-hide' to
4075 make this work.
4076 Changing it requires restart of `font-lock-mode' to become effective
4077 also in regions already fontified.
4078 You may also set this on a per-file basis by adding one of the following
4079 lines to the buffer:
4081 #+STARTUP: hidestars
4082 #+STARTUP: showstars"
4083 :group 'org-appearance
4084 :type 'boolean)
4086 (defcustom org-hidden-keywords nil
4087 "List of symbols corresponding to keywords to be hidden the org buffer.
4088 For example, a value '(title) for this list will make the document's title
4089 appear in the buffer without the initial #+TITLE: keyword."
4090 :group 'org-appearance
4091 :version "24.1"
4092 :type '(set (const :tag "#+AUTHOR" author)
4093 (const :tag "#+DATE" date)
4094 (const :tag "#+EMAIL" email)
4095 (const :tag "#+TITLE" title)))
4097 (defcustom org-custom-properties nil
4098 "List of properties (as strings) with a special meaning.
4099 The default use of these custom properties is to let the user
4100 hide them with `org-toggle-custom-properties-visibility'."
4101 :group 'org-properties
4102 :group 'org-appearance
4103 :version "24.3"
4104 :type '(repeat (string :tag "Property Name")))
4106 (defcustom org-fontify-done-headline nil
4107 "Non-nil means change the face of a headline if it is marked DONE.
4108 Normally, only the TODO/DONE keyword indicates the state of a headline.
4109 When this is non-nil, the headline after the keyword is set to the
4110 `org-headline-done' as an additional indication."
4111 :group 'org-appearance
4112 :type 'boolean)
4114 (defcustom org-fontify-emphasized-text t
4115 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4116 Changing this variable requires a restart of Emacs to take effect."
4117 :group 'org-appearance
4118 :type 'boolean)
4120 (defcustom org-fontify-whole-heading-line nil
4121 "Non-nil means fontify the whole line for headings.
4122 This is useful when setting a background color for the
4123 org-level-* faces."
4124 :group 'org-appearance
4125 :type 'boolean)
4127 (defcustom org-highlight-latex-and-related nil
4128 "Non-nil means highlight LaTeX related syntax in the buffer.
4129 When non nil, the value should be a list containing any of the
4130 following symbols:
4131 `latex' Highlight LaTeX snippets and environments.
4132 `script' Highlight subscript and superscript.
4133 `entities' Highlight entities."
4134 :group 'org-appearance
4135 :version "24.4"
4136 :package-version '(Org . "8.0")
4137 :type '(choice
4138 (const :tag "No highlighting" nil)
4139 (set :greedy t :tag "Highlight"
4140 (const :tag "LaTeX snippets and environments" latex)
4141 (const :tag "Subscript and superscript" script)
4142 (const :tag "Entities" entities))))
4144 (defcustom org-hide-emphasis-markers nil
4145 "Non-nil mean font-lock should hide the emphasis marker characters."
4146 :group 'org-appearance
4147 :type 'boolean)
4149 (defcustom org-pretty-entities nil
4150 "Non-nil means show entities as UTF8 characters.
4151 When nil, the \\name form remains in the buffer."
4152 :group 'org-appearance
4153 :version "24.1"
4154 :type 'boolean)
4156 (defcustom org-pretty-entities-include-sub-superscripts t
4157 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4158 :group 'org-appearance
4159 :version "24.1"
4160 :type 'boolean)
4162 (defvar org-emph-re nil
4163 "Regular expression for matching emphasis.
4164 After a match, the match groups contain these elements:
4165 0 The match of the full regular expression, including the characters
4166 before and after the proper match
4167 1 The character before the proper match, or empty at beginning of line
4168 2 The proper match, including the leading and trailing markers
4169 3 The leading marker like * or /, indicating the type of highlighting
4170 4 The text between the emphasis markers, not including the markers
4171 5 The character after the match, empty at the end of a line")
4172 (defvar org-verbatim-re nil
4173 "Regular expression for matching verbatim text.")
4174 (defvar org-emphasis-regexp-components) ; defined just below
4175 (defvar org-emphasis-alist) ; defined just below
4176 (defun org-set-emph-re (var val)
4177 "Set variable and compute the emphasis regular expression."
4178 (set var val)
4179 (when (and (boundp 'org-emphasis-alist)
4180 (boundp 'org-emphasis-regexp-components)
4181 org-emphasis-alist org-emphasis-regexp-components)
4182 (let* ((e org-emphasis-regexp-components)
4183 (pre (car e))
4184 (post (nth 1 e))
4185 (border (nth 2 e))
4186 (body (nth 3 e))
4187 (nl (nth 4 e))
4188 (body1 (concat body "*?"))
4189 (markers (mapconcat 'car org-emphasis-alist ""))
4190 (vmarkers (mapconcat
4191 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4192 org-emphasis-alist "")))
4193 ;; make sure special characters appear at the right position in the class
4194 (if (string-match "\\^" markers)
4195 (setq markers (concat (replace-match "" t t markers) "^")))
4196 (if (string-match "-" markers)
4197 (setq markers (concat (replace-match "" t t markers) "-")))
4198 (if (string-match "\\^" vmarkers)
4199 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4200 (if (string-match "-" vmarkers)
4201 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4202 (if (> nl 0)
4203 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4204 (int-to-string nl) "\\}")))
4205 ;; Make the regexp
4206 (setq org-emph-re
4207 (concat "\\([" pre "]\\|^\\)"
4208 "\\("
4209 "\\([" markers "]\\)"
4210 "\\("
4211 "[^" border "]\\|"
4212 "[^" border "]"
4213 body1
4214 "[^" border "]"
4215 "\\)"
4216 "\\3\\)"
4217 "\\([" post "]\\|$\\)"))
4218 (setq org-verbatim-re
4219 (concat "\\([" pre "]\\|^\\)"
4220 "\\("
4221 "\\([" vmarkers "]\\)"
4222 "\\("
4223 "[^" border "]\\|"
4224 "[^" border "]"
4225 body1
4226 "[^" border "]"
4227 "\\)"
4228 "\\3\\)"
4229 "\\([" post "]\\|$\\)")))))
4231 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4232 ;; set this option proved cumbersome. See this message/thread:
4233 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4234 (defvar org-emphasis-regexp-components
4235 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4236 "Components used to build the regular expression for emphasis.
4237 This is a list with five entries. Terminology: In an emphasis string
4238 like \" *strong word* \", we call the initial space PREMATCH, the final
4239 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4240 and \"trong wor\" is the body. The different components in this variable
4241 specify what is allowed/forbidden in each part:
4243 pre Chars allowed as prematch. Beginning of line will be allowed too.
4244 post Chars allowed as postmatch. End of line will be allowed too.
4245 border The chars *forbidden* as border characters.
4246 body-regexp A regexp like \".\" to match a body character. Don't use
4247 non-shy groups here, and don't allow newline here.
4248 newline The maximum number of newlines allowed in an emphasis exp.
4250 You need to reload Org or to restart Emacs after customizing this.")
4252 (defcustom org-emphasis-alist
4253 `(("*" bold)
4254 ("/" italic)
4255 ("_" underline)
4256 ("=" org-code verbatim)
4257 ("~" org-verbatim verbatim)
4258 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4259 "Alist of characters and faces to emphasize text.
4260 Text starting and ending with a special character will be emphasized,
4261 for example *bold*, _underlined_ and /italic/. This variable sets the
4262 marker characters and the face to be used by font-lock for highlighting
4263 in Org-mode Emacs buffers.
4265 You need to reload Org or to restart Emacs after customizing this."
4266 :group 'org-appearance
4267 :set 'org-set-emph-re
4268 :version "24.4"
4269 :package-version '(Org . "8.0")
4270 :type '(repeat
4271 (list
4272 (string :tag "Marker character")
4273 (choice
4274 (face :tag "Font-lock-face")
4275 (plist :tag "Face property list"))
4276 (option (const verbatim)))))
4278 (defvar org-protecting-blocks
4279 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4280 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4281 This is needed for font-lock setup.")
4283 ;;; Miscellaneous options
4285 (defgroup org-completion nil
4286 "Completion in Org-mode."
4287 :tag "Org Completion"
4288 :group 'org)
4290 (defcustom org-completion-use-ido nil
4291 "Non-nil means use ido completion wherever possible.
4292 Note that `ido-mode' must be active for this variable to be relevant.
4293 If you decide to turn this variable on, you might well want to turn off
4294 `org-outline-path-complete-in-steps'.
4295 See also `org-completion-use-iswitchb'."
4296 :group 'org-completion
4297 :type 'boolean)
4299 (defcustom org-completion-use-iswitchb nil
4300 "Non-nil means use iswitchb completion wherever possible.
4301 Note that `iswitchb-mode' must be active for this variable to be relevant.
4302 If you decide to turn this variable on, you might well want to turn off
4303 `org-outline-path-complete-in-steps'.
4304 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4305 :group 'org-completion
4306 :type 'boolean)
4308 (defcustom org-completion-fallback-command 'hippie-expand
4309 "The expansion command called by \\[pcomplete] in normal context.
4310 Normal means, no org-mode-specific context."
4311 :group 'org-completion
4312 :type 'function)
4314 ;;; Functions and variables from their packages
4315 ;; Declared here to avoid compiler warnings
4317 ;; XEmacs only
4318 (defvar outline-mode-menu-heading)
4319 (defvar outline-mode-menu-show)
4320 (defvar outline-mode-menu-hide)
4321 (defvar zmacs-regions) ; XEmacs regions
4323 ;; Emacs only
4324 (defvar mark-active)
4326 ;; Various packages
4327 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4328 (declare-function calendar-forward-day "cal-move" (arg))
4329 (declare-function calendar-goto-date "cal-move" (date))
4330 (declare-function calendar-goto-today "cal-move" ())
4331 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4332 (defvar calc-embedded-close-formula)
4333 (defvar calc-embedded-open-formula)
4334 (declare-function cdlatex-tab "ext:cdlatex" ())
4335 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4336 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4337 (defvar font-lock-unfontify-region-function)
4338 (declare-function iswitchb-read-buffer "iswitchb"
4339 (prompt &optional default require-match start matches-set))
4340 (defvar iswitchb-temp-buflist)
4341 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4342 (defvar org-agenda-tags-todo-honor-ignore-options)
4343 (declare-function org-agenda-skip "org-agenda" ())
4344 (declare-function
4345 org-agenda-format-item "org-agenda"
4346 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4347 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4348 (declare-function org-agenda-change-all-lines "org-agenda"
4349 (newhead hdmarker &optional fixface just-this))
4350 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4351 (declare-function org-agenda-maybe-redo "org-agenda" ())
4352 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4353 (beg end))
4354 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4355 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4356 "org-agenda" (&optional end))
4357 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4358 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4359 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4360 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4361 (declare-function org-indent-mode "org-indent" (&optional arg))
4362 (declare-function parse-time-string "parse-time" (string))
4363 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4364 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4365 (defvar remember-data-file)
4366 (defvar texmathp-why)
4367 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4368 (declare-function table--at-cell-p "table" (position &optional object at-column))
4370 ;;;###autoload
4371 (defun turn-on-orgtbl ()
4372 "Unconditionally turn on `orgtbl-mode'."
4373 (require 'org-table)
4374 (orgtbl-mode 1))
4376 (defun org-at-table-p (&optional table-type)
4377 "Return t if the cursor is inside an org-type table.
4378 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4379 (if org-enable-table-editor
4380 (save-excursion
4381 (beginning-of-line 1)
4382 (looking-at (if table-type org-table-any-line-regexp
4383 org-table-line-regexp)))
4384 nil))
4385 (defsubst org-table-p () (org-at-table-p))
4387 (defun org-at-table.el-p ()
4388 "Return t if and only if we are at a table.el table."
4389 (and (org-at-table-p 'any)
4390 (save-excursion
4391 (goto-char (org-table-begin 'any))
4392 (looking-at org-table1-hline-regexp))))
4394 (defun org-table-recognize-table.el ()
4395 "If there is a table.el table nearby, recognize it and move into it."
4396 (if org-table-tab-recognizes-table.el
4397 (if (org-at-table.el-p)
4398 (progn
4399 (beginning-of-line 1)
4400 (if (looking-at org-table-dataline-regexp)
4402 (if (looking-at org-table1-hline-regexp)
4403 (progn
4404 (beginning-of-line 2)
4405 (if (looking-at org-table-any-border-regexp)
4406 (beginning-of-line -1)))))
4407 (if (re-search-forward "|" (org-table-end t) t)
4408 (progn
4409 (require 'table)
4410 (if (table--at-cell-p (point))
4412 (message "recognizing table.el table...")
4413 (table-recognize-table)
4414 (message "recognizing table.el table...done")))
4415 (error "This should not happen"))
4417 nil)
4418 nil))
4420 (defun org-at-table-hline-p ()
4421 "Return t if the cursor is inside a hline in a table."
4422 (if org-enable-table-editor
4423 (save-excursion
4424 (beginning-of-line 1)
4425 (looking-at org-table-hline-regexp))
4426 nil))
4428 (defun org-table-map-tables (function &optional quietly)
4429 "Apply FUNCTION to the start of all tables in the buffer."
4430 (save-excursion
4431 (save-restriction
4432 (widen)
4433 (goto-char (point-min))
4434 (while (re-search-forward org-table-any-line-regexp nil t)
4435 (unless quietly
4436 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4437 (beginning-of-line 1)
4438 (when (and (looking-at org-table-line-regexp)
4439 ;; Exclude tables in src/example/verbatim/clocktable blocks
4440 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4441 (save-excursion (funcall function))
4442 (or (looking-at org-table-line-regexp)
4443 (forward-char 1)))
4444 (re-search-forward org-table-any-border-regexp nil 1))))
4445 (unless quietly (message "Mapping tables: done")))
4447 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4448 (declare-function org-clock-update-mode-line "org-clock" ())
4449 (declare-function org-resolve-clocks "org-clock"
4450 (&optional also-non-dangling-p prompt last-valid))
4452 (defun org-at-TBLFM-p (&optional pos)
4453 "Return t when point (or POS) is in #+TBLFM line."
4454 (save-excursion
4455 (let ((pos pos)))
4456 (goto-char (or pos (point)))
4457 (beginning-of-line 1)
4458 (looking-at org-TBLFM-regexp)))
4460 (defvar org-clock-start-time)
4461 (defvar org-clock-marker (make-marker)
4462 "Marker recording the last clock-in.")
4463 (defvar org-clock-hd-marker (make-marker)
4464 "Marker recording the last clock-in, but the headline position.")
4465 (defvar org-clock-heading ""
4466 "The heading of the current clock entry.")
4467 (defun org-clock-is-active ()
4468 "Return the buffer where the clock is currently running.
4469 Return nil if no clock is running."
4470 (marker-buffer org-clock-marker))
4472 (defun org-check-running-clock ()
4473 "Check if the current buffer contains the running clock.
4474 If yes, offer to stop it and to save the buffer with the changes."
4475 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4476 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4477 (buffer-name))))
4478 (org-clock-out)
4479 (when (y-or-n-p "Save changed buffer?")
4480 (save-buffer))))
4482 (defun org-clocktable-try-shift (dir n)
4483 "Check if this line starts a clock table, if yes, shift the time block."
4484 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4485 (org-clocktable-shift dir n)))
4487 ;;;###autoload
4488 (defun org-clock-persistence-insinuate ()
4489 "Set up hooks for clock persistence."
4490 (require 'org-clock)
4491 (add-hook 'org-mode-hook 'org-clock-load)
4492 (add-hook 'kill-emacs-hook 'org-clock-save))
4494 (defgroup org-archive nil
4495 "Options concerning archiving in Org-mode."
4496 :tag "Org Archive"
4497 :group 'org-structure)
4499 (defcustom org-archive-location "%s_archive::"
4500 "The location where subtrees should be archived.
4502 The value of this variable is a string, consisting of two parts,
4503 separated by a double-colon. The first part is a filename and
4504 the second part is a headline.
4506 When the filename is omitted, archiving happens in the same file.
4507 %s in the filename will be replaced by the current file
4508 name (without the directory part). Archiving to a different file
4509 is useful to keep archived entries from contributing to the
4510 Org-mode Agenda.
4512 The archived entries will be filed as subtrees of the specified
4513 headline. When the headline is omitted, the subtrees are simply
4514 filed away at the end of the file, as top-level entries. Also in
4515 the heading you can use %s to represent the file name, this can be
4516 useful when using the same archive for a number of different files.
4518 Here are a few examples:
4519 \"%s_archive::\"
4520 If the current file is Projects.org, archive in file
4521 Projects.org_archive, as top-level trees. This is the default.
4523 \"::* Archived Tasks\"
4524 Archive in the current file, under the top-level headline
4525 \"* Archived Tasks\".
4527 \"~/org/archive.org::\"
4528 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4530 \"~/org/archive.org::* From %s\"
4531 Archive in file ~/org/archive.org (absolute path), under headlines
4532 \"From FILENAME\" where file name is the current file name.
4534 \"~/org/datetree.org::datetree/* Finished Tasks\"
4535 The \"datetree/\" string is special, signifying to archive
4536 items to the datetree. Items are placed in either the CLOSED
4537 date of the item, or the current date if there is no CLOSED date.
4538 The heading will be a subentry to the current date. There doesn't
4539 need to be a heading, but there always needs to be a slash after
4540 datetree. For example, to store archived items directly in the
4541 datetree, use \"~/org/datetree.org::datetree/\".
4543 \"basement::** Finished Tasks\"
4544 Archive in file ./basement (relative path), as level 3 trees
4545 below the level 2 heading \"** Finished Tasks\".
4547 You may set this option on a per-file basis by adding to the buffer a
4548 line like
4550 #+ARCHIVE: basement::** Finished Tasks
4552 You may also define it locally for a subtree by setting an ARCHIVE property
4553 in the entry. If such a property is found in an entry, or anywhere up
4554 the hierarchy, it will be used."
4555 :group 'org-archive
4556 :type 'string)
4558 (defcustom org-agenda-skip-archived-trees t
4559 "Non-nil means the agenda will skip any items located in archived trees.
4560 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4561 variable is no longer recommended, you should leave it at the value t.
4562 Instead, use the key `v' to cycle the archives-mode in the agenda."
4563 :group 'org-archive
4564 :group 'org-agenda-skip
4565 :type 'boolean)
4567 (defcustom org-columns-skip-archived-trees t
4568 "Non-nil means ignore archived trees when creating column view."
4569 :group 'org-archive
4570 :group 'org-properties
4571 :type 'boolean)
4573 (defcustom org-cycle-open-archived-trees nil
4574 "Non-nil means `org-cycle' will open archived trees.
4575 An archived tree is a tree marked with the tag ARCHIVE.
4576 When nil, archived trees will stay folded. You can still open them with
4577 normal outline commands like `show-all', but not with the cycling commands."
4578 :group 'org-archive
4579 :group 'org-cycle
4580 :type 'boolean)
4582 (defcustom org-sparse-tree-open-archived-trees nil
4583 "Non-nil means sparse tree construction shows matches in archived trees.
4584 When nil, matches in these trees are highlighted, but the trees are kept in
4585 collapsed state."
4586 :group 'org-archive
4587 :group 'org-sparse-trees
4588 :type 'boolean)
4590 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4591 "The default date type when building a sparse tree.
4592 When this is nil, a date is a scheduled or a deadline timestamp.
4593 Otherwise, these types are allowed:
4595 all: all timestamps
4596 active: only active timestamps (<...>)
4597 inactive: only inactive timestamps (<...)
4598 scheduled: only scheduled timestamps
4599 deadline: only deadline timestamps"
4600 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4601 (const :tag "All timestamps" all)
4602 (const :tag "Only active timestamps" active)
4603 (const :tag "Only inactive timestamps" inactive)
4604 (const :tag "Only scheduled timestamps" scheduled)
4605 (const :tag "Only deadline timestamps" deadline)
4606 (const :tag "Only closed timestamps" closed))
4607 :version "24.3"
4608 :group 'org-sparse-trees)
4610 (defun org-cycle-hide-archived-subtrees (state)
4611 "Re-hide all archived subtrees after a visibility state change."
4612 (when (and (not org-cycle-open-archived-trees)
4613 (not (memq state '(overview folded))))
4614 (save-excursion
4615 (let* ((globalp (memq state '(contents all)))
4616 (beg (if globalp (point-min) (point)))
4617 (end (if globalp (point-max) (org-end-of-subtree t))))
4618 (org-hide-archived-subtrees beg end)
4619 (goto-char beg)
4620 (if (looking-at (concat ".*:" org-archive-tag ":"))
4621 (message "%s" (substitute-command-keys
4622 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4624 (defun org-force-cycle-archived ()
4625 "Cycle subtree even if it is archived."
4626 (interactive)
4627 (setq this-command 'org-cycle)
4628 (let ((org-cycle-open-archived-trees t))
4629 (call-interactively 'org-cycle)))
4631 (defun org-hide-archived-subtrees (beg end)
4632 "Re-hide all archived subtrees after a visibility state change."
4633 (save-excursion
4634 (let* ((re (concat ":" org-archive-tag ":")))
4635 (goto-char beg)
4636 (while (re-search-forward re end t)
4637 (when (org-at-heading-p)
4638 (org-flag-subtree t)
4639 (org-end-of-subtree t))))))
4641 (declare-function outline-end-of-heading "outline" ())
4642 (declare-function outline-flag-region "outline" (from to flag))
4643 (defun org-flag-subtree (flag)
4644 (save-excursion
4645 (org-back-to-heading t)
4646 (outline-end-of-heading)
4647 (outline-flag-region (point)
4648 (progn (org-end-of-subtree t) (point))
4649 flag)))
4651 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4653 ;; Declare Column View Code
4655 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4656 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4657 (declare-function org-columns-compute "org-colview" (property))
4659 ;; Declare ID code
4661 (declare-function org-id-store-link "org-id")
4662 (declare-function org-id-locations-load "org-id")
4663 (declare-function org-id-locations-save "org-id")
4664 (defvar org-id-track-globally)
4666 ;;; Variables for pre-computed regular expressions, all buffer local
4668 (defvar org-todo-regexp nil
4669 "Matches any of the TODO state keywords.")
4670 (make-variable-buffer-local 'org-todo-regexp)
4671 (defvar org-not-done-regexp nil
4672 "Matches any of the TODO state keywords except the last one.")
4673 (make-variable-buffer-local 'org-not-done-regexp)
4674 (defvar org-not-done-heading-regexp nil
4675 "Matches a TODO headline that is not done.")
4676 (make-variable-buffer-local 'org-not-done-regexp)
4677 (defvar org-todo-line-regexp nil
4678 "Matches a headline and puts TODO state into group 2 if present.")
4679 (make-variable-buffer-local 'org-todo-line-regexp)
4680 (defvar org-complex-heading-regexp nil
4681 "Matches a headline and puts everything into groups:
4682 group 1: the stars
4683 group 2: The todo keyword, maybe
4684 group 3: Priority cookie
4685 group 4: True headline
4686 group 5: Tags")
4687 (make-variable-buffer-local 'org-complex-heading-regexp)
4688 (defvar org-complex-heading-regexp-format nil
4689 "Printf format to make regexp to match an exact headline.
4690 This regexp will match the headline of any node which has the
4691 exact headline text that is put into the format, but may have any
4692 TODO state, priority and tags.")
4693 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4694 (defvar org-todo-line-tags-regexp nil
4695 "Matches a headline and puts TODO state into group 2 if present.
4696 Also put tags into group 4 if tags are present.")
4697 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4698 (defvar org-ds-keyword-length 12
4699 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4700 (make-variable-buffer-local 'org-ds-keyword-length)
4701 (defvar org-deadline-regexp nil
4702 "Matches the DEADLINE keyword.")
4703 (make-variable-buffer-local 'org-deadline-regexp)
4704 (defvar org-deadline-time-regexp nil
4705 "Matches the DEADLINE keyword together with a time stamp.")
4706 (make-variable-buffer-local 'org-deadline-time-regexp)
4707 (defvar org-deadline-time-hour-regexp nil
4708 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4709 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4710 (defvar org-deadline-line-regexp nil
4711 "Matches the DEADLINE keyword and the rest of the line.")
4712 (make-variable-buffer-local 'org-deadline-line-regexp)
4713 (defvar org-scheduled-regexp nil
4714 "Matches the SCHEDULED keyword.")
4715 (make-variable-buffer-local 'org-scheduled-regexp)
4716 (defvar org-scheduled-time-regexp nil
4717 "Matches the SCHEDULED keyword together with a time stamp.")
4718 (make-variable-buffer-local 'org-scheduled-time-regexp)
4719 (defvar org-scheduled-time-hour-regexp nil
4720 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4721 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4722 (defvar org-closed-time-regexp nil
4723 "Matches the CLOSED keyword together with a time stamp.")
4724 (make-variable-buffer-local 'org-closed-time-regexp)
4726 (defvar org-keyword-time-regexp nil
4727 "Matches any of the 4 keywords, together with the time stamp.")
4728 (make-variable-buffer-local 'org-keyword-time-regexp)
4729 (defvar org-keyword-time-not-clock-regexp nil
4730 "Matches any of the 3 keywords, together with the time stamp.")
4731 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4732 (defvar org-maybe-keyword-time-regexp nil
4733 "Matches a timestamp, possibly preceded by a keyword.")
4734 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4735 (defvar org-all-time-keywords nil
4736 "List of time keywords.")
4737 (make-variable-buffer-local 'org-all-time-keywords)
4739 (defconst org-plain-time-of-day-regexp
4740 (concat
4741 "\\(\\<[012]?[0-9]"
4742 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4743 "\\(--?"
4744 "\\(\\<[012]?[0-9]"
4745 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4746 "\\)?")
4747 "Regular expression to match a plain time or time range.
4748 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4749 groups carry important information:
4750 0 the full match
4751 1 the first time, range or not
4752 8 the second time, if it is a range.")
4754 (defconst org-plain-time-extension-regexp
4755 (concat
4756 "\\(\\<[012]?[0-9]"
4757 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4758 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4759 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4760 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4761 groups carry important information:
4762 0 the full match
4763 7 hours of duration
4764 9 minutes of duration")
4766 (defconst org-stamp-time-of-day-regexp
4767 (concat
4768 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4769 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4770 "\\(--?"
4771 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4772 "Regular expression to match a timestamp time or time range.
4773 After a match, the following groups carry important information:
4774 0 the full match
4775 1 date plus weekday, for back referencing to make sure both times are on the same day
4776 2 the first time, range or not
4777 4 the second time, if it is a range.")
4779 (defconst org-startup-options
4780 '(("fold" org-startup-folded t)
4781 ("overview" org-startup-folded t)
4782 ("nofold" org-startup-folded nil)
4783 ("showall" org-startup-folded nil)
4784 ("showeverything" org-startup-folded showeverything)
4785 ("content" org-startup-folded content)
4786 ("indent" org-startup-indented t)
4787 ("noindent" org-startup-indented nil)
4788 ("hidestars" org-hide-leading-stars t)
4789 ("showstars" org-hide-leading-stars nil)
4790 ("odd" org-odd-levels-only t)
4791 ("oddeven" org-odd-levels-only nil)
4792 ("align" org-startup-align-all-tables t)
4793 ("noalign" org-startup-align-all-tables nil)
4794 ("inlineimages" org-startup-with-inline-images t)
4795 ("noinlineimages" org-startup-with-inline-images nil)
4796 ("latexpreview" org-startup-with-latex-preview t)
4797 ("nolatexpreview" org-startup-with-latex-preview nil)
4798 ("customtime" org-display-custom-times t)
4799 ("logdone" org-log-done time)
4800 ("lognotedone" org-log-done note)
4801 ("nologdone" org-log-done nil)
4802 ("lognoteclock-out" org-log-note-clock-out t)
4803 ("nolognoteclock-out" org-log-note-clock-out nil)
4804 ("logrepeat" org-log-repeat state)
4805 ("lognoterepeat" org-log-repeat note)
4806 ("logdrawer" org-log-into-drawer t)
4807 ("nologdrawer" org-log-into-drawer nil)
4808 ("logstatesreversed" org-log-states-order-reversed t)
4809 ("nologstatesreversed" org-log-states-order-reversed nil)
4810 ("nologrepeat" org-log-repeat nil)
4811 ("logreschedule" org-log-reschedule time)
4812 ("lognotereschedule" org-log-reschedule note)
4813 ("nologreschedule" org-log-reschedule nil)
4814 ("logredeadline" org-log-redeadline time)
4815 ("lognoteredeadline" org-log-redeadline note)
4816 ("nologredeadline" org-log-redeadline nil)
4817 ("logrefile" org-log-refile time)
4818 ("lognoterefile" org-log-refile note)
4819 ("nologrefile" org-log-refile nil)
4820 ("fninline" org-footnote-define-inline t)
4821 ("nofninline" org-footnote-define-inline nil)
4822 ("fnlocal" org-footnote-section nil)
4823 ("fnauto" org-footnote-auto-label t)
4824 ("fnprompt" org-footnote-auto-label nil)
4825 ("fnconfirm" org-footnote-auto-label confirm)
4826 ("fnplain" org-footnote-auto-label plain)
4827 ("fnadjust" org-footnote-auto-adjust t)
4828 ("nofnadjust" org-footnote-auto-adjust nil)
4829 ("constcgs" constants-unit-system cgs)
4830 ("constSI" constants-unit-system SI)
4831 ("noptag" org-tag-persistent-alist nil)
4832 ("hideblocks" org-hide-block-startup t)
4833 ("nohideblocks" org-hide-block-startup nil)
4834 ("beamer" org-startup-with-beamer-mode t)
4835 ("entitiespretty" org-pretty-entities t)
4836 ("entitiesplain" org-pretty-entities nil))
4837 "Variable associated with STARTUP options for org-mode.
4838 Each element is a list of three items: the startup options (as written
4839 in the #+STARTUP line), the corresponding variable, and the value to set
4840 this variable to if the option is found. An optional forth element PUSH
4841 means to push this value onto the list in the variable.")
4843 (defun org-update-property-plist (key val props)
4844 "Update PROPS with KEY and VAL."
4845 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4846 (key (if appending (substring key 0 (- (length key) 1)) key))
4847 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4848 (previous (cdr (assoc key props))))
4849 (if appending
4850 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4851 (cons (cons key val) remainder))))
4853 (defcustom org-group-tags t
4854 "When non-nil (the default), use group tags.
4855 This can be turned on/off through `org-toggle-tags-groups'."
4856 :group 'org-tags
4857 :group 'org-startup
4858 :type 'boolean)
4860 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4862 (defun org-toggle-tags-groups ()
4863 "Toggle support for group tags.
4864 Support for group tags is controlled by the option
4865 `org-group-tags', which is non-nil by default."
4866 (interactive)
4867 (setq org-group-tags (not org-group-tags))
4868 (cond ((and (derived-mode-p 'org-agenda-mode)
4869 org-group-tags)
4870 (org-agenda-redo))
4871 ((derived-mode-p 'org-mode)
4872 (let ((org-inhibit-startup t)) (org-mode))))
4873 (message "Groups tags support has been turned %s"
4874 (if org-group-tags "on" "off")))
4876 (defun org-set-regexps-and-options-for-tags ()
4877 "Precompute variables used for tags."
4878 (when (derived-mode-p 'org-mode)
4879 (org-set-local 'org-file-tags nil)
4880 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4881 (splitre "[ \t]+")
4882 (start 0)
4883 tags ftags key value)
4884 (save-excursion
4885 (save-restriction
4886 (widen)
4887 (goto-char (point-min))
4888 (while (re-search-forward re nil t)
4889 (setq key (upcase (org-match-string-no-properties 1))
4890 value (org-match-string-no-properties 2))
4891 (if (stringp value) (setq value (org-trim value)))
4892 (cond
4893 ((equal key "TAGS")
4894 (setq tags (append tags (if tags '("\\n") nil)
4895 (org-split-string value splitre))))
4896 ((equal key "FILETAGS")
4897 (when (string-match "\\S-" value)
4898 (setq ftags
4899 (append
4900 ftags
4901 (apply 'append
4902 (mapcar (lambda (x) (org-split-string x ":"))
4903 (org-split-string value)))))))))))
4904 ;; Process the file tags.
4905 (and ftags (org-set-local 'org-file-tags
4906 (mapcar 'org-add-prop-inherited ftags)))
4907 (org-set-local 'org-tag-groups-alist nil)
4908 ;; Process the tags.
4909 (when (and (not tags) org-tag-alist)
4910 (setq tags
4911 (mapcar
4912 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4913 ((eq (car tg) :endgroup) "}")
4914 ((eq (car tg) :grouptags) ":")
4915 ((eq (car tg) :newline) "\n")
4916 (t (concat (car tg)
4917 (if (characterp (cdr tg))
4918 (format "(%s)" (char-to-string (cdr tg))) "")))))
4919 org-tag-alist)))
4920 (let (e tgs g)
4921 (while (setq e (pop tags))
4922 (cond
4923 ((equal e "{")
4924 (progn (push '(:startgroup) tgs)
4925 (when (equal (nth 1 tags) ":")
4926 (push (list (replace-regexp-in-string
4927 "(.+)$" "" (nth 0 tags)))
4928 org-tag-groups-alist)
4929 (setq g 0))))
4930 ((equal e ":") (push '(:grouptags) tgs))
4931 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4932 ((equal e "\\n") (push '(:newline) tgs))
4933 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4934 (push (cons (match-string 1 e)
4935 (string-to-char (match-string 2 e))) tgs)
4936 (if (and g (> g 0))
4937 (setcar org-tag-groups-alist
4938 (append (car org-tag-groups-alist)
4939 (list (match-string 1 e)))))
4940 (if g (setq g (1+ g))))
4941 (t (push (list e) tgs)
4942 (if (and g (> g 0))
4943 (setcar org-tag-groups-alist
4944 (append (car org-tag-groups-alist) (list e))))
4945 (if g (setq g (1+ g))))))
4946 (org-set-local 'org-tag-alist nil)
4947 (while (setq e (pop tgs))
4948 (or (and (stringp (car e))
4949 (assoc (car e) org-tag-alist))
4950 (push e org-tag-alist)))
4951 ;; Return a list with tag variables
4952 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4954 (defvar org-ota nil)
4955 (defun org-set-regexps-and-options ()
4956 "Precompute regular expressions used in the current buffer."
4957 (when (derived-mode-p 'org-mode)
4958 (org-set-local 'org-todo-kwd-alist nil)
4959 (org-set-local 'org-todo-key-alist nil)
4960 (org-set-local 'org-todo-key-trigger nil)
4961 (org-set-local 'org-todo-keywords-1 nil)
4962 (org-set-local 'org-done-keywords nil)
4963 (org-set-local 'org-todo-heads nil)
4964 (org-set-local 'org-todo-sets nil)
4965 (org-set-local 'org-todo-log-states nil)
4966 (org-set-local 'org-file-properties nil)
4967 (let ((re (org-make-options-regexp
4968 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4969 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4970 "SETUPFILE" "OPTIONS")
4971 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4972 (splitre "[ \t]+")
4973 (scripts org-use-sub-superscripts)
4974 kwds kws0 kwsa key log value cat arch const links hw dws
4975 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4976 (start 0))
4977 (save-excursion
4978 (save-restriction
4979 (widen)
4980 (goto-char (point-min))
4981 (while
4982 (or (and
4983 ext-setup-or-nil
4984 (not org-ota)
4985 (let (ret)
4986 (with-temp-buffer
4987 (insert ext-setup-or-nil)
4988 (let ((major-mode 'org-mode) org-ota)
4989 (setq ret (save-match-data
4990 (org-set-regexps-and-options-for-tags)))))
4991 ;; Append setupfile tags to existing tags
4992 (setq org-ota t)
4993 (setq org-file-tags
4994 (delq nil (append org-file-tags (nth 0 ret)))
4995 org-tag-alist
4996 (delq nil (append org-tag-alist (nth 1 ret)))
4997 org-tag-groups-alist
4998 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4999 (and ext-setup-or-nil
5000 (string-match re ext-setup-or-nil start)
5001 (setq start (match-end 0)))
5002 (and (setq ext-setup-or-nil nil start 0)
5003 (re-search-forward re nil t)))
5004 (setq key (upcase (match-string 1 ext-setup-or-nil))
5005 value (org-match-string-no-properties 2 ext-setup-or-nil))
5006 (if (stringp value) (setq value (org-trim value)))
5007 (cond
5008 ((equal key "CATEGORY")
5009 (setq cat value))
5010 ((member key '("SEQ_TODO" "TODO"))
5011 (push (cons 'sequence (org-split-string value splitre)) kwds))
5012 ((equal key "TYP_TODO")
5013 (push (cons 'type (org-split-string value splitre)) kwds))
5014 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
5015 ;; general TODO-like setup
5016 (push (cons (intern (downcase (match-string 1 key)))
5017 (org-split-string value splitre)) kwds))
5018 ((equal key "COLUMNS")
5019 (org-set-local 'org-columns-default-format value))
5020 ((equal key "LINK")
5021 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5022 (push (cons (match-string 1 value)
5023 (org-trim (match-string 2 value)))
5024 links)))
5025 ((equal key "PRIORITIES")
5026 (setq prio (org-split-string value " +")))
5027 ((equal key "PROPERTY")
5028 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5029 (setq props (org-update-property-plist (match-string 1 value)
5030 (match-string 2 value)
5031 props))))
5032 ((equal key "CONSTANTS")
5033 (org-table-set-constants))
5034 ((equal key "STARTUP")
5035 (let ((opts (org-split-string value splitre))
5036 l var val)
5037 (while (setq l (pop opts))
5038 (when (setq l (assoc l org-startup-options))
5039 (setq var (nth 1 l) val (nth 2 l))
5040 (if (not (nth 3 l))
5041 (set (make-local-variable var) val)
5042 (if (not (listp (symbol-value var)))
5043 (set (make-local-variable var) nil))
5044 (set (make-local-variable var) (symbol-value var))
5045 (add-to-list var val))))))
5046 ((equal key "ARCHIVE")
5047 (setq arch value)
5048 (remove-text-properties 0 (length arch)
5049 '(face t fontified t) arch))
5050 ((equal key "OPTIONS")
5051 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5052 (setq scripts (read (match-string 2 value)))))
5053 ((and (equal key "SETUPFILE")
5054 ;; Prevent checking in Gnus messages
5055 (not buffer-read-only))
5056 (setq setup-contents (org-file-contents
5057 (expand-file-name
5058 (org-remove-double-quotes value))
5059 'noerror))
5060 (if (not ext-setup-or-nil)
5061 (setq ext-setup-or-nil setup-contents start 0)
5062 (setq ext-setup-or-nil
5063 (concat (substring ext-setup-or-nil 0 start)
5064 "\n" setup-contents "\n"
5065 (substring ext-setup-or-nil start)))))))
5066 ;; search for property blocks
5067 (goto-char (point-min))
5068 (while (re-search-forward org-block-regexp nil t)
5069 (when (equal "PROPERTY" (upcase (match-string 1)))
5070 (setq value (replace-regexp-in-string
5071 "[\n\r]" " " (match-string 4)))
5072 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5073 (setq props (org-update-property-plist (match-string 1 value)
5074 (match-string 2 value)
5075 props)))))))
5076 (org-set-local 'org-use-sub-superscripts scripts)
5077 (when cat
5078 (org-set-local 'org-category (intern cat))
5079 (push (cons "CATEGORY" cat) props))
5080 (when prio
5081 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5082 (setq prio (mapcar 'string-to-char prio))
5083 (org-set-local 'org-highest-priority (nth 0 prio))
5084 (org-set-local 'org-lowest-priority (nth 1 prio))
5085 (org-set-local 'org-default-priority (nth 2 prio)))
5086 (and props (org-set-local 'org-file-properties (nreverse props)))
5087 (and arch (org-set-local 'org-archive-location arch))
5088 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5089 ;; Process the TODO keywords
5090 (unless kwds
5091 ;; Use the global values as if they had been given locally.
5092 (setq kwds (default-value 'org-todo-keywords))
5093 (if (stringp (car kwds))
5094 (setq kwds (list (cons org-todo-interpretation
5095 (default-value 'org-todo-keywords)))))
5096 (setq kwds (reverse kwds)))
5097 (setq kwds (nreverse kwds))
5098 (let (inter kws kw)
5099 (while (setq kws (pop kwds))
5100 (let ((kws (or
5101 (run-hook-with-args-until-success
5102 'org-todo-setup-filter-hook kws)
5103 kws)))
5104 (setq inter (pop kws) sep (member "|" kws)
5105 kws0 (delete "|" (copy-sequence kws))
5106 kwsa nil
5107 kws1 (mapcar
5108 (lambda (x)
5109 ;; 1 2
5110 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5111 (progn
5112 (setq kw (match-string 1 x)
5113 key (and (match-end 2) (match-string 2 x))
5114 log (org-extract-log-state-settings x))
5115 (push (cons kw (and key (string-to-char key))) kwsa)
5116 (and log (push log org-todo-log-states))
5118 (error "Invalid TODO keyword %s" x)))
5119 kws0)
5120 kwsa (if kwsa (append '((:startgroup))
5121 (nreverse kwsa)
5122 '((:endgroup))))
5123 hw (car kws1)
5124 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5125 tail (list inter hw (car dws) (org-last dws))))
5126 (add-to-list 'org-todo-heads hw 'append)
5127 (push kws1 org-todo-sets)
5128 (setq org-done-keywords (append org-done-keywords dws nil))
5129 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5130 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5131 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5132 (setq org-todo-sets (nreverse org-todo-sets)
5133 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5134 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5135 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5136 ;; Compute the regular expressions and other local variables.
5137 ;; Using `org-outline-regexp-bol' would complicate them much,
5138 ;; because of the fixed white space at the end of that string.
5139 (if (not org-done-keywords)
5140 (setq org-done-keywords (and org-todo-keywords-1
5141 (list (org-last org-todo-keywords-1)))))
5142 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5143 (length org-scheduled-string)
5144 (length org-clock-string)
5145 (length org-closed-string)))
5146 org-not-done-keywords
5147 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5148 org-todo-regexp
5149 (concat "\\("
5150 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5151 "\\)")
5152 org-not-done-regexp
5153 (concat "\\("
5154 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5155 "\\)")
5156 org-not-done-heading-regexp
5157 (format org-heading-keyword-regexp-format org-not-done-regexp)
5158 org-todo-line-regexp
5159 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5160 org-complex-heading-regexp
5161 (concat "^\\(\\*+\\)"
5162 "\\(?: +" org-todo-regexp "\\)?"
5163 "\\(?: +\\(\\[#.\\]\\)\\)?"
5164 "\\(?: +\\(.*?\\)\\)??"
5165 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5166 "[ \t]*$")
5167 org-complex-heading-regexp-format
5168 (concat "^\\(\\*+\\)"
5169 "\\(?: +" org-todo-regexp "\\)?"
5170 "\\(?: +\\(\\[#.\\]\\)\\)?"
5171 "\\(?: +"
5172 ;; Stats cookies can be stuck to body.
5173 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5174 "\\(%s\\)"
5175 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5176 "\\)"
5177 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5178 "[ \t]*$")
5179 org-todo-line-tags-regexp
5180 (concat "^\\(\\*+\\)"
5181 "\\(?: +" org-todo-regexp "\\)?"
5182 "\\(?: +\\(.*?\\)\\)??"
5183 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5184 "[ \t]*$")
5185 org-deadline-regexp (concat "\\<" org-deadline-string)
5186 org-deadline-time-regexp
5187 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5188 org-deadline-time-hour-regexp
5189 (concat "\\<" org-deadline-string
5190 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5191 org-deadline-line-regexp
5192 (concat "\\<\\(" org-deadline-string "\\).*")
5193 org-scheduled-regexp
5194 (concat "\\<" org-scheduled-string)
5195 org-scheduled-time-regexp
5196 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5197 org-scheduled-time-hour-regexp
5198 (concat "\\<" org-scheduled-string
5199 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5200 org-closed-time-regexp
5201 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5202 org-keyword-time-regexp
5203 (concat "\\<\\(" org-scheduled-string
5204 "\\|" org-deadline-string
5205 "\\|" org-closed-string
5206 "\\|" org-clock-string "\\)"
5207 " *[[<]\\([^]>]+\\)[]>]")
5208 org-keyword-time-not-clock-regexp
5209 (concat "\\<\\(" org-scheduled-string
5210 "\\|" org-deadline-string
5211 "\\|" org-closed-string
5212 "\\)"
5213 " *[[<]\\([^]>]+\\)[]>]")
5214 org-maybe-keyword-time-regexp
5215 (concat "\\(\\<\\(" org-scheduled-string
5216 "\\|" org-deadline-string
5217 "\\|" org-closed-string
5218 "\\|" org-clock-string "\\)\\)?"
5219 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5220 org-all-time-keywords
5221 (mapcar (lambda (w) (substring w 0 -1))
5222 (list org-scheduled-string org-deadline-string
5223 org-clock-string org-closed-string)))
5224 (setq org-ota nil)
5225 (org-compute-latex-and-related-regexp))))
5227 (defun org-file-contents (file &optional noerror)
5228 "Return the contents of FILE, as a string."
5229 (if (or (not file)
5230 (not (file-readable-p file)))
5231 (if noerror
5232 (message "Cannot read file \"%s\"" file)
5233 (error "Cannot read file \"%s\"" file))
5234 (with-temp-buffer
5235 (insert-file-contents file)
5236 (buffer-string))))
5238 (defun org-extract-log-state-settings (x)
5239 "Extract the log state setting from a TODO keyword string.
5240 This will extract info from a string like \"WAIT(w@/!)\"."
5241 (let (kw key log1 log2)
5242 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5243 (setq kw (match-string 1 x)
5244 key (and (match-end 2) (match-string 2 x))
5245 log1 (and (match-end 3) (match-string 3 x))
5246 log2 (and (match-end 4) (match-string 4 x)))
5247 (and (or log1 log2)
5248 (list kw
5249 (and log1 (if (equal log1 "!") 'time 'note))
5250 (and log2 (if (equal log2 "!") 'time 'note)))))))
5252 (defun org-remove-keyword-keys (list)
5253 "Remove a pair of parenthesis at the end of each string in LIST."
5254 (mapcar (lambda (x)
5255 (if (string-match "(.*)$" x)
5256 (substring x 0 (match-beginning 0))
5258 list))
5260 (defun org-assign-fast-keys (alist)
5261 "Assign fast keys to a keyword-key alist.
5262 Respect keys that are already there."
5263 (let (new e (alt ?0))
5264 (while (setq e (pop alist))
5265 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5266 (cdr e)) ;; Key already assigned.
5267 (push e new)
5268 (let ((clist (string-to-list (downcase (car e))))
5269 (used (append new alist)))
5270 (when (= (car clist) ?@)
5271 (pop clist))
5272 (while (and clist (rassoc (car clist) used))
5273 (pop clist))
5274 (unless clist
5275 (while (rassoc alt used)
5276 (incf alt)))
5277 (push (cons (car e) (or (car clist) alt)) new))))
5278 (nreverse new)))
5280 ;;; Some variables used in various places
5282 (defvar org-window-configuration nil
5283 "Used in various places to store a window configuration.")
5284 (defvar org-selected-window nil
5285 "Used in various places to store a window configuration.")
5286 (defvar org-finish-function nil
5287 "Function to be called when `C-c C-c' is used.
5288 This is for getting out of special buffers like capture.")
5291 ;; FIXME: Occasionally check by commenting these, to make sure
5292 ;; no other functions uses these, forgetting to let-bind them.
5293 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5294 (defvar org-last-state)
5295 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5297 ;; Defined somewhere in this file, but used before definition.
5298 (defvar org-entities) ;; defined in org-entities.el
5299 (defvar org-struct-menu)
5300 (defvar org-org-menu)
5301 (defvar org-tbl-menu)
5303 ;;;; Define the Org-mode
5305 ;; We use a before-change function to check if a table might need
5306 ;; an update.
5307 (defvar org-table-may-need-update t
5308 "Indicates that a table might need an update.
5309 This variable is set by `org-before-change-function'.
5310 `org-table-align' sets it back to nil.")
5311 (defun org-before-change-function (beg end)
5312 "Every change indicates that a table might need an update."
5313 (setq org-table-may-need-update t))
5314 (defvar org-mode-map)
5315 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5316 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5317 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5318 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5319 (defvar org-table-buffer-is-an nil)
5321 (defvar bidi-paragraph-direction)
5322 (defvar buffer-face-mode-face)
5324 (require 'outline)
5325 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5326 (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"))
5327 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5329 ;; Other stuff we need.
5330 (require 'time-date)
5331 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5332 (require 'easymenu)
5333 (require 'overlay)
5335 ;; (require 'org-macs) moved higher up in the file before it is first used
5336 (require 'org-entities)
5337 ;; (require 'org-compat) moved higher up in the file before it is first used
5338 (require 'org-faces)
5339 (require 'org-list)
5340 (require 'org-pcomplete)
5341 (require 'org-src)
5342 (require 'org-footnote)
5343 (require 'org-macro)
5345 ;; babel
5346 (require 'ob)
5348 ;;;###autoload
5349 (define-derived-mode org-mode outline-mode "Org"
5350 "Outline-based notes management and organizer, alias
5351 \"Carsten's outline-mode for keeping track of everything.\"
5353 Org-mode develops organizational tasks around a NOTES file which
5354 contains information about projects as plain text. Org-mode is
5355 implemented on top of outline-mode, which is ideal to keep the content
5356 of large files well structured. It supports ToDo items, deadlines and
5357 time stamps, which magically appear in the diary listing of the Emacs
5358 calendar. Tables are easily created with a built-in table editor.
5359 Plain text URL-like links connect to websites, emails (VM), Usenet
5360 messages (Gnus), BBDB entries, and any files related to the project.
5361 For printing and sharing of notes, an Org-mode file (or a part of it)
5362 can be exported as a structured ASCII or HTML file.
5364 The following commands are available:
5366 \\{org-mode-map}"
5368 ;; Get rid of Outline menus, they are not needed
5369 ;; Need to do this here because define-derived-mode sets up
5370 ;; the keymap so late. Still, it is a waste to call this each time
5371 ;; we switch another buffer into org-mode.
5372 (if (featurep 'xemacs)
5373 (when (boundp 'outline-mode-menu-heading)
5374 ;; Assume this is Greg's port, it uses easymenu
5375 (easy-menu-remove outline-mode-menu-heading)
5376 (easy-menu-remove outline-mode-menu-show)
5377 (easy-menu-remove outline-mode-menu-hide))
5378 (define-key org-mode-map [menu-bar headings] 'undefined)
5379 (define-key org-mode-map [menu-bar hide] 'undefined)
5380 (define-key org-mode-map [menu-bar show] 'undefined))
5382 (org-load-modules-maybe)
5383 (easy-menu-add org-org-menu)
5384 (easy-menu-add org-tbl-menu)
5385 (org-install-agenda-files-menu)
5386 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5387 (add-to-invisibility-spec '(org-cwidth))
5388 (add-to-invisibility-spec '(org-hide-block . t))
5389 (when (featurep 'xemacs)
5390 (org-set-local 'line-move-ignore-invisible t))
5391 (org-set-local 'outline-regexp org-outline-regexp)
5392 (org-set-local 'outline-level 'org-outline-level)
5393 (setq bidi-paragraph-direction 'left-to-right)
5394 (when (and org-ellipsis
5395 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5396 (fboundp 'make-glyph-code))
5397 (unless org-display-table
5398 (setq org-display-table (make-display-table)))
5399 (set-display-table-slot
5400 org-display-table 4
5401 (vconcat (mapcar
5402 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5403 org-ellipsis)))
5404 (if (stringp org-ellipsis) org-ellipsis "..."))))
5405 (setq buffer-display-table org-display-table))
5406 (org-set-regexps-and-options-for-tags)
5407 (org-set-regexps-and-options)
5408 (org-set-font-lock-defaults)
5409 (when (and org-tag-faces (not org-tags-special-faces-re))
5410 ;; tag faces set outside customize.... force initialization.
5411 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5412 ;; Calc embedded
5413 (org-set-local 'calc-embedded-open-mode "# ")
5414 ;; Modify a few syntax entries
5415 (modify-syntax-entry ?@ "w")
5416 (modify-syntax-entry ?\" "\"")
5417 (if org-startup-truncated (setq truncate-lines t))
5418 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5419 (org-set-local 'font-lock-unfontify-region-function
5420 'org-unfontify-region)
5421 ;; Activate before-change-function
5422 (org-set-local 'org-table-may-need-update t)
5423 (org-add-hook 'before-change-functions 'org-before-change-function nil
5424 'local)
5425 ;; Check for running clock before killing a buffer
5426 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5427 ;; Initialize macros templates.
5428 (org-macro-initialize-templates)
5429 ;; Initialize radio targets.
5430 (org-update-radio-target-regexp)
5431 ;; Indentation.
5432 (org-set-local 'indent-line-function 'org-indent-line)
5433 (org-set-local 'indent-region-function 'org-indent-region)
5434 ;; Filling and auto-filling.
5435 (org-setup-filling)
5436 ;; Comments.
5437 (org-setup-comments-handling)
5438 ;; Initialize cache.
5439 (org-element-cache-reset)
5440 ;; Beginning/end of defun
5441 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5442 (org-set-local 'end-of-defun-function 'org-forward-element)
5443 ;; Next error for sparse trees
5444 (org-set-local 'next-error-function 'org-occur-next-match)
5445 ;; Make sure dependence stuff works reliably, even for users who set it
5446 ;; too late :-(
5447 (if org-enforce-todo-dependencies
5448 (add-hook 'org-blocker-hook
5449 'org-block-todo-from-children-or-siblings-or-parent)
5450 (remove-hook 'org-blocker-hook
5451 'org-block-todo-from-children-or-siblings-or-parent))
5452 (if org-enforce-todo-checkbox-dependencies
5453 (add-hook 'org-blocker-hook
5454 'org-block-todo-from-checkboxes)
5455 (remove-hook 'org-blocker-hook
5456 'org-block-todo-from-checkboxes))
5458 ;; Align options lines
5459 (org-set-local
5460 'align-mode-rules-list
5461 '((org-in-buffer-settings
5462 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5463 (modes . '(org-mode)))))
5465 ;; Imenu
5466 (org-set-local 'imenu-create-index-function
5467 'org-imenu-get-tree)
5469 ;; Make isearch reveal context
5470 (if (or (featurep 'xemacs)
5471 (not (boundp 'outline-isearch-open-invisible-function)))
5472 ;; Emacs 21 and XEmacs make use of the hook
5473 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5474 ;; Emacs 22 deals with this through a special variable
5475 (org-set-local 'outline-isearch-open-invisible-function
5476 (lambda (&rest ignore) (org-show-context 'isearch)))
5477 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5479 ;; Setup the pcomplete hooks
5480 (set (make-local-variable 'pcomplete-command-completion-function)
5481 'org-pcomplete-initial)
5482 (set (make-local-variable 'pcomplete-command-name-function)
5483 'org-command-at-point)
5484 (set (make-local-variable 'pcomplete-default-completion-function)
5485 'ignore)
5486 (set (make-local-variable 'pcomplete-parse-arguments-function)
5487 'org-parse-arguments)
5488 (set (make-local-variable 'pcomplete-termination-string) "")
5489 (when (>= emacs-major-version 23)
5490 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5492 ;; If empty file that did not turn on org-mode automatically, make it to.
5493 (if (and org-insert-mode-line-in-empty-file
5494 (org-called-interactively-p 'any)
5495 (= (point-min) (point-max)))
5496 (insert "# -*- mode: org -*-\n\n"))
5497 (unless org-inhibit-startup
5498 (org-unmodified
5499 (and org-startup-with-beamer-mode (org-beamer-mode))
5500 (when org-startup-align-all-tables
5501 (org-table-map-tables 'org-table-align 'quietly))
5502 (when org-startup-with-inline-images
5503 (org-display-inline-images))
5504 (when org-startup-with-latex-preview
5505 (org-preview-latex-fragment))
5506 (unless org-inhibit-startup-visibility-stuff
5507 (org-set-startup-visibility))))
5508 ;; Try to set org-hide correctly
5509 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5511 ;; Update `customize-package-emacs-version-alist'
5512 (add-to-list 'customize-package-emacs-version-alist
5513 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5514 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5515 ("8.2.6" . "24.4")))
5517 (defvar org-mode-transpose-word-syntax-table
5518 (let ((st (make-syntax-table)))
5519 (mapc (lambda(c) (modify-syntax-entry
5520 (string-to-char (car c)) "w p" st))
5521 org-emphasis-alist)
5522 st))
5524 (when (fboundp 'abbrev-table-put)
5525 (abbrev-table-put org-mode-abbrev-table
5526 :parents (list text-mode-abbrev-table)))
5528 (defsubst org-fix-ellipsis-at-bol ()
5529 (save-excursion (goto-char (window-start)) (recenter 0)))
5531 (defun org-find-invisible-foreground ()
5532 (let ((candidates (remove
5533 "unspecified-bg"
5534 (nconc
5535 (list (face-background 'default)
5536 (face-background 'org-default))
5537 (mapcar
5538 (lambda (alist)
5539 (when (boundp alist)
5540 (cdr (assoc 'background-color (symbol-value alist)))))
5541 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5542 (list (face-foreground 'org-hide))))))
5543 (car (remove nil candidates))))
5545 (defun org-current-time (&optional rounding-minutes past)
5546 "Current time, possibly rounded to ROUNDING-MINUTES.
5547 When ROUNDING-MINUTES is not an integer, fall back on the car of
5548 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5549 the rounding returns a past time."
5550 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5551 (car org-time-stamp-rounding-minutes)))
5552 (time (decode-time)) res)
5553 (if (< r 1)
5554 (current-time)
5555 (setq res
5556 (apply 'encode-time
5557 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5558 (nthcdr 2 time))))
5559 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5560 (seconds-to-time (- (org-float-time res) (* r 60)))
5561 res))))
5563 (defun org-today ()
5564 "Return today date, considering `org-extend-today-until'."
5565 (time-to-days
5566 (time-subtract (current-time)
5567 (list 0 (* 3600 org-extend-today-until) 0))))
5569 ;;;; Font-Lock stuff, including the activators
5571 (defvar org-mouse-map (make-sparse-keymap))
5572 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5573 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5574 (when org-mouse-1-follows-link
5575 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5576 (when org-tab-follows-link
5577 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5578 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5580 (require 'font-lock)
5582 (defconst org-non-link-chars "]\t\n\r<>")
5583 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5584 "shell" "elisp" "doi" "message"))
5585 (defvar org-link-types-re nil
5586 "Matches a link that has a url-like prefix like \"http:\"")
5587 (defvar org-link-re-with-space nil
5588 "Matches a link with spaces, optional angular brackets around it.")
5589 (defvar org-link-re-with-space2 nil
5590 "Matches a link with spaces, optional angular brackets around it.")
5591 (defvar org-link-re-with-space3 nil
5592 "Matches a link with spaces, only for internal part in bracket links.")
5593 (defvar org-angle-link-re nil
5594 "Matches link with angular brackets, spaces are allowed.")
5595 (defvar org-plain-link-re nil
5596 "Matches plain link, without spaces.")
5597 (defvar org-bracket-link-regexp nil
5598 "Matches a link in double brackets.")
5599 (defvar org-bracket-link-analytic-regexp nil
5600 "Regular expression used to analyze links.
5601 Here is what the match groups contain after a match:
5602 1: http:
5603 2: http
5604 3: path
5605 4: [desc]
5606 5: desc")
5607 (defvar org-bracket-link-analytic-regexp++ nil
5608 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5609 (defvar org-any-link-re nil
5610 "Regular expression matching any link.")
5612 (defconst org-match-sexp-depth 3
5613 "Number of stacked braces for sub/superscript matching.")
5615 (defun org-create-multibrace-regexp (left right n)
5616 "Create a regular expression which will match a balanced sexp.
5617 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5618 as single character strings.
5619 The regexp returned will match the entire expression including the
5620 delimiters. It will also define a single group which contains the
5621 match except for the outermost delimiters. The maximum depth of
5622 stacked delimiters is N. Escaping delimiters is not possible."
5623 (let* ((nothing (concat "[^" left right "]*?"))
5624 (or "\\|")
5625 (re nothing)
5626 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5627 (while (> n 1)
5628 (setq n (1- n)
5629 re (concat re or next)
5630 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5631 (concat left "\\(" re "\\)" right)))
5633 (defconst org-match-substring-regexp
5634 (concat
5635 "\\(\\S-\\)\\([_^]\\)\\("
5636 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5637 "\\|"
5638 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5639 "\\|"
5640 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5641 "The regular expression matching a sub- or superscript.")
5643 (defconst org-match-substring-with-braces-regexp
5644 (concat
5645 "\\(\\S-\\)\\([_^]\\)"
5646 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5647 "The regular expression matching a sub- or superscript, forcing braces.")
5649 (defun org-make-link-regexps ()
5650 "Update the link regular expressions.
5651 This should be called after the variable `org-link-types' has changed."
5652 (setq org-link-types-re
5653 (concat
5654 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5655 org-link-re-with-space
5656 (concat
5657 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5658 "\\([^" org-non-link-chars " ]"
5659 "[^" org-non-link-chars "]*"
5660 "[^" org-non-link-chars " ]\\)>?")
5661 org-link-re-with-space2
5662 (concat
5663 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5664 "\\([^" org-non-link-chars " ]"
5665 "[^\t\n\r]*"
5666 "[^" org-non-link-chars " ]\\)>?")
5667 org-link-re-with-space3
5668 (concat
5669 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5670 "\\([^" org-non-link-chars " ]"
5671 "[^\t\n\r]*\\)")
5672 org-angle-link-re
5673 (concat
5674 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5675 "\\([^" org-non-link-chars " ]"
5676 "[^" org-non-link-chars "]*"
5677 "\\)>")
5678 org-plain-link-re
5679 (concat
5680 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5681 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5682 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5683 org-bracket-link-regexp
5684 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5685 org-bracket-link-analytic-regexp
5686 (concat
5687 "\\[\\["
5688 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5689 "\\([^]]+\\)"
5690 "\\]"
5691 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5692 "\\]")
5693 org-bracket-link-analytic-regexp++
5694 (concat
5695 "\\[\\["
5696 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5697 "\\([^]]+\\)"
5698 "\\]"
5699 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5700 "\\]")
5701 org-any-link-re
5702 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5703 org-angle-link-re "\\)\\|\\("
5704 org-plain-link-re "\\)")))
5706 (org-make-link-regexps)
5708 (defvar org-emph-face nil)
5710 (defun org-do-emphasis-faces (limit)
5711 "Run through the buffer and add overlays to emphasized strings."
5712 (let (rtn a)
5713 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5714 (if (not (= (char-after (match-beginning 3))
5715 (char-after (match-beginning 4))))
5716 (progn
5717 (setq rtn t)
5718 (setq a (assoc (match-string 3) org-emphasis-alist))
5719 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5720 'face
5721 (nth 1 a))
5722 (and (nth 2 a)
5723 (org-remove-flyspell-overlays-in
5724 (match-beginning 0) (match-end 0)))
5725 (add-text-properties (match-beginning 2) (match-end 2)
5726 '(font-lock-multiline t org-emphasis t))
5727 (when org-hide-emphasis-markers
5728 (add-text-properties (match-end 4) (match-beginning 5)
5729 '(invisible org-link))
5730 (add-text-properties (match-beginning 3) (match-end 3)
5731 '(invisible org-link)))))
5732 (goto-char (1+ (match-beginning 0))))
5733 rtn))
5735 (defun org-emphasize (&optional char)
5736 "Insert or change an emphasis, i.e. a font like bold or italic.
5737 If there is an active region, change that region to a new emphasis.
5738 If there is no region, just insert the marker characters and position
5739 the cursor between them.
5740 CHAR should be the marker character. If it is a space, it means to
5741 remove the emphasis of the selected region.
5742 If CHAR is not given (for example in an interactive call) it will be
5743 prompted for."
5744 (interactive)
5745 (let ((erc org-emphasis-regexp-components)
5746 (prompt "")
5747 (string "") beg end move c s)
5748 (if (org-region-active-p)
5749 (setq beg (region-beginning) end (region-end)
5750 string (buffer-substring beg end))
5751 (setq move t))
5753 (unless char
5754 (message "Emphasis marker or tag: [%s]"
5755 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5756 (setq char (read-char-exclusive)))
5757 (if (equal char ?\ )
5758 (setq s "" move nil)
5759 (unless (assoc (char-to-string char) org-emphasis-alist)
5760 (user-error "No such emphasis marker: \"%c\"" char))
5761 (setq s (char-to-string char)))
5762 (while (and (> (length string) 1)
5763 (equal (substring string 0 1) (substring string -1))
5764 (assoc (substring string 0 1) org-emphasis-alist))
5765 (setq string (substring string 1 -1)))
5766 (setq string (concat s string s))
5767 (if beg (delete-region beg end))
5768 (unless (or (bolp)
5769 (string-match (concat "[" (nth 0 erc) "\n]")
5770 (char-to-string (char-before (point)))))
5771 (insert " "))
5772 (unless (or (eobp)
5773 (string-match (concat "[" (nth 1 erc) "\n]")
5774 (char-to-string (char-after (point)))))
5775 (insert " ") (backward-char 1))
5776 (insert string)
5777 (and move (backward-char 1))))
5779 (defconst org-nonsticky-props
5780 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5782 (defsubst org-rear-nonsticky-at (pos)
5783 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5785 (defun org-activate-plain-links (limit)
5786 "Run through the buffer and add overlays to links."
5787 (let (f hl)
5788 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5789 (not (org-in-src-block-p)))
5790 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5791 (setq f (get-text-property (match-beginning 0) 'face))
5792 (setq hl (org-match-string-no-properties 0))
5793 (if (or (eq f 'org-tag)
5794 (and (listp f) (memq 'org-tag f)))
5796 (add-text-properties (match-beginning 0) (match-end 0)
5797 (list 'mouse-face 'highlight
5798 'face 'org-link
5799 'htmlize-link `(:uri ,hl)
5800 'keymap org-mouse-map))
5801 (org-rear-nonsticky-at (match-end 0)))
5802 t)))
5804 (defun org-activate-code (limit)
5805 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5806 (progn
5807 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5808 (remove-text-properties (match-beginning 0) (match-end 0)
5809 '(display t invisible t intangible t))
5810 t)))
5812 (defcustom org-src-fontify-natively t
5813 "When non-nil, fontify code in code blocks."
5814 :type 'boolean
5815 :version "24.4"
5816 :package-version '(Org . "8.3")
5817 :group 'org-appearance
5818 :group 'org-babel)
5820 (defcustom org-allow-promoting-top-level-subtree nil
5821 "When non-nil, allow promoting a top level subtree.
5822 The leading star of the top level headline will be replaced
5823 by a #."
5824 :type 'boolean
5825 :version "24.1"
5826 :group 'org-appearance)
5828 (defun org-fontify-meta-lines-and-blocks (limit)
5829 (condition-case nil
5830 (org-fontify-meta-lines-and-blocks-1 limit)
5831 (error (message "org-mode fontification error"))))
5833 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5834 "Fontify #+ lines and blocks."
5835 (let ((case-fold-search t))
5836 (if (re-search-forward
5837 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5838 limit t)
5839 (let ((beg (match-beginning 0))
5840 (block-start (match-end 0))
5841 (block-end nil)
5842 (lang (match-string 7))
5843 (beg1 (line-beginning-position 2))
5844 (dc1 (downcase (match-string 2)))
5845 (dc3 (downcase (match-string 3)))
5846 end end1 quoting block-type ovl)
5847 (cond
5848 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5849 ;; a single line of backend-specific content
5850 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5851 (remove-text-properties (match-beginning 0) (match-end 0)
5852 '(display t invisible t intangible t))
5853 (add-text-properties (match-beginning 1) (match-end 3)
5854 '(font-lock-fontified t face org-meta-line))
5855 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5856 '(font-lock-fontified t face org-block))
5857 ; for backend-specific code
5859 ((and (match-end 4) (equal dc3 "+begin"))
5860 ;; Truly a block
5861 (setq block-type (downcase (match-string 5))
5862 quoting (member block-type org-protecting-blocks))
5863 (when (re-search-forward
5864 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5865 nil t) ;; on purpose, we look further than LIMIT
5866 (setq end (min (point-max) (match-end 0))
5867 end1 (min (point-max) (1- (match-beginning 0))))
5868 (setq block-end (match-beginning 0))
5869 (when quoting
5870 (org-remove-flyspell-overlays-in beg1 end1)
5871 (remove-text-properties beg end
5872 '(display t invisible t intangible t)))
5873 (add-text-properties
5874 beg end '(font-lock-fontified t font-lock-multiline t))
5875 (add-text-properties beg beg1 '(face org-meta-line))
5876 (org-remove-flyspell-overlays-in beg beg1)
5877 (add-text-properties ; For end_src
5878 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5879 (org-remove-flyspell-overlays-in end1 end)
5880 (cond
5881 ((and lang (not (string= lang "")) org-src-fontify-natively)
5882 (org-src-font-lock-fontify-block lang block-start block-end)
5883 ;; remove old background overlays
5884 (mapc (lambda (ov)
5885 (if (eq (overlay-get ov 'face) 'org-block-background)
5886 (delete-overlay ov)))
5887 (overlays-at (/ (+ beg1 block-end) 2)))
5888 ;; add a background overlay
5889 (setq ovl (make-overlay beg1 block-end))
5890 (overlay-put ovl 'face 'org-block-background)
5891 (overlay-put ovl 'evaporate t)) ; make it go away when empty
5892 (quoting
5893 (add-text-properties beg1 (min (point-max) (1+ end1))
5894 '(face org-block))) ; end of source block
5895 ((not org-fontify-quote-and-verse-blocks))
5896 ((string= block-type "quote")
5897 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5898 ((string= block-type "verse")
5899 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5900 (add-text-properties beg beg1 '(face org-block-begin-line))
5901 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5902 '(face org-block-end-line))
5904 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5905 (org-remove-flyspell-overlays-in
5906 (match-beginning 0)
5907 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5908 (add-text-properties
5909 beg (match-end 3)
5910 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5911 '(font-lock-fontified t invisible t)
5912 '(font-lock-fontified t face org-document-info-keyword)))
5913 (add-text-properties
5914 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5915 (if (string-equal dc1 "+title:")
5916 '(font-lock-fontified t face org-document-title)
5917 '(font-lock-fontified t face org-document-info))))
5918 ((or (equal dc1 "+results")
5919 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5920 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5921 "+call:" "+header:" "+headers:" "+name:"))
5922 (and (match-end 4) (equal dc3 "+attr")))
5923 (org-remove-flyspell-overlays-in
5924 (match-beginning 0)
5925 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5926 (add-text-properties
5927 beg (match-end 0)
5928 '(font-lock-fontified t face org-meta-line))
5930 ((member dc3 '(" " ""))
5931 (org-remove-flyspell-overlays-in beg (match-end 0))
5932 (add-text-properties
5933 beg (match-end 0)
5934 '(font-lock-fontified t face font-lock-comment-face)))
5935 ((not (member (char-after beg) '(?\ ?\t)))
5936 ;; just any other in-buffer setting, but not indented
5937 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5938 (add-text-properties
5939 beg (match-end 0)
5940 '(font-lock-fontified t face org-meta-line))
5942 (t nil))))))
5944 (defun org-fontify-drawers (limit)
5945 "Fontify drawers."
5946 (when (re-search-forward org-drawer-regexp limit t)
5947 (add-text-properties
5948 (match-beginning 0) (match-end 0)
5949 '(font-lock-fontified t face org-special-keyword))
5950 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5953 (defun org-activate-angle-links (limit)
5954 "Run through the buffer and add overlays to links."
5955 (if (and (re-search-forward org-angle-link-re limit t)
5956 (not (org-in-src-block-p)))
5957 (progn
5958 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5959 (add-text-properties (match-beginning 0) (match-end 0)
5960 (list 'mouse-face 'highlight
5961 'keymap org-mouse-map))
5962 (org-rear-nonsticky-at (match-end 0))
5963 t)))
5965 (defun org-activate-footnote-links (limit)
5966 "Run through the buffer and add overlays to footnotes."
5967 (let ((fn (org-footnote-next-reference-or-definition limit)))
5968 (when fn
5969 (let* ((beg (nth 1 fn))
5970 (end (nth 2 fn))
5971 (label (car fn))
5972 (referencep (/= (line-beginning-position) beg)))
5973 (when (and referencep (nth 3 fn))
5974 (save-excursion
5975 (goto-char beg)
5976 (search-forward (or label "fn:"))
5977 (org-remove-flyspell-overlays-in beg (match-end 0))))
5978 (add-text-properties beg end
5979 (list 'mouse-face 'highlight
5980 'keymap org-mouse-map
5981 'help-echo
5982 (if referencep "Footnote reference"
5983 "Footnote definition")
5984 'font-lock-fontified t
5985 'font-lock-multiline t
5986 'face 'org-footnote))))))
5988 (defun org-activate-bracket-links (limit)
5989 "Run through the buffer and add overlays to bracketed links."
5990 (if (and (re-search-forward org-bracket-link-regexp limit t)
5991 (not (org-in-src-block-p)))
5992 (let* ((hl (org-match-string-no-properties 1))
5993 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5994 (ip (org-maybe-intangible
5995 (list 'invisible 'org-link
5996 'keymap org-mouse-map 'mouse-face 'highlight
5997 'font-lock-multiline t 'help-echo help
5998 'htmlize-link `(:uri ,hl))))
5999 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6000 'font-lock-multiline t 'help-echo help
6001 'htmlize-link `(:uri ,hl))))
6002 ;; We need to remove the invisible property here. Table narrowing
6003 ;; may have made some of this invisible.
6004 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6005 (remove-text-properties (match-beginning 0) (match-end 0)
6006 '(invisible nil))
6007 (if (match-end 3)
6008 (progn
6009 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6010 (org-rear-nonsticky-at (match-beginning 3))
6011 (add-text-properties (match-beginning 3) (match-end 3) vp)
6012 (org-rear-nonsticky-at (match-end 3))
6013 (add-text-properties (match-end 3) (match-end 0) ip)
6014 (org-rear-nonsticky-at (match-end 0)))
6015 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6016 (org-rear-nonsticky-at (match-beginning 1))
6017 (add-text-properties (match-beginning 1) (match-end 1) vp)
6018 (org-rear-nonsticky-at (match-end 1))
6019 (add-text-properties (match-end 1) (match-end 0) ip)
6020 (org-rear-nonsticky-at (match-end 0)))
6021 t)))
6023 (defun org-activate-dates (limit)
6024 "Run through the buffer and add overlays to dates."
6025 (if (and (re-search-forward org-tsr-regexp-both limit t)
6026 (not (equal (char-before (match-beginning 0)) 91)))
6027 (progn
6028 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6029 (add-text-properties (match-beginning 0) (match-end 0)
6030 (list 'mouse-face 'highlight
6031 'keymap org-mouse-map))
6032 (org-rear-nonsticky-at (match-end 0))
6033 (when org-display-custom-times
6034 (if (match-end 3)
6035 (org-display-custom-time (match-beginning 3) (match-end 3)))
6036 (org-display-custom-time (match-beginning 1) (match-end 1)))
6037 t)))
6039 (defvar org-target-link-regexp nil
6040 "Regular expression matching radio targets in plain text.")
6041 (make-variable-buffer-local 'org-target-link-regexp)
6042 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
6043 "Regular expression matching a link target.")
6044 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
6045 "Regular expression matching a radio target.")
6046 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
6047 "Regular expression matching any target.")
6049 (defun org-activate-target-links (limit)
6050 "Run through the buffer and add overlays to target matches."
6051 (when org-target-link-regexp
6052 (let ((case-fold-search t))
6053 (if (re-search-forward org-target-link-regexp limit t)
6054 (progn
6055 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6056 (add-text-properties (match-beginning 0) (match-end 0)
6057 (list 'mouse-face 'highlight
6058 'keymap org-mouse-map
6059 'help-echo "Radio target link"
6060 'org-linked-text t))
6061 (org-rear-nonsticky-at (match-end 0))
6062 t)))))
6064 (defun org-update-radio-target-regexp ()
6065 "Find all radio targets in this file and update the regular expression."
6066 (interactive)
6067 (when (memq 'radio org-activate-links)
6068 (setq org-target-link-regexp
6069 (org-make-target-link-regexp (org-all-targets 'radio)))
6070 (org-restart-font-lock)))
6072 (defun org-hide-wide-columns (limit)
6073 (let (s e)
6074 (setq s (text-property-any (point) (or limit (point-max))
6075 'org-cwidth t))
6076 (when s
6077 (setq e (next-single-property-change s 'org-cwidth))
6078 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6079 (goto-char e)
6080 t)))
6082 (defvar org-latex-and-related-regexp nil
6083 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6085 (defun org-compute-latex-and-related-regexp ()
6086 "Compute regular expression for LaTeX, entities and sub/superscript.
6087 Result depends on variable `org-highlight-latex-and-related'."
6088 (org-set-local
6089 'org-latex-and-related-regexp
6090 (let* ((re-sub
6091 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6092 ((eq org-use-sub-superscripts '{})
6093 (list org-match-substring-with-braces-regexp))
6094 (org-use-sub-superscripts (list org-match-substring-regexp))))
6095 (re-latex
6096 (when (memq 'latex org-highlight-latex-and-related)
6097 (let ((matchers (plist-get org-format-latex-options :matchers)))
6098 (delq nil
6099 (mapcar (lambda (x)
6100 (and (member (car x) matchers) (nth 1 x)))
6101 org-latex-regexps)))))
6102 (re-entities
6103 (when (memq 'entities org-highlight-latex-and-related)
6104 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6105 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6107 (defun org-do-latex-and-related (limit)
6108 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6109 LIMIT bounds the search for syntax to highlight. Stop at first
6110 highlighted object, if any. Return t if some highlighting was
6111 done, nil otherwise."
6112 (when (org-string-nw-p org-latex-and-related-regexp)
6113 (catch 'found
6114 (while (re-search-forward org-latex-and-related-regexp limit t)
6115 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6116 'face))
6117 '(org-code org-verbatim underline))
6118 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6119 '(?_ ?^))
6121 0)))
6122 (font-lock-prepend-text-property
6123 (+ offset (match-beginning 0)) (match-end 0)
6124 'face 'org-latex-and-related)
6125 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6126 '(font-lock-multiline t)))
6127 (throw 'found t)))
6128 nil)))
6130 (defun org-restart-font-lock ()
6131 "Restart `font-lock-mode', to force refontification."
6132 (when (and (boundp 'font-lock-mode) font-lock-mode)
6133 (font-lock-mode -1)
6134 (font-lock-mode 1)))
6136 (defun org-all-targets (&optional radio)
6137 "Return a list of all targets in this file.
6138 When optional argument RADIO is non-nil, only find radio
6139 targets."
6140 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6141 (save-excursion
6142 (goto-char (point-min))
6143 (while (re-search-forward re nil t)
6144 ;; Make sure point is really within the object.
6145 (backward-char)
6146 (let ((obj (org-element-context)))
6147 (when (memq (org-element-type obj) '(radio-target target))
6148 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6149 rtn)))
6151 (defun org-make-target-link-regexp (targets)
6152 "Make regular expression matching all strings in TARGETS.
6153 The regular expression finds the targets also if there is a line break
6154 between words."
6155 (and targets
6156 (concat
6157 "\\<\\("
6158 (mapconcat
6159 (lambda (x)
6160 (setq x (regexp-quote x))
6161 (while (string-match " +" x)
6162 (setq x (replace-match "\\s-+" t t x)))
6164 targets
6165 "\\|")
6166 "\\)\\>")))
6168 (defun org-activate-tags (limit)
6169 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6170 (progn
6171 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6172 (add-text-properties (match-beginning 1) (match-end 1)
6173 (list 'mouse-face 'highlight
6174 'keymap org-mouse-map))
6175 (org-rear-nonsticky-at (match-end 1))
6176 t)))
6178 (defun org-outline-level ()
6179 "Compute the outline level of the heading at point.
6180 If this is called at a normal headline, the level is the number of stars.
6181 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6182 (save-excursion
6183 (if (not (condition-case nil
6184 (org-back-to-heading t)
6185 (error nil)))
6187 (looking-at org-outline-regexp)
6188 (1- (- (match-end 0) (match-beginning 0))))))
6190 (defvar org-font-lock-keywords nil)
6192 (defsubst org-re-property (property &optional literal)
6193 "Return a regexp matching a PROPERTY line.
6194 Match group 3 will be set to the value if it exists."
6195 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6196 (if literal property (regexp-quote property))
6197 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6199 (defconst org-property-re
6200 (org-re-property ".*?" 'literal)
6201 "Regular expression matching a property line.
6202 There are four matching groups:
6203 1: :PROPKEY: including the leading and trailing colon,
6204 2: PROPKEY without the leading and trailing colon,
6205 3: PROPVAL without leading or trailing spaces,
6206 4: the indentation of the current line,
6207 5: trailing whitespace.")
6209 (defvar org-font-lock-hook nil
6210 "Functions to be called for special font lock stuff.")
6212 (defvar org-font-lock-set-keywords-hook nil
6213 "Functions that can manipulate `org-font-lock-extra-keywords'.
6214 This is called after `org-font-lock-extra-keywords' is defined, but before
6215 it is installed to be used by font lock. This can be useful if something
6216 needs to be inserted at a specific position in the font-lock sequence.")
6218 (defun org-font-lock-hook (limit)
6219 "Run `org-font-lock-hook' within LIMIT."
6220 (run-hook-with-args 'org-font-lock-hook limit))
6222 (defun org-set-font-lock-defaults ()
6223 "Set font lock defaults for the current buffer."
6224 (let* ((em org-fontify-emphasized-text)
6225 (lk org-activate-links)
6226 (org-font-lock-extra-keywords
6227 (list
6228 ;; Call the hook
6229 '(org-font-lock-hook)
6230 ;; Headlines
6231 `(,(if org-fontify-whole-heading-line
6232 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6233 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6234 (1 (org-get-level-face 1))
6235 (2 (org-get-level-face 2))
6236 (3 (org-get-level-face 3)))
6237 ;; Table lines
6238 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6239 (1 'org-table t))
6240 ;; Table internals
6241 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6242 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6243 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6244 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6245 ;; Drawers
6246 '(org-fontify-drawers)
6247 ;; Properties
6248 (list org-property-re
6249 '(1 'org-special-keyword t)
6250 '(3 'org-property-value t))
6251 ;; Links
6252 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6253 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6254 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6255 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6256 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6257 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6258 (if (memq 'footnote lk) '(org-activate-footnote-links))
6259 ;; Targets.
6260 (list org-any-target-regexp '(0 'org-target t))
6261 ;; Diary sexps.
6262 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6263 ;; Macro
6264 '("{{{.+?}}}" (0 'org-macro t))
6265 '(org-hide-wide-columns (0 nil append))
6266 ;; TODO keyword
6267 (list (format org-heading-keyword-regexp-format
6268 org-todo-regexp)
6269 '(2 (org-get-todo-face 2) t))
6270 ;; DONE
6271 (if org-fontify-done-headline
6272 (list (format org-heading-keyword-regexp-format
6273 (concat
6274 "\\(?:"
6275 (mapconcat 'regexp-quote org-done-keywords "\\|")
6276 "\\)"))
6277 '(2 'org-headline-done t))
6278 nil)
6279 ;; Priorities
6280 '(org-font-lock-add-priority-faces)
6281 ;; Tags
6282 '(org-font-lock-add-tag-faces)
6283 ;; Tags groups
6284 (if (and org-group-tags org-tag-groups-alist)
6285 (list (concat org-outline-regexp-bol ".+\\(:"
6286 (regexp-opt (mapcar 'car org-tag-groups-alist))
6287 ":\\).*$")
6288 '(1 'org-tag-group prepend)))
6289 ;; Special keywords
6290 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6291 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6292 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6293 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6294 ;; Emphasis
6295 (if em
6296 (if (featurep 'xemacs)
6297 '(org-do-emphasis-faces (0 nil append))
6298 '(org-do-emphasis-faces)))
6299 ;; Checkboxes
6300 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6301 1 'org-checkbox prepend)
6302 (if (cdr (assq 'checkbox org-list-automatic-rules))
6303 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6304 (0 (org-get-checkbox-statistics-face) t)))
6305 ;; Description list items
6306 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6307 1 'org-list-dt prepend)
6308 ;; ARCHIVEd headings
6309 (list (concat
6310 org-outline-regexp-bol
6311 "\\(.*:" org-archive-tag ":.*\\)")
6312 '(1 'org-archived prepend))
6313 ;; Specials
6314 '(org-do-latex-and-related)
6315 '(org-fontify-entities)
6316 '(org-raise-scripts)
6317 ;; Code
6318 '(org-activate-code (1 'org-code t))
6319 ;; COMMENT
6320 (list (format org-heading-keyword-regexp-format
6321 (concat "\\("
6322 org-comment-string "\\|" org-quote-string
6323 "\\)"))
6324 '(2 'org-special-keyword t))
6325 ;; Blocks and meta lines
6326 '(org-fontify-meta-lines-and-blocks))))
6327 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6328 (run-hooks 'org-font-lock-set-keywords-hook)
6329 ;; Now set the full font-lock-keywords
6330 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6331 (org-set-local 'font-lock-defaults
6332 '(org-font-lock-keywords t nil nil backward-paragraph))
6333 (kill-local-variable 'font-lock-keywords) nil))
6335 (defun org-toggle-pretty-entities ()
6336 "Toggle the composition display of entities as UTF8 characters."
6337 (interactive)
6338 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6339 (org-restart-font-lock)
6340 (if org-pretty-entities
6341 (message "Entities are now displayed as UTF8 characters")
6342 (save-restriction
6343 (widen)
6344 (org-decompose-region (point-min) (point-max))
6345 (message "Entities are now displayed as plain text"))))
6347 (defvar org-custom-properties-overlays nil
6348 "List of overlays used for custom properties.")
6349 (make-variable-buffer-local 'org-custom-properties-overlays)
6351 (defun org-toggle-custom-properties-visibility ()
6352 "Display or hide properties in `org-custom-properties'."
6353 (interactive)
6354 (if org-custom-properties-overlays
6355 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6356 (setq org-custom-properties-overlays nil))
6357 (unless (not org-custom-properties)
6358 (save-excursion
6359 (save-restriction
6360 (widen)
6361 (goto-char (point-min))
6362 (while (re-search-forward org-property-re nil t)
6363 (mapc (lambda(p)
6364 (when (equal p (substring (match-string 1) 1 -1))
6365 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6366 (overlay-put o 'invisible t)
6367 (overlay-put o 'org-custom-property t)
6368 (push o org-custom-properties-overlays))))
6369 org-custom-properties)))))))
6371 (defun org-fontify-entities (limit)
6372 "Find an entity to fontify."
6373 (let (ee)
6374 (when org-pretty-entities
6375 (catch 'match
6376 (while (re-search-forward
6377 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6378 limit t)
6379 (if (and (not (org-in-indented-comment-line))
6380 (setq ee (org-entity-get (match-string 1)))
6381 (= (length (nth 6 ee)) 1))
6382 (let*
6383 ((end (if (equal (match-string 2) "{}")
6384 (match-end 2)
6385 (match-end 1))))
6386 (add-text-properties
6387 (match-beginning 0) end
6388 (list 'font-lock-fontified t))
6389 (compose-region (match-beginning 0) end
6390 (nth 6 ee) nil)
6391 (backward-char 1)
6392 (throw 'match t))))
6393 nil))))
6395 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6396 "Fontify string S like in Org-mode."
6397 (with-temp-buffer
6398 (insert s)
6399 (let ((org-odd-levels-only odd-levels))
6400 (org-mode)
6401 (font-lock-fontify-buffer)
6402 (buffer-string))))
6404 (defvar org-m nil)
6405 (defvar org-l nil)
6406 (defvar org-f nil)
6407 (defun org-get-level-face (n)
6408 "Get the right face for match N in font-lock matching of headlines."
6409 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6410 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6411 (if org-cycle-level-faces
6412 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6413 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6414 (cond
6415 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6416 ((eq n 2) org-f)
6417 (t (if org-level-color-stars-only nil org-f))))
6420 (defun org-get-todo-face (kwd)
6421 "Get the right face for a TODO keyword KWD.
6422 If KWD is a number, get the corresponding match group."
6423 (if (numberp kwd) (setq kwd (match-string kwd)))
6424 (or (org-face-from-face-or-color
6425 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6426 (and (member kwd org-done-keywords) 'org-done)
6427 'org-todo))
6429 (defun org-face-from-face-or-color (context inherit face-or-color)
6430 "Create a face list that inherits INHERIT, but sets the foreground color.
6431 When FACE-OR-COLOR is not a string, just return it."
6432 (if (stringp face-or-color)
6433 (list :inherit inherit
6434 (cdr (assoc context org-faces-easy-properties))
6435 face-or-color)
6436 face-or-color))
6438 (defun org-font-lock-add-tag-faces (limit)
6439 "Add the special tag faces."
6440 (when (and org-tag-faces org-tags-special-faces-re)
6441 (while (re-search-forward org-tags-special-faces-re limit t)
6442 (add-text-properties (match-beginning 1) (match-end 1)
6443 (list 'face (org-get-tag-face 1)
6444 'font-lock-fontified t))
6445 (backward-char 1))))
6447 (defun org-font-lock-add-priority-faces (limit)
6448 "Add the special priority faces."
6449 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6450 (when (save-match-data (org-at-heading-p))
6451 (add-text-properties
6452 (match-beginning 0) (match-end 0)
6453 (list 'face (or (org-face-from-face-or-color
6454 'priority 'org-priority
6455 (cdr (assoc (char-after (match-beginning 1))
6456 org-priority-faces)))
6457 'org-priority)
6458 'font-lock-fontified t)))))
6460 (defun org-get-tag-face (kwd)
6461 "Get the right face for a TODO keyword KWD.
6462 If KWD is a number, get the corresponding match group."
6463 (if (numberp kwd) (setq kwd (match-string kwd)))
6464 (or (org-face-from-face-or-color
6465 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6466 'org-tag))
6468 (defun org-unfontify-region (beg end &optional maybe_loudly)
6469 "Remove fontification and activation overlays from links."
6470 (font-lock-default-unfontify-region beg end)
6471 (let* ((buffer-undo-list t)
6472 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6473 (inhibit-modification-hooks t)
6474 deactivate-mark buffer-file-name buffer-file-truename)
6475 (org-decompose-region beg end)
6476 (remove-text-properties beg end
6477 '(mouse-face t keymap t org-linked-text t
6478 invisible t intangible t
6479 org-emphasis t))
6480 (org-remove-font-lock-display-properties beg end)))
6482 (defconst org-script-display '(((raise -0.3) (height 0.7))
6483 ((raise 0.3) (height 0.7))
6484 ((raise -0.5))
6485 ((raise 0.5)))
6486 "Display properties for showing superscripts and subscripts.")
6488 (defun org-remove-font-lock-display-properties (beg end)
6489 "Remove specific display properties that have been added by font lock.
6490 The will remove the raise properties that are used to show superscripts
6491 and subscripts."
6492 (let (next prop)
6493 (while (< beg end)
6494 (setq next (next-single-property-change beg 'display nil end)
6495 prop (get-text-property beg 'display))
6496 (if (member prop org-script-display)
6497 (put-text-property beg next 'display nil))
6498 (setq beg next))))
6500 (defun org-raise-scripts (limit)
6501 "Add raise properties to sub/superscripts."
6502 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6503 (if (re-search-forward
6504 (if (eq org-use-sub-superscripts t)
6505 org-match-substring-regexp
6506 org-match-substring-with-braces-regexp)
6507 limit t)
6508 (let* ((pos (point)) table-p comment-p
6509 (mpos (match-beginning 3))
6510 (emph-p (get-text-property mpos 'org-emphasis))
6511 (link-p (get-text-property mpos 'mouse-face))
6512 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6513 (goto-char (point-at-bol))
6514 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6515 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6516 (goto-char pos)
6517 ;; Handle a_b^c
6518 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6519 (if (or comment-p emph-p link-p keyw-p)
6521 (put-text-property (match-beginning 3) (match-end 0)
6522 'display
6523 (if (equal (char-after (match-beginning 2)) ?^)
6524 (nth (if table-p 3 1) org-script-display)
6525 (nth (if table-p 2 0) org-script-display)))
6526 (add-text-properties (match-beginning 2) (match-end 2)
6527 (list 'invisible t
6528 'org-dwidth t 'org-dwidth-n 1))
6529 (if (and (eq (char-after (match-beginning 3)) ?{)
6530 (eq (char-before (match-end 3)) ?}))
6531 (progn
6532 (add-text-properties
6533 (match-beginning 3) (1+ (match-beginning 3))
6534 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6535 (add-text-properties
6536 (1- (match-end 3)) (match-end 3)
6537 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6538 t)))))
6540 ;;;; Visibility cycling, including org-goto and indirect buffer
6542 ;;; Cycling
6544 (defvar org-cycle-global-status nil)
6545 (make-variable-buffer-local 'org-cycle-global-status)
6546 (put 'org-cycle-global-status 'org-state t)
6547 (defvar org-cycle-subtree-status nil)
6548 (make-variable-buffer-local 'org-cycle-subtree-status)
6549 (put 'org-cycle-subtree-status 'org-state t)
6551 (defvar org-inlinetask-min-level)
6553 (defun org-unlogged-message (&rest args)
6554 "Display a message, but avoid logging it in the *Messages* buffer."
6555 (let ((message-log-max nil))
6556 (apply 'message args)))
6558 ;;;###autoload
6559 (defun org-cycle (&optional arg)
6560 "TAB-action and visibility cycling for Org-mode.
6562 This is the command invoked in Org-mode by the TAB key. Its main purpose
6563 is outline visibility cycling, but it also invokes other actions
6564 in special contexts.
6566 - When this function is called with a prefix argument, rotate the entire
6567 buffer through 3 states (global cycling)
6568 1. OVERVIEW: Show only top-level headlines.
6569 2. CONTENTS: Show all headlines of all levels, but no body text.
6570 3. SHOW ALL: Show everything.
6571 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6572 determined by the variable `org-startup-folded', and by any VISIBILITY
6573 properties in the buffer.
6574 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6575 including any drawers.
6577 - When inside a table, re-align the table and move to the next field.
6579 - When point is at the beginning of a headline, rotate the subtree started
6580 by this line through 3 different states (local cycling)
6581 1. FOLDED: Only the main headline is shown.
6582 2. CHILDREN: The main headline and the direct children are shown.
6583 From this state, you can move to one of the children
6584 and zoom in further.
6585 3. SUBTREE: Show the entire subtree, including body text.
6586 If there is no subtree, switch directly from CHILDREN to FOLDED.
6588 - When point is at the beginning of an empty headline and the variable
6589 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6590 of the headline by demoting and promoting it to likely levels. This
6591 speeds up creation document structure by pressing TAB once or several
6592 times right after creating a new headline.
6594 - When there is a numeric prefix, go up to a heading with level ARG, do
6595 a `show-subtree' and return to the previous cursor position. If ARG
6596 is negative, go up that many levels.
6598 - When point is not at the beginning of a headline, execute the global
6599 binding for TAB, which is re-indenting the line. See the option
6600 `org-cycle-emulate-tab' for details.
6602 - Special case: if point is at the beginning of the buffer and there is
6603 no headline in line 1, this function will act as if called with prefix arg
6604 (C-u TAB, same as S-TAB) also when called without prefix arg.
6605 But only if also the variable `org-cycle-global-at-bob' is t."
6606 (interactive "P")
6607 (org-load-modules-maybe)
6608 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6609 (and org-cycle-level-after-item/entry-creation
6610 (or (org-cycle-level)
6611 (org-cycle-item-indentation))))
6612 (let* ((limit-level
6613 (or org-cycle-max-level
6614 (and (boundp 'org-inlinetask-min-level)
6615 org-inlinetask-min-level
6616 (1- org-inlinetask-min-level))))
6617 (nstars (and limit-level
6618 (if org-odd-levels-only
6619 (and limit-level (1- (* limit-level 2)))
6620 limit-level)))
6621 (org-outline-regexp
6622 (if (not (derived-mode-p 'org-mode))
6623 outline-regexp
6624 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6625 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6626 (not (looking-at org-outline-regexp))))
6627 (org-cycle-hook
6628 (if bob-special
6629 (delq 'org-optimize-window-after-visibility-change
6630 (copy-sequence org-cycle-hook))
6631 org-cycle-hook))
6632 (pos (point)))
6634 (if (or bob-special (equal arg '(4)))
6635 ;; special case: use global cycling
6636 (setq arg t))
6638 (cond
6640 ((equal arg '(16))
6641 (setq last-command 'dummy)
6642 (org-set-startup-visibility)
6643 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6645 ((equal arg '(64))
6646 (show-all)
6647 (org-unlogged-message "Entire buffer visible, including drawers"))
6649 ;; Table: enter it or move to the next field.
6650 ((org-at-table-p 'any)
6651 (if (org-at-table.el-p)
6652 (message "Use C-c ' to edit table.el tables")
6653 (if arg (org-table-edit-field t)
6654 (org-table-justify-field-maybe)
6655 (call-interactively 'org-table-next-field))))
6657 ((run-hook-with-args-until-success
6658 'org-tab-after-check-for-table-hook))
6660 ;; Global cycling: delegate to `org-cycle-internal-global'.
6661 ((eq arg t) (org-cycle-internal-global))
6663 ;; Drawers: delegate to `org-flag-drawer'.
6664 ((save-excursion
6665 (beginning-of-line 1)
6666 (looking-at org-drawer-regexp))
6667 (org-flag-drawer ; toggle block visibility
6668 (not (get-char-property (match-end 0) 'invisible))))
6670 ;; Show-subtree, ARG levels up from here.
6671 ((integerp arg)
6672 (save-excursion
6673 (org-back-to-heading)
6674 (outline-up-heading (if (< arg 0) (- arg)
6675 (- (funcall outline-level) arg)))
6676 (org-show-subtree)))
6678 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6679 ((and (featurep 'org-inlinetask)
6680 (org-inlinetask-at-task-p)
6681 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6682 (org-inlinetask-toggle-visibility))
6684 ((org-try-cdlatex-tab))
6686 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6687 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6688 (save-excursion (beginning-of-line 1)
6689 (looking-at org-outline-regexp)))
6690 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6691 (org-cycle-internal-local))
6693 ;; From there: TAB emulation and template completion.
6694 (buffer-read-only (org-back-to-heading))
6696 ((run-hook-with-args-until-success
6697 'org-tab-after-check-for-cycling-hook))
6699 ((org-try-structure-completion))
6701 ((run-hook-with-args-until-success
6702 'org-tab-before-tab-emulation-hook))
6704 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6705 (or (not (bolp))
6706 (not (looking-at org-outline-regexp))))
6707 (call-interactively (global-key-binding "\t")))
6709 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6710 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6711 (or (and (eq org-cycle-emulate-tab 'white)
6712 (= (match-end 0) (point-at-eol)))
6713 (and (eq org-cycle-emulate-tab 'whitestart)
6714 (>= (match-end 0) pos))))
6716 (eq org-cycle-emulate-tab t))
6717 (call-interactively (global-key-binding "\t")))
6719 (t (save-excursion
6720 (org-back-to-heading)
6721 (org-cycle)))))))
6723 (defun org-cycle-internal-global ()
6724 "Do the global cycling action."
6725 ;; Hack to avoid display of messages for .org attachments in Gnus
6726 (let ((ga (string-match "\\*fontification" (buffer-name))))
6727 (cond
6728 ((and (eq last-command this-command)
6729 (eq org-cycle-global-status 'overview))
6730 ;; We just created the overview - now do table of contents
6731 ;; This can be slow in very large buffers, so indicate action
6732 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6733 (unless ga (org-unlogged-message "CONTENTS..."))
6734 (org-content)
6735 (unless ga (org-unlogged-message "CONTENTS...done"))
6736 (setq org-cycle-global-status 'contents)
6737 (run-hook-with-args 'org-cycle-hook 'contents))
6739 ((and (eq last-command this-command)
6740 (eq org-cycle-global-status 'contents))
6741 ;; We just showed the table of contents - now show everything
6742 (run-hook-with-args 'org-pre-cycle-hook 'all)
6743 (show-all)
6744 (unless ga (org-unlogged-message "SHOW ALL"))
6745 (setq org-cycle-global-status 'all)
6746 (run-hook-with-args 'org-cycle-hook 'all))
6749 ;; Default action: go to overview
6750 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6751 (org-overview)
6752 (unless ga (org-unlogged-message "OVERVIEW"))
6753 (setq org-cycle-global-status 'overview)
6754 (run-hook-with-args 'org-cycle-hook 'overview)))))
6756 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6758 (defun org-cycle-internal-local ()
6759 "Do the local cycling action."
6760 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6761 ;; First, determine end of headline (EOH), end of subtree or item
6762 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6763 (save-excursion
6764 (if (org-at-item-p)
6765 (progn
6766 (beginning-of-line)
6767 (setq struct (org-list-struct))
6768 (setq eoh (point-at-eol))
6769 (setq eos (org-list-get-item-end-before-blank (point) struct))
6770 (setq has-children (org-list-has-child-p (point) struct)))
6771 (org-back-to-heading)
6772 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6773 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6774 (setq has-children
6775 (or (save-excursion
6776 (let ((level (funcall outline-level)))
6777 (outline-next-heading)
6778 (and (org-at-heading-p t)
6779 (> (funcall outline-level) level))))
6780 (save-excursion
6781 (org-list-search-forward (org-item-beginning-re) eos t)))))
6782 ;; Determine end invisible part of buffer (EOL)
6783 (beginning-of-line 2)
6784 ;; XEmacs doesn't have `next-single-char-property-change'
6785 (if (featurep 'xemacs)
6786 (while (and (not (eobp)) ;; this is like `next-line'
6787 (get-char-property (1- (point)) 'invisible))
6788 (beginning-of-line 2))
6789 (while (and (not (eobp)) ;; this is like `next-line'
6790 (get-char-property (1- (point)) 'invisible))
6791 (goto-char (next-single-char-property-change (point) 'invisible))
6792 (and (eolp) (beginning-of-line 2))))
6793 (setq eol (point)))
6794 ;; Find out what to do next and set `this-command'
6795 (cond
6796 ((= eos eoh)
6797 ;; Nothing is hidden behind this heading
6798 (unless (org-before-first-heading-p)
6799 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6800 (org-unlogged-message "EMPTY ENTRY")
6801 (setq org-cycle-subtree-status nil)
6802 (save-excursion
6803 (goto-char eos)
6804 (outline-next-heading)
6805 (if (outline-invisible-p) (org-flag-heading nil))))
6806 ((and (or (>= eol eos)
6807 (not (string-match "\\S-" (buffer-substring eol eos))))
6808 (or has-children
6809 (not (setq children-skipped
6810 org-cycle-skip-children-state-if-no-children))))
6811 ;; Entire subtree is hidden in one line: children view
6812 (unless (org-before-first-heading-p)
6813 (run-hook-with-args 'org-pre-cycle-hook 'children))
6814 (if (org-at-item-p)
6815 (org-list-set-item-visibility (point-at-bol) struct 'children)
6816 (org-show-entry)
6817 (org-with-limited-levels (show-children))
6818 ;; FIXME: This slows down the func way too much.
6819 ;; How keep drawers hidden in subtree anyway?
6820 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6821 ;; (org-cycle-hide-drawers 'subtree))
6823 ;; Fold every list in subtree to top-level items.
6824 (when (eq org-cycle-include-plain-lists 'integrate)
6825 (save-excursion
6826 (org-back-to-heading)
6827 (while (org-list-search-forward (org-item-beginning-re) eos t)
6828 (beginning-of-line 1)
6829 (let* ((struct (org-list-struct))
6830 (prevs (org-list-prevs-alist struct))
6831 (end (org-list-get-bottom-point struct)))
6832 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6833 (org-list-get-all-items (point) struct prevs))
6834 (goto-char (if (< end eos) end eos)))))))
6835 (org-unlogged-message "CHILDREN")
6836 (save-excursion
6837 (goto-char eos)
6838 (outline-next-heading)
6839 (if (outline-invisible-p) (org-flag-heading nil)))
6840 (setq org-cycle-subtree-status 'children)
6841 (unless (org-before-first-heading-p)
6842 (run-hook-with-args 'org-cycle-hook 'children)))
6843 ((or children-skipped
6844 (and (eq last-command this-command)
6845 (eq org-cycle-subtree-status 'children)))
6846 ;; We just showed the children, or no children are there,
6847 ;; now show everything.
6848 (unless (org-before-first-heading-p)
6849 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6850 (outline-flag-region eoh eos nil)
6851 (org-unlogged-message
6852 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6853 (setq org-cycle-subtree-status 'subtree)
6854 (unless (org-before-first-heading-p)
6855 (run-hook-with-args 'org-cycle-hook 'subtree)))
6857 ;; Default action: hide the subtree.
6858 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6859 (outline-flag-region eoh eos t)
6860 (org-unlogged-message "FOLDED")
6861 (setq org-cycle-subtree-status 'folded)
6862 (unless (org-before-first-heading-p)
6863 (run-hook-with-args 'org-cycle-hook 'folded))))))
6865 ;;;###autoload
6866 (defun org-global-cycle (&optional arg)
6867 "Cycle the global visibility. For details see `org-cycle'.
6868 With \\[universal-argument] prefix arg, switch to startup visibility.
6869 With a numeric prefix, show all headlines up to that level."
6870 (interactive "P")
6871 (let ((org-cycle-include-plain-lists
6872 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6873 (cond
6874 ((integerp arg)
6875 (show-all)
6876 (hide-sublevels arg)
6877 (setq org-cycle-global-status 'contents))
6878 ((equal arg '(4))
6879 (org-set-startup-visibility)
6880 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6882 (org-cycle '(4))))))
6884 (defun org-set-startup-visibility ()
6885 "Set the visibility required by startup options and properties."
6886 (cond
6887 ((eq org-startup-folded t)
6888 (org-overview))
6889 ((eq org-startup-folded 'content)
6890 (org-content))
6891 ((or (eq org-startup-folded 'showeverything)
6892 (eq org-startup-folded nil))
6893 (show-all)))
6894 (unless (eq org-startup-folded 'showeverything)
6895 (if org-hide-block-startup (org-hide-block-all))
6896 (org-set-visibility-according-to-property 'no-cleanup)
6897 (org-cycle-hide-archived-subtrees 'all)
6898 (org-cycle-hide-drawers 'all)
6899 (org-cycle-show-empty-lines t)))
6901 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6902 "Switch subtree visibilities according to :VISIBILITY: property."
6903 (interactive)
6904 (let (org-show-entry-below state)
6905 (save-excursion
6906 (goto-char (point-min))
6907 (while (re-search-forward
6908 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6909 nil t)
6910 (setq state (match-string 1))
6911 (save-excursion
6912 (org-back-to-heading t)
6913 (hide-subtree)
6914 (org-reveal)
6915 (cond
6916 ((equal state '("fold" "folded"))
6917 (hide-subtree))
6918 ((equal state "children")
6919 (org-show-hidden-entry)
6920 (show-children))
6921 ((equal state "content")
6922 (save-excursion
6923 (save-restriction
6924 (org-narrow-to-subtree)
6925 (org-content))))
6926 ((member state '("all" "showall"))
6927 (show-subtree)))))
6928 (unless no-cleanup
6929 (org-cycle-hide-archived-subtrees 'all)
6930 (org-cycle-hide-drawers 'all)
6931 (org-cycle-show-empty-lines 'all)))))
6933 ;; This function uses outline-regexp instead of the more fundamental
6934 ;; org-outline-regexp so that org-cycle-global works outside of Org
6935 ;; buffers, where outline-regexp is needed.
6936 (defun org-overview ()
6937 "Switch to overview mode, showing only top-level headlines.
6938 Really, this shows all headlines with level equal or greater than the level
6939 of the first headline in the buffer. This is important, because if the
6940 first headline is not level one, then (hide-sublevels 1) gives confusing
6941 results."
6942 (interactive)
6943 (let ((pos (point))
6944 (level (save-excursion
6945 (goto-char (point-min))
6946 (if (re-search-forward (concat "^" outline-regexp) nil t)
6947 (progn
6948 (goto-char (match-beginning 0))
6949 (funcall outline-level))))))
6950 (and level (hide-sublevels level))
6951 (recenter '(4))
6952 (goto-char pos)))
6954 (defun org-content (&optional arg)
6955 "Show all headlines in the buffer, like a table of contents.
6956 With numerical argument N, show content up to level N."
6957 (interactive "P")
6958 (save-excursion
6959 ;; Visit all headings and show their offspring
6960 (and (integerp arg) (org-overview))
6961 (goto-char (point-max))
6962 (catch 'exit
6963 (while (and (progn (condition-case nil
6964 (outline-previous-visible-heading 1)
6965 (error (goto-char (point-min))))
6967 (looking-at org-outline-regexp))
6968 (if (integerp arg)
6969 (show-children (1- arg))
6970 (show-branches))
6971 (if (bobp) (throw 'exit nil))))))
6973 (defun org-optimize-window-after-visibility-change (state)
6974 "Adjust the window after a change in outline visibility.
6975 This function is the default value of the hook `org-cycle-hook'."
6976 (when (get-buffer-window (current-buffer))
6977 (cond
6978 ((eq state 'content) nil)
6979 ((eq state 'all) nil)
6980 ((eq state 'folded) nil)
6981 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6982 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6984 (defun org-remove-empty-overlays-at (pos)
6985 "Remove outline overlays that do not contain non-white stuff."
6986 (mapc
6987 (lambda (o)
6988 (and (eq 'outline (overlay-get o 'invisible))
6989 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6990 (overlay-end o))))
6991 (delete-overlay o)))
6992 (overlays-at pos)))
6994 (defun org-clean-visibility-after-subtree-move ()
6995 "Fix visibility issues after moving a subtree."
6996 ;; First, find a reasonable region to look at:
6997 ;; Start two siblings above, end three below
6998 (let* ((beg (save-excursion
6999 (and (org-get-last-sibling)
7000 (org-get-last-sibling))
7001 (point)))
7002 (end (save-excursion
7003 (and (org-get-next-sibling)
7004 (org-get-next-sibling)
7005 (org-get-next-sibling))
7006 (if (org-at-heading-p)
7007 (point-at-eol)
7008 (point))))
7009 (level (looking-at "\\*+"))
7010 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7011 (save-excursion
7012 (save-restriction
7013 (narrow-to-region beg end)
7014 (when re
7015 ;; Properly fold already folded siblings
7016 (goto-char (point-min))
7017 (while (re-search-forward re nil t)
7018 (if (and (not (outline-invisible-p))
7019 (save-excursion
7020 (goto-char (point-at-eol)) (outline-invisible-p)))
7021 (hide-entry))))
7022 (org-cycle-show-empty-lines 'overview)
7023 (org-cycle-hide-drawers 'overview)))))
7025 (defun org-cycle-show-empty-lines (state)
7026 "Show empty lines above all visible headlines.
7027 The region to be covered depends on STATE when called through
7028 `org-cycle-hook'. Lisp program can use t for STATE to get the
7029 entire buffer covered. Note that an empty line is only shown if there
7030 are at least `org-cycle-separator-lines' empty lines before the headline."
7031 (when (not (= org-cycle-separator-lines 0))
7032 (save-excursion
7033 (let* ((n (abs org-cycle-separator-lines))
7034 (re (cond
7035 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7036 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7037 (t (let ((ns (number-to-string (- n 2))))
7038 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7039 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7040 beg end b e)
7041 (cond
7042 ((memq state '(overview contents t))
7043 (setq beg (point-min) end (point-max)))
7044 ((memq state '(children folded))
7045 (setq beg (point) end (progn (org-end-of-subtree t t)
7046 (beginning-of-line 2)
7047 (point)))))
7048 (when beg
7049 (goto-char beg)
7050 (while (re-search-forward re end t)
7051 (unless (get-char-property (match-end 1) 'invisible)
7052 (setq e (match-end 1))
7053 (if (< org-cycle-separator-lines 0)
7054 (setq b (save-excursion
7055 (goto-char (match-beginning 0))
7056 (org-back-over-empty-lines)
7057 (if (save-excursion
7058 (goto-char (max (point-min) (1- (point))))
7059 (org-at-heading-p))
7060 (1- (point))
7061 (point))))
7062 (setq b (match-beginning 1)))
7063 (outline-flag-region b e nil)))))))
7064 ;; Never hide empty lines at the end of the file.
7065 (save-excursion
7066 (goto-char (point-max))
7067 (outline-previous-heading)
7068 (outline-end-of-heading)
7069 (if (and (looking-at "[ \t\n]+")
7070 (= (match-end 0) (point-max)))
7071 (outline-flag-region (point) (match-end 0) nil))))
7073 (defun org-show-empty-lines-in-parent ()
7074 "Move to the parent and re-show empty lines before visible headlines."
7075 (save-excursion
7076 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7077 (org-cycle-show-empty-lines context))))
7079 (defun org-files-list ()
7080 "Return `org-agenda-files' list, plus all open org-mode files.
7081 This is useful for operations that need to scan all of a user's
7082 open and agenda-wise Org files."
7083 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7084 (dolist (buf (buffer-list))
7085 (with-current-buffer buf
7086 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7087 (let ((file (expand-file-name (buffer-file-name))))
7088 (unless (member file files)
7089 (push file files))))))
7090 files))
7092 (defsubst org-entry-beginning-position ()
7093 "Return the beginning position of the current entry."
7094 (save-excursion (outline-back-to-heading t) (point)))
7096 (defsubst org-entry-end-position ()
7097 "Return the end position of the current entry."
7098 (save-excursion (outline-next-heading) (point)))
7100 (defun org-cycle-hide-drawers (state &optional exceptions)
7101 "Re-hide all drawers after a visibility state change.
7102 When non-nil, optional argument EXCEPTIONS is a list of strings
7103 specifying which drawers should not be hidden."
7104 (when (and (derived-mode-p 'org-mode)
7105 (not (memq state '(overview folded contents))))
7106 (save-excursion
7107 (let* ((globalp (memq state '(contents all)))
7108 (beg (if globalp (point-min) (point)))
7109 (end (if globalp (point-max)
7110 (if (eq state 'children)
7111 (save-excursion (outline-next-heading) (point))
7112 (org-end-of-subtree t)))))
7113 (goto-char beg)
7114 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7115 (unless (member-ignore-case (match-string 1) exceptions)
7116 (let ((drawer (org-element-at-point)))
7117 (when (memq (org-element-type drawer) '(drawer property-drawer))
7118 (org-flag-drawer t drawer)
7119 ;; Make sure to skip drawer entirely or we might flag
7120 ;; it another time when matching its ending line with
7121 ;; `org-drawer-regexp'.
7122 (goto-char (org-element-property :end drawer))))))))))
7124 (defun org-cycle-hide-inline-tasks (state)
7125 "Re-hide inline tasks when switching to 'contents or 'children
7126 visibility state."
7127 (case state
7128 (contents
7129 (when (org-bound-and-true-p org-inlinetask-min-level)
7130 (hide-sublevels (1- org-inlinetask-min-level))))
7131 (children
7132 (when (featurep 'org-inlinetask)
7133 (save-excursion
7134 (while (and (outline-next-heading)
7135 (org-inlinetask-at-task-p))
7136 (org-inlinetask-toggle-visibility)
7137 (org-inlinetask-goto-end)))))))
7139 (defun org-flag-drawer (flag &optional element)
7140 "When FLAG is non-nil, hide the drawer we are at.
7141 Otherwise make it visible. When optional argument ELEMENT is
7142 a parsed drawer, as returned by `org-element-at-point', hide or
7143 show that drawer instead."
7144 (let ((drawer (or element (org-element-at-point))))
7145 (when (memq (org-element-type drawer) '(drawer property-drawer))
7146 (save-excursion
7147 (goto-char (org-element-property :post-affiliated drawer))
7148 (outline-flag-region
7149 (line-end-position)
7150 (progn (goto-char (org-element-property :end drawer))
7151 (skip-chars-backward " \r\t\n")
7152 (line-end-position))
7153 flag)))))
7155 (defun org-subtree-end-visible-p ()
7156 "Is the end of the current subtree visible?"
7157 (pos-visible-in-window-p
7158 (save-excursion (org-end-of-subtree t) (point))))
7160 (defun org-first-headline-recenter (&optional N)
7161 "Move cursor to the first headline and recenter the headline.
7162 Optional argument N means put the headline into the Nth line of the window."
7163 (goto-char (point-min))
7164 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7165 (beginning-of-line)
7166 (recenter (prefix-numeric-value N))))
7168 ;;; Saving and restoring visibility
7170 (defun org-outline-overlay-data (&optional use-markers)
7171 "Return a list of the locations of all outline overlays.
7172 These are overlays with the `invisible' property value `outline'.
7173 The return value is a list of cons cells, with start and stop
7174 positions for each overlay.
7175 If USE-MARKERS is set, return the positions as markers."
7176 (let (beg end)
7177 (save-excursion
7178 (save-restriction
7179 (widen)
7180 (delq nil
7181 (mapcar (lambda (o)
7182 (when (eq (overlay-get o 'invisible) 'outline)
7183 (setq beg (overlay-start o)
7184 end (overlay-end o))
7185 (and beg end (> end beg)
7186 (if use-markers
7187 (cons (move-marker (make-marker) beg)
7188 (move-marker (make-marker) end))
7189 (cons beg end)))))
7190 (overlays-in (point-min) (point-max))))))))
7192 (defun org-set-outline-overlay-data (data)
7193 "Create visibility overlays for all positions in DATA.
7194 DATA should have been made by `org-outline-overlay-data'."
7195 (let (o)
7196 (save-excursion
7197 (save-restriction
7198 (widen)
7199 (show-all)
7200 (mapc (lambda (c)
7201 (outline-flag-region (car c) (cdr c) t))
7202 data)))))
7204 ;;; Folding of blocks
7206 (defvar org-hide-block-overlays nil
7207 "Overlays hiding blocks.")
7208 (make-variable-buffer-local 'org-hide-block-overlays)
7210 (defun org-block-map (function &optional start end)
7211 "Call FUNCTION at the head of all source blocks in the current buffer.
7212 Optional arguments START and END can be used to limit the range."
7213 (let ((start (or start (point-min)))
7214 (end (or end (point-max))))
7215 (save-excursion
7216 (goto-char start)
7217 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7218 (save-excursion
7219 (save-match-data
7220 (goto-char (match-beginning 0))
7221 (funcall function)))))))
7223 (defun org-hide-block-toggle-all ()
7224 "Toggle the visibility of all blocks in the current buffer."
7225 (org-block-map #'org-hide-block-toggle))
7227 (defun org-hide-block-all ()
7228 "Fold all blocks in the current buffer."
7229 (interactive)
7230 (org-show-block-all)
7231 (org-block-map #'org-hide-block-toggle-maybe))
7233 (defun org-show-block-all ()
7234 "Unfold all blocks in the current buffer."
7235 (interactive)
7236 (mapc 'delete-overlay org-hide-block-overlays)
7237 (setq org-hide-block-overlays nil))
7239 (defun org-hide-block-toggle-maybe ()
7240 "Toggle visibility of block at point."
7241 (interactive)
7242 (let ((case-fold-search t))
7243 (if (save-excursion
7244 (beginning-of-line 1)
7245 (looking-at org-block-regexp))
7246 (progn (org-hide-block-toggle)
7247 t) ;; to signal that we took action
7248 nil))) ;; to signal that we did not
7250 (defun org-hide-block-toggle (&optional force)
7251 "Toggle the visibility of the current block."
7252 (interactive)
7253 (save-excursion
7254 (beginning-of-line)
7255 (if (re-search-forward org-block-regexp nil t)
7256 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7257 (end (match-end 0)) ;; end of entire body
7259 (if (memq t (mapcar (lambda (overlay)
7260 (eq (overlay-get overlay 'invisible)
7261 'org-hide-block))
7262 (overlays-at start)))
7263 (if (or (not force) (eq force 'off))
7264 (mapc (lambda (ov)
7265 (when (member ov org-hide-block-overlays)
7266 (setq org-hide-block-overlays
7267 (delq ov org-hide-block-overlays)))
7268 (when (eq (overlay-get ov 'invisible)
7269 'org-hide-block)
7270 (delete-overlay ov)))
7271 (overlays-at start)))
7272 (setq ov (make-overlay start end))
7273 (overlay-put ov 'invisible 'org-hide-block)
7274 ;; make the block accessible to isearch
7275 (overlay-put
7276 ov 'isearch-open-invisible
7277 (lambda (ov)
7278 (when (member ov org-hide-block-overlays)
7279 (setq org-hide-block-overlays
7280 (delq ov org-hide-block-overlays)))
7281 (when (eq (overlay-get ov 'invisible)
7282 'org-hide-block)
7283 (delete-overlay ov))))
7284 (push ov org-hide-block-overlays)))
7285 (user-error "Not looking at a source block"))))
7287 ;; org-tab-after-check-for-cycling-hook
7288 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7289 ;; Remove overlays when changing major mode
7290 (add-hook 'org-mode-hook
7291 (lambda () (org-add-hook 'change-major-mode-hook
7292 'org-show-block-all 'append 'local)))
7294 ;;; Org-goto
7296 (defvar org-goto-window-configuration nil)
7297 (defvar org-goto-marker nil)
7298 (defvar org-goto-map)
7299 (defun org-goto-map ()
7300 "Set the keymap `org-goto'."
7301 (setq org-goto-map
7302 (let ((map (make-sparse-keymap)))
7303 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7304 mouse-drag-region universal-argument org-occur))
7305 cmd)
7306 (while (setq cmd (pop cmds))
7307 (substitute-key-definition cmd cmd map global-map)))
7308 (suppress-keymap map)
7309 (org-defkey map "\C-m" 'org-goto-ret)
7310 (org-defkey map [(return)] 'org-goto-ret)
7311 (org-defkey map [(left)] 'org-goto-left)
7312 (org-defkey map [(right)] 'org-goto-right)
7313 (org-defkey map [(control ?g)] 'org-goto-quit)
7314 (org-defkey map "\C-i" 'org-cycle)
7315 (org-defkey map [(tab)] 'org-cycle)
7316 (org-defkey map [(down)] 'outline-next-visible-heading)
7317 (org-defkey map [(up)] 'outline-previous-visible-heading)
7318 (if org-goto-auto-isearch
7319 (if (fboundp 'define-key-after)
7320 (define-key-after map [t] 'org-goto-local-auto-isearch)
7321 nil)
7322 (org-defkey map "q" 'org-goto-quit)
7323 (org-defkey map "n" 'outline-next-visible-heading)
7324 (org-defkey map "p" 'outline-previous-visible-heading)
7325 (org-defkey map "f" 'outline-forward-same-level)
7326 (org-defkey map "b" 'outline-backward-same-level)
7327 (org-defkey map "u" 'outline-up-heading))
7328 (org-defkey map "/" 'org-occur)
7329 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7330 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7331 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7332 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7333 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7334 map)))
7336 (defconst org-goto-help
7337 "Browse buffer copy, to find location or copy text.%s
7338 RET=jump to location C-g=quit and return to previous location
7339 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7341 (defvar org-goto-start-pos) ; dynamically scoped parameter
7343 (defun org-goto (&optional alternative-interface)
7344 "Look up a different location in the current file, keeping current visibility.
7346 When you want look-up or go to a different location in a
7347 document, the fastest way is often to fold the entire buffer and
7348 then dive into the tree. This method has the disadvantage, that
7349 the previous location will be folded, which may not be what you
7350 want.
7352 This command works around this by showing a copy of the current
7353 buffer in an indirect buffer, in overview mode. You can dive
7354 into the tree in that copy, use org-occur and incremental search
7355 to find a location. When pressing RET or `Q', the command
7356 returns to the original buffer in which the visibility is still
7357 unchanged. After RET it will also jump to the location selected
7358 in the indirect buffer and expose the headline hierarchy above.
7360 With a prefix argument, use the alternative interface: e.g. if
7361 `org-goto-interface' is 'outline use 'outline-path-completion."
7362 (interactive "P")
7363 (org-goto-map)
7364 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7365 (org-refile-use-outline-path t)
7366 (org-refile-target-verify-function nil)
7367 (interface
7368 (if (not alternative-interface)
7369 org-goto-interface
7370 (if (eq org-goto-interface 'outline)
7371 'outline-path-completion
7372 'outline)))
7373 (org-goto-start-pos (point))
7374 (selected-point
7375 (if (eq interface 'outline)
7376 (car (org-get-location (current-buffer) org-goto-help))
7377 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7378 (org-refile-check-position pa)
7379 (nth 3 pa)))))
7380 (if selected-point
7381 (progn
7382 (org-mark-ring-push org-goto-start-pos)
7383 (goto-char selected-point)
7384 (if (or (outline-invisible-p) (org-invisible-p2))
7385 (org-show-context 'org-goto)))
7386 (message "Quit"))))
7388 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7389 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7390 (defvar org-goto-local-auto-isearch-map) ; defined below
7392 (defun org-get-location (buf help)
7393 "Let the user select a location in the Org-mode buffer BUF.
7394 This function uses a recursive edit. It returns the selected position
7395 or nil."
7396 (org-no-popups
7397 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7398 (isearch-hide-immediately nil)
7399 (isearch-search-fun-function
7400 (lambda () 'org-goto-local-search-headings))
7401 (org-goto-selected-point org-goto-exit-command))
7402 (save-excursion
7403 (save-window-excursion
7404 (delete-other-windows)
7405 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7406 (org-pop-to-buffer-same-window
7407 (condition-case nil
7408 (make-indirect-buffer (current-buffer) "*org-goto*")
7409 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7410 (with-output-to-temp-buffer "*Org Help*"
7411 (princ (format help (if org-goto-auto-isearch
7412 " Just type for auto-isearch."
7413 " n/p/f/b/u to navigate, q to quit."))))
7414 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7415 (setq buffer-read-only nil)
7416 (let ((org-startup-truncated t)
7417 (org-startup-folded nil)
7418 (org-startup-align-all-tables nil))
7419 (org-mode)
7420 (org-overview))
7421 (setq buffer-read-only t)
7422 (if (and (boundp 'org-goto-start-pos)
7423 (integer-or-marker-p org-goto-start-pos))
7424 (let ((org-show-hierarchy-above t)
7425 (org-show-siblings t)
7426 (org-show-following-heading t))
7427 (goto-char org-goto-start-pos)
7428 (and (outline-invisible-p) (org-show-context)))
7429 (goto-char (point-min)))
7430 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7431 (message "Select location and press RET")
7432 (use-local-map org-goto-map)
7433 (recursive-edit)))
7434 (kill-buffer "*org-goto*")
7435 (cons org-goto-selected-point org-goto-exit-command))))
7437 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7438 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7439 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7440 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7442 (defun org-goto-local-search-headings (string bound noerror)
7443 "Search and make sure that any matches are in headlines."
7444 (catch 'return
7445 (while (if isearch-forward
7446 (search-forward string bound noerror)
7447 (search-backward string bound noerror))
7448 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7449 (and (member :headline context)
7450 (not (member :tags context))))
7451 (throw 'return (point))))))
7453 (defun org-goto-local-auto-isearch ()
7454 "Start isearch."
7455 (interactive)
7456 (goto-char (point-min))
7457 (let ((keys (this-command-keys)))
7458 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7459 (isearch-mode t)
7460 (isearch-process-search-char (string-to-char keys)))))
7462 (defun org-goto-ret (&optional arg)
7463 "Finish `org-goto' by going to the new location."
7464 (interactive "P")
7465 (setq org-goto-selected-point (point)
7466 org-goto-exit-command 'return)
7467 (throw 'exit nil))
7469 (defun org-goto-left ()
7470 "Finish `org-goto' by going to the new location."
7471 (interactive)
7472 (if (org-at-heading-p)
7473 (progn
7474 (beginning-of-line 1)
7475 (setq org-goto-selected-point (point)
7476 org-goto-exit-command 'left)
7477 (throw 'exit nil))
7478 (user-error "Not on a heading")))
7480 (defun org-goto-right ()
7481 "Finish `org-goto' by going to the new location."
7482 (interactive)
7483 (if (org-at-heading-p)
7484 (progn
7485 (setq org-goto-selected-point (point)
7486 org-goto-exit-command 'right)
7487 (throw 'exit nil))
7488 (user-error "Not on a heading")))
7490 (defun org-goto-quit ()
7491 "Finish `org-goto' without cursor motion."
7492 (interactive)
7493 (setq org-goto-selected-point nil)
7494 (setq org-goto-exit-command 'quit)
7495 (throw 'exit nil))
7497 ;;; Indirect buffer display of subtrees
7499 (defvar org-indirect-dedicated-frame nil
7500 "This is the frame being used for indirect tree display.")
7501 (defvar org-last-indirect-buffer nil)
7503 (defun org-tree-to-indirect-buffer (&optional arg)
7504 "Create indirect buffer and narrow it to current subtree.
7505 With a numerical prefix ARG, go up to this level and then take that tree.
7506 If ARG is negative, go up that many levels.
7508 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7509 indirect buffer previously made with this command, to avoid proliferation of
7510 indirect buffers. However, when you call the command with a \
7511 \\[universal-argument] prefix, or
7512 when `org-indirect-buffer-display' is `new-frame', the last buffer
7513 is kept so that you can work with several indirect buffers at the same time.
7514 If `org-indirect-buffer-display' is `dedicated-frame', the \
7515 \\[universal-argument] prefix also
7516 requests that a new frame be made for the new buffer, so that the dedicated
7517 frame is not changed."
7518 (interactive "P")
7519 (let ((cbuf (current-buffer))
7520 (cwin (selected-window))
7521 (pos (point))
7522 beg end level heading ibuf)
7523 (save-excursion
7524 (org-back-to-heading t)
7525 (when (numberp arg)
7526 (setq level (org-outline-level))
7527 (if (< arg 0) (setq arg (+ level arg)))
7528 (while (> (setq level (org-outline-level)) arg)
7529 (org-up-heading-safe)))
7530 (setq beg (point)
7531 heading (org-get-heading))
7532 (org-end-of-subtree t t)
7533 (if (org-at-heading-p) (backward-char 1))
7534 (setq end (point)))
7535 (if (and (buffer-live-p org-last-indirect-buffer)
7536 (not (eq org-indirect-buffer-display 'new-frame))
7537 (not arg))
7538 (kill-buffer org-last-indirect-buffer))
7539 (setq ibuf (org-get-indirect-buffer cbuf heading)
7540 org-last-indirect-buffer ibuf)
7541 (cond
7542 ((or (eq org-indirect-buffer-display 'new-frame)
7543 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7544 (select-frame (make-frame))
7545 (delete-other-windows)
7546 (org-pop-to-buffer-same-window ibuf)
7547 (org-set-frame-title heading))
7548 ((eq org-indirect-buffer-display 'dedicated-frame)
7549 (raise-frame
7550 (select-frame (or (and org-indirect-dedicated-frame
7551 (frame-live-p org-indirect-dedicated-frame)
7552 org-indirect-dedicated-frame)
7553 (setq org-indirect-dedicated-frame (make-frame)))))
7554 (delete-other-windows)
7555 (org-pop-to-buffer-same-window ibuf)
7556 (org-set-frame-title (concat "Indirect: " heading)))
7557 ((eq org-indirect-buffer-display 'current-window)
7558 (org-pop-to-buffer-same-window ibuf))
7559 ((eq org-indirect-buffer-display 'other-window)
7560 (pop-to-buffer ibuf))
7561 (t (error "Invalid value")))
7562 (if (featurep 'xemacs)
7563 (save-excursion (org-mode) (turn-on-font-lock)))
7564 (narrow-to-region beg end)
7565 (show-all)
7566 (goto-char pos)
7567 (run-hook-with-args 'org-cycle-hook 'all)
7568 (and (window-live-p cwin) (select-window cwin))))
7570 (defun org-get-indirect-buffer (&optional buffer heading)
7571 (setq buffer (or buffer (current-buffer)))
7572 (let ((n 1) (base (buffer-name buffer)) bname)
7573 (while (buffer-live-p
7574 (get-buffer
7575 (setq bname
7576 (concat base "-"
7577 (if heading (concat heading "-" (number-to-string n))
7578 (number-to-string n))))))
7579 (setq n (1+ n)))
7580 (condition-case nil
7581 (make-indirect-buffer buffer bname 'clone)
7582 (error (make-indirect-buffer buffer bname)))))
7584 (defun org-set-frame-title (title)
7585 "Set the title of the current frame to the string TITLE."
7586 ;; FIXME: how to name a single frame in XEmacs???
7587 (unless (featurep 'xemacs)
7588 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7590 ;;;; Structure editing
7592 ;;; Inserting headlines
7594 (defun org-previous-line-empty-p (&optional next)
7595 "Is the previous line a blank line?
7596 When NEXT is non-nil, check the next line instead."
7597 (save-excursion
7598 (and (not (bobp))
7599 (or (beginning-of-line (if next 2 0)) t)
7600 (save-match-data
7601 (looking-at "[ \t]*$")))))
7603 (defun org-insert-heading (&optional arg invisible-ok)
7604 "Insert a new heading or item with same depth at point.
7605 If point is in a plain list and ARG is nil, create a new list item.
7606 With one universal prefix argument, insert a heading even in lists.
7607 With two universal prefix arguments, insert the heading at the end
7608 of the parent subtree.
7610 If point is at the beginning of a headline, insert a sibling before
7611 the current headline. If point is not at the beginning, split the line
7612 and create a new headline with the text in the current line after point
7613 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7615 If point is at the beginning of a normal line, turn this line into
7616 a heading.
7618 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7619 This is important for non-interactive uses of the command."
7620 (interactive "P")
7621 (if (org-called-interactively-p 'any) (org-reveal))
7622 (let ((itemp (org-in-item-p))
7623 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7624 (respect-content (or org-insert-heading-respect-content
7625 (equal arg '(16))))
7626 (initial-content "")
7627 (adjust-empty-lines t))
7629 (cond
7631 ((or (= (buffer-size) 0)
7632 (and (not (save-excursion
7633 (and (ignore-errors (org-back-to-heading invisible-ok))
7634 (org-at-heading-p))))
7635 (or arg (not itemp))))
7636 ;; At beginning of buffer or so high up that only a heading
7637 ;; makes sense.
7638 (insert
7639 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7640 (if (org-in-src-block-p) ",* " "* "))
7641 (run-hooks 'org-insert-heading-hook))
7643 ((and itemp (not (equal arg '(4))))
7644 ;; Insert an item
7645 (org-insert-item))
7648 ;; Insert a heading
7649 (save-restriction
7650 (widen)
7651 (let* ((level nil)
7652 (on-heading (org-at-heading-p))
7653 (empty-line-p (if on-heading
7654 (org-previous-line-empty-p)
7655 ;; We will decide later
7656 nil))
7657 ;; Get a level string to fall back on
7658 (fix-level
7659 (save-excursion
7660 (org-back-to-heading t)
7661 (if (org-previous-line-empty-p) (setq empty-line-p t))
7662 (looking-at org-outline-regexp)
7663 (make-string (1- (length (match-string 0))) ?*)))
7664 (stars
7665 (save-excursion
7666 (condition-case nil
7667 (progn
7668 (org-back-to-heading invisible-ok)
7669 (when (and (not on-heading)
7670 (featurep 'org-inlinetask)
7671 (integerp org-inlinetask-min-level)
7672 (>= (length (match-string 0))
7673 org-inlinetask-min-level))
7674 ;; Find a heading level before the inline task
7675 (while (and (setq level (org-up-heading-safe))
7676 (>= level org-inlinetask-min-level)))
7677 (if (org-at-heading-p)
7678 (org-back-to-heading invisible-ok)
7679 (error "This should not happen")))
7680 (unless (and (save-excursion
7681 (save-match-data
7682 (org-backward-heading-same-level
7683 1 invisible-ok))
7684 (= (point) (match-beginning 0)))
7685 (not (org-previous-line-empty-p t)))
7686 (setq empty-line-p (or empty-line-p
7687 (org-previous-line-empty-p))))
7688 (match-string 0))
7689 (error (or fix-level "* ")))))
7690 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7691 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7692 pos hide-previous previous-pos)
7694 ;; If we insert after content, move there and clean up whitespace
7695 (when respect-content
7696 (org-end-of-subtree nil t)
7697 (skip-chars-backward " \r\n")
7698 (and (looking-at "[ \t]+") (replace-match ""))
7699 (unless (eobp) (forward-char 1))
7700 (when (looking-at "^\\*")
7701 (unless (bobp) (backward-char 1))
7702 (insert "\n")))
7704 ;; If we are splitting, grab the text that should be moved to the new headline
7705 (when may-split
7706 (if (org-on-heading-p)
7707 ;; This is a heading, we split intelligently (keeping tags)
7708 (let ((pos (point)))
7709 (goto-char (point-at-bol))
7710 (unless (looking-at org-complex-heading-regexp)
7711 (error "This should not happen"))
7712 (when (and (match-beginning 4)
7713 (> pos (match-beginning 4))
7714 (< pos (match-end 4)))
7715 (setq initial-content (buffer-substring pos (match-end 4)))
7716 (goto-char pos)
7717 (delete-region (point) (match-end 4))
7718 (if (looking-at "[ \t]*$")
7719 (replace-match "")
7720 (insert (make-string (length initial-content) ?\ )))
7721 (setq initial-content (org-trim initial-content)))
7722 (goto-char pos))
7723 ;; a normal line
7724 (unless (bolp)
7725 (setq initial-content (buffer-substring (point) (point-at-eol)))
7726 (delete-region (point) (point-at-eol))
7727 (setq initial-content (org-trim initial-content)))))
7729 ;; If we are at the beginning of the line, insert before it. Else after
7730 (cond
7731 ((and (bolp) (looking-at "[ \t]*$")))
7732 ((and (bolp) (not (looking-at "[ \t]*$")))
7733 (open-line 1))
7735 (goto-char (point-at-eol))
7736 (insert "\n")))
7738 ;; Insert the new heading
7739 (insert stars)
7740 (just-one-space)
7741 (insert initial-content)
7742 (when adjust-empty-lines
7743 (if (or (not blank)
7744 (and blank (not (org-previous-line-empty-p))))
7745 (org-N-empty-lines-before-current (if blank 1 0))))
7746 (run-hooks 'org-insert-heading-hook)))))))
7748 (defun org-N-empty-lines-before-current (N)
7749 "Make the number of empty lines before current exactly N.
7750 So this will delete or add empty lines."
7751 (save-excursion
7752 (goto-char (point-at-bol))
7753 (if (looking-back "\\s-+" nil 'greedy)
7754 (replace-match ""))
7755 (or (bobp) (insert "\n"))
7756 (while (> N 0)
7757 (insert "\n")
7758 (setq N (1- N)))))
7760 (defun org-get-heading (&optional no-tags no-todo)
7761 "Return the heading of the current entry, without the stars.
7762 When NO-TAGS is non-nil, don't include tags.
7763 When NO-TODO is non-nil, don't include TODO keywords."
7764 (save-excursion
7765 (org-back-to-heading t)
7766 (cond
7767 ((and no-tags no-todo)
7768 (looking-at org-complex-heading-regexp)
7769 (match-string 4))
7770 (no-tags
7771 (looking-at (concat org-outline-regexp
7772 "\\(.*?\\)"
7773 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7774 (match-string 1))
7775 (no-todo
7776 (looking-at org-todo-line-regexp)
7777 (match-string 3))
7778 (t (looking-at org-heading-regexp)
7779 (match-string 2)))))
7781 (defvar orgstruct-mode) ; defined below
7783 (defun org-heading-components ()
7784 "Return the components of the current heading.
7785 This is a list with the following elements:
7786 - the level as an integer
7787 - the reduced level, different if `org-odd-levels-only' is set.
7788 - the TODO keyword, or nil
7789 - the priority character, like ?A, or nil if no priority is given
7790 - the headline text itself, or the tags string if no headline text
7791 - the tags string, or nil."
7792 (save-excursion
7793 (org-back-to-heading t)
7794 (if (let (case-fold-search)
7795 (looking-at
7796 (if orgstruct-mode
7797 org-heading-regexp
7798 org-complex-heading-regexp)))
7799 (if orgstruct-mode
7800 (list (length (match-string 1))
7801 (org-reduced-level (length (match-string 1)))
7804 (match-string 2)
7805 nil)
7806 (list (length (match-string 1))
7807 (org-reduced-level (length (match-string 1)))
7808 (org-match-string-no-properties 2)
7809 (and (match-end 3) (aref (match-string 3) 2))
7810 (org-match-string-no-properties 4)
7811 (org-match-string-no-properties 5))))))
7813 (defun org-get-entry ()
7814 "Get the entry text, after heading, entire subtree."
7815 (save-excursion
7816 (org-back-to-heading t)
7817 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7819 (defun org-insert-heading-after-current ()
7820 "Insert a new heading with same level as current, after current subtree."
7821 (interactive)
7822 (org-back-to-heading)
7823 (org-insert-heading)
7824 (org-move-subtree-down)
7825 (end-of-line 1))
7827 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7828 "Insert heading with `org-insert-heading-respect-content' set to t."
7829 (interactive "P")
7830 (let ((org-insert-heading-respect-content t))
7831 (org-insert-heading '(4) invisible-ok)))
7833 (defun org-insert-todo-heading-respect-content (&optional force-state)
7834 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7835 (interactive "P")
7836 (let ((org-insert-heading-respect-content t))
7837 (org-insert-todo-heading force-state '(4))))
7839 (defun org-insert-todo-heading (arg &optional force-heading)
7840 "Insert a new heading with the same level and TODO state as current heading.
7841 If the heading has no TODO state, or if the state is DONE, use the first
7842 state (TODO by default). Also one prefix arg, force first state. With two
7843 prefix args, force inserting at the end of the parent subtree."
7844 (interactive "P")
7845 (when (or force-heading (not (org-insert-item 'checkbox)))
7846 (org-insert-heading (or (and (equal arg '(16)) '(16))
7847 force-heading))
7848 (save-excursion
7849 (org-back-to-heading)
7850 (outline-previous-heading)
7851 (looking-at org-todo-line-regexp))
7852 (let*
7853 ((new-mark-x
7854 (if (or arg
7855 (not (match-beginning 2))
7856 (member (match-string 2) org-done-keywords))
7857 (car org-todo-keywords-1)
7858 (match-string 2)))
7859 (new-mark
7861 (run-hook-with-args-until-success
7862 'org-todo-get-default-hook new-mark-x nil)
7863 new-mark-x)))
7864 (beginning-of-line 1)
7865 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7866 (if org-treat-insert-todo-heading-as-state-change
7867 (org-todo new-mark)
7868 (insert new-mark " "))))
7869 (when org-provide-todo-statistics
7870 (org-update-parent-todo-statistics))))
7872 (defun org-insert-subheading (arg)
7873 "Insert a new subheading and demote it.
7874 Works for outline headings and for plain lists alike."
7875 (interactive "P")
7876 (org-insert-heading arg)
7877 (cond
7878 ((org-at-heading-p) (org-do-demote))
7879 ((org-at-item-p) (org-indent-item))))
7881 (defun org-insert-todo-subheading (arg)
7882 "Insert a new subheading with TODO keyword or checkbox and demote it.
7883 Works for outline headings and for plain lists alike."
7884 (interactive "P")
7885 (org-insert-todo-heading arg)
7886 (cond
7887 ((org-at-heading-p) (org-do-demote))
7888 ((org-at-item-p) (org-indent-item))))
7890 ;;; Promotion and Demotion
7892 (defvar org-after-demote-entry-hook nil
7893 "Hook run after an entry has been demoted.
7894 The cursor will be at the beginning of the entry.
7895 When a subtree is being demoted, the hook will be called for each node.")
7897 (defvar org-after-promote-entry-hook nil
7898 "Hook run after an entry has been promoted.
7899 The cursor will be at the beginning of the entry.
7900 When a subtree is being promoted, the hook will be called for each node.")
7902 (defun org-promote-subtree ()
7903 "Promote the entire subtree.
7904 See also `org-promote'."
7905 (interactive)
7906 (save-excursion
7907 (org-with-limited-levels (org-map-tree 'org-promote)))
7908 (org-fix-position-after-promote))
7910 (defun org-demote-subtree ()
7911 "Demote the entire subtree. See `org-demote'.
7912 See also `org-promote'."
7913 (interactive)
7914 (save-excursion
7915 (org-with-limited-levels (org-map-tree 'org-demote)))
7916 (org-fix-position-after-promote))
7919 (defun org-do-promote ()
7920 "Promote the current heading higher up the tree.
7921 If the region is active in `transient-mark-mode', promote all headings
7922 in the region."
7923 (interactive)
7924 (save-excursion
7925 (if (org-region-active-p)
7926 (org-map-region 'org-promote (region-beginning) (region-end))
7927 (org-promote)))
7928 (org-fix-position-after-promote))
7930 (defun org-do-demote ()
7931 "Demote the current heading lower down the tree.
7932 If the region is active in `transient-mark-mode', demote all headings
7933 in the region."
7934 (interactive)
7935 (save-excursion
7936 (if (org-region-active-p)
7937 (org-map-region 'org-demote (region-beginning) (region-end))
7938 (org-demote)))
7939 (org-fix-position-after-promote))
7941 (defun org-fix-position-after-promote ()
7942 "Make sure that after pro/demotion cursor position is right."
7943 (let ((pos (point)))
7944 (when (save-excursion
7945 (beginning-of-line 1)
7946 (looking-at org-todo-line-regexp)
7947 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7948 (cond ((eobp) (insert " "))
7949 ((eolp) (insert " "))
7950 ((equal (char-after) ?\ ) (forward-char 1))))))
7952 (defun org-current-level ()
7953 "Return the level of the current entry, or nil if before the first headline.
7954 The level is the number of stars at the beginning of the headline."
7955 (save-excursion
7956 (org-with-limited-levels
7957 (if (ignore-errors (org-back-to-heading t))
7958 (funcall outline-level)))))
7960 (defun org-get-previous-line-level ()
7961 "Return the outline depth of the last headline before the current line.
7962 Returns 0 for the first headline in the buffer, and nil if before the
7963 first headline."
7964 (and (org-current-level)
7965 (or (and (/= (line-beginning-position) (point-min))
7966 (save-excursion (beginning-of-line 0) (org-current-level)))
7967 0)))
7969 (defun org-reduced-level (l)
7970 "Compute the effective level of a heading.
7971 This takes into account the setting of `org-odd-levels-only'."
7972 (cond
7973 ((zerop l) 0)
7974 (org-odd-levels-only (1+ (floor (/ l 2))))
7975 (t l)))
7977 (defun org-level-increment ()
7978 "Return the number of stars that will be added or removed at a
7979 time to headlines when structure editing, based on the value of
7980 `org-odd-levels-only'."
7981 (if org-odd-levels-only 2 1))
7983 (defun org-get-valid-level (level &optional change)
7984 "Rectify a level change under the influence of `org-odd-levels-only'
7985 LEVEL is a current level, CHANGE is by how much the level should be
7986 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7987 even level numbers will become the next higher odd number."
7988 (if org-odd-levels-only
7989 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7990 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7991 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7992 (max 1 (+ level (or change 0)))))
7994 (if (boundp 'define-obsolete-function-alias)
7995 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7996 (define-obsolete-function-alias 'org-get-legal-level
7997 'org-get-valid-level)
7998 (define-obsolete-function-alias 'org-get-legal-level
7999 'org-get-valid-level "23.1")))
8001 (defun org-promote ()
8002 "Promote the current heading higher up the tree.
8003 If the region is active in `transient-mark-mode', promote all headings
8004 in the region."
8005 (org-back-to-heading t)
8006 (let* ((level (save-match-data (funcall outline-level)))
8007 (after-change-functions (remove 'flyspell-after-change-function
8008 after-change-functions))
8009 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8010 (diff (abs (- level (length up-head) -1))))
8011 (cond ((and (= level 1) org-called-with-limited-levels
8012 org-allow-promoting-top-level-subtree)
8013 (replace-match "# " nil t))
8014 ((= level 1)
8015 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8016 (t (replace-match up-head nil t)))
8017 ;; Fixup tag positioning
8018 (unless (= level 1)
8019 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8020 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8021 (run-hooks 'org-after-promote-entry-hook)))
8023 (defun org-demote ()
8024 "Demote the current heading lower down the tree.
8025 If the region is active in `transient-mark-mode', demote all headings
8026 in the region."
8027 (org-back-to-heading t)
8028 (let* ((level (save-match-data (funcall outline-level)))
8029 (after-change-functions (remove 'flyspell-after-change-function
8030 after-change-functions))
8031 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8032 (diff (abs (- level (length down-head) -1))))
8033 (replace-match down-head nil t)
8034 ;; Fixup tag positioning
8035 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8036 (if org-adapt-indentation (org-fixup-indentation diff))
8037 (run-hooks 'org-after-demote-entry-hook)))
8039 (defun org-cycle-level ()
8040 "Cycle the level of an empty headline through possible states.
8041 This goes first to child, then to parent, level, then up the hierarchy.
8042 After top level, it switches back to sibling level."
8043 (interactive)
8044 (let ((org-adapt-indentation nil))
8045 (when (org-point-at-end-of-empty-headline)
8046 (setq this-command 'org-cycle-level) ; Only needed for caching
8047 (let ((cur-level (org-current-level))
8048 (prev-level (org-get-previous-line-level)))
8049 (cond
8050 ;; If first headline in file, promote to top-level.
8051 ((= prev-level 0)
8052 (loop repeat (/ (- cur-level 1) (org-level-increment))
8053 do (org-do-promote)))
8054 ;; If same level as prev, demote one.
8055 ((= prev-level cur-level)
8056 (org-do-demote))
8057 ;; If parent is top-level, promote to top level if not already.
8058 ((= prev-level 1)
8059 (loop repeat (/ (- cur-level 1) (org-level-increment))
8060 do (org-do-promote)))
8061 ;; If top-level, return to prev-level.
8062 ((= cur-level 1)
8063 (loop repeat (/ (- prev-level 1) (org-level-increment))
8064 do (org-do-demote)))
8065 ;; If less than prev-level, promote one.
8066 ((< cur-level prev-level)
8067 (org-do-promote))
8068 ;; If deeper than prev-level, promote until higher than
8069 ;; prev-level.
8070 ((> cur-level prev-level)
8071 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8072 do (org-do-promote))))
8073 t))))
8075 (defun org-map-tree (fun)
8076 "Call FUN for every heading underneath the current one."
8077 (org-back-to-heading)
8078 (let ((level (funcall outline-level)))
8079 (save-excursion
8080 (funcall fun)
8081 (while (and (progn
8082 (outline-next-heading)
8083 (> (funcall outline-level) level))
8084 (not (eobp)))
8085 (funcall fun)))))
8087 (defun org-map-region (fun beg end)
8088 "Call FUN for every heading between BEG and END."
8089 (let ((org-ignore-region t))
8090 (save-excursion
8091 (setq end (copy-marker end))
8092 (goto-char beg)
8093 (if (and (re-search-forward org-outline-regexp-bol nil t)
8094 (< (point) end))
8095 (funcall fun))
8096 (while (and (progn
8097 (outline-next-heading)
8098 (< (point) end))
8099 (not (eobp)))
8100 (funcall fun)))))
8102 (defvar org-property-end-re) ; silence byte-compiler
8103 (defun org-fixup-indentation (diff)
8104 "Change the indentation in the current entry by DIFF.
8105 However, if any line in the current entry has no indentation, or if it
8106 would end up with no indentation after the change, nothing at all is done."
8107 (save-excursion
8108 (let ((end (save-excursion (outline-next-heading)
8109 (point-marker)))
8110 (prohibit (if (> diff 0)
8111 "^\\S-"
8112 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8113 col)
8114 (unless (save-excursion (end-of-line 1)
8115 (re-search-forward prohibit end t))
8116 (while (and (< (point) end)
8117 (re-search-forward "^[ \t]+" end t))
8118 (goto-char (match-end 0))
8119 (setq col (current-column))
8120 (if (< diff 0) (replace-match ""))
8121 (org-indent-to-column (+ diff col))))
8122 (move-marker end nil))))
8124 (defun org-convert-to-odd-levels ()
8125 "Convert an org-mode file with all levels allowed to one with odd levels.
8126 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8127 level 5 etc."
8128 (interactive)
8129 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8130 (let ((outline-level 'org-outline-level)
8131 (org-odd-levels-only nil) n)
8132 (save-excursion
8133 (goto-char (point-min))
8134 (while (re-search-forward "^\\*\\*+ " nil t)
8135 (setq n (- (length (match-string 0)) 2))
8136 (while (>= (setq n (1- n)) 0)
8137 (org-demote))
8138 (end-of-line 1))))))
8140 (defun org-convert-to-oddeven-levels ()
8141 "Convert an org-mode file with only odd levels to one with odd/even levels.
8142 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8143 file contains a section with an even level, conversion would
8144 destroy the structure of the file. An error is signaled in this
8145 case."
8146 (interactive)
8147 (goto-char (point-min))
8148 ;; First check if there are no even levels
8149 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8150 (org-show-context t)
8151 (error "Not all levels are odd in this file. Conversion not possible"))
8152 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8153 (let ((outline-regexp org-outline-regexp)
8154 (outline-level 'org-outline-level)
8155 (org-odd-levels-only nil) n)
8156 (save-excursion
8157 (goto-char (point-min))
8158 (while (re-search-forward "^\\*\\*+ " nil t)
8159 (setq n (/ (1- (length (match-string 0))) 2))
8160 (while (>= (setq n (1- n)) 0)
8161 (org-promote))
8162 (end-of-line 1))))))
8164 (defun org-tr-level (n)
8165 "Make N odd if required."
8166 (if org-odd-levels-only (1+ (/ n 2)) n))
8168 ;;; Vertical tree motion, cutting and pasting of subtrees
8170 (defun org-move-subtree-up (&optional arg)
8171 "Move the current subtree up past ARG headlines of the same level."
8172 (interactive "p")
8173 (org-move-subtree-down (- (prefix-numeric-value arg))))
8175 (defun org-move-subtree-down (&optional arg)
8176 "Move the current subtree down past ARG headlines of the same level."
8177 (interactive "p")
8178 (setq arg (prefix-numeric-value arg))
8179 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8180 'org-get-last-sibling))
8181 (ins-point (make-marker))
8182 (cnt (abs arg))
8183 (col (current-column))
8184 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8185 ;; Select the tree
8186 (org-back-to-heading)
8187 (setq beg0 (point))
8188 (save-excursion
8189 (setq ne-beg (org-back-over-empty-lines))
8190 (setq beg (point)))
8191 (save-match-data
8192 (save-excursion (outline-end-of-heading)
8193 (setq folded (outline-invisible-p)))
8194 (outline-end-of-subtree))
8195 (outline-next-heading)
8196 (setq ne-end (org-back-over-empty-lines))
8197 (setq end (point))
8198 (goto-char beg0)
8199 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8200 ;; include less whitespace
8201 (save-excursion
8202 (goto-char beg)
8203 (forward-line (- ne-beg ne-end))
8204 (setq beg (point))))
8205 ;; Find insertion point, with error handling
8206 (while (> cnt 0)
8207 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8208 (progn (goto-char beg0)
8209 (user-error "Cannot move past superior level or buffer limit")))
8210 (setq cnt (1- cnt)))
8211 (if (> arg 0)
8212 ;; Moving forward - still need to move over subtree
8213 (progn (org-end-of-subtree t t)
8214 (save-excursion
8215 (org-back-over-empty-lines)
8216 (or (bolp) (newline)))))
8217 (setq ne-ins (org-back-over-empty-lines))
8218 (move-marker ins-point (point))
8219 (setq txt (buffer-substring beg end))
8220 (org-save-markers-in-region beg end)
8221 (delete-region beg end)
8222 (org-remove-empty-overlays-at beg)
8223 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8224 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8225 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8226 (let ((bbb (point)))
8227 (insert-before-markers txt)
8228 (org-reinstall-markers-in-region bbb)
8229 (move-marker ins-point bbb))
8230 (or (bolp) (insert "\n"))
8231 (setq ins-end (point))
8232 (goto-char ins-point)
8233 (org-skip-whitespace)
8234 (when (and (< arg 0)
8235 (org-first-sibling-p)
8236 (> ne-ins ne-beg))
8237 ;; Move whitespace back to beginning
8238 (save-excursion
8239 (goto-char ins-end)
8240 (let ((kill-whole-line t))
8241 (kill-line (- ne-ins ne-beg)) (point)))
8242 (insert (make-string (- ne-ins ne-beg) ?\n)))
8243 (move-marker ins-point nil)
8244 (if folded
8245 (hide-subtree)
8246 (org-show-entry)
8247 (show-children)
8248 (org-cycle-hide-drawers 'children))
8249 (org-clean-visibility-after-subtree-move)
8250 ;; move back to the initial column we were at
8251 (move-to-column col)))
8253 (defvar org-subtree-clip ""
8254 "Clipboard for cut and paste of subtrees.
8255 This is actually only a copy of the kill, because we use the normal kill
8256 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8258 (defvar org-subtree-clip-folded nil
8259 "Was the last copied subtree folded?
8260 This is used to fold the tree back after pasting.")
8262 (defun org-cut-subtree (&optional n)
8263 "Cut the current subtree into the clipboard.
8264 With prefix arg N, cut this many sequential subtrees.
8265 This is a short-hand for marking the subtree and then cutting it."
8266 (interactive "p")
8267 (org-copy-subtree n 'cut))
8269 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8270 "Copy the current subtree it in the clipboard.
8271 With prefix arg N, copy this many sequential subtrees.
8272 This is a short-hand for marking the subtree and then copying it.
8273 If CUT is non-nil, actually cut the subtree.
8274 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8275 of some markers in the region, even if CUT is non-nil. This is
8276 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8277 (interactive "p")
8278 (let (beg end folded (beg0 (point)))
8279 (if (org-called-interactively-p 'any)
8280 (org-back-to-heading nil) ; take what looks like a subtree
8281 (org-back-to-heading t)) ; take what is really there
8282 (setq beg (point))
8283 (skip-chars-forward " \t\r\n")
8284 (save-match-data
8285 (if nosubtrees
8286 (outline-next-heading)
8287 (save-excursion (outline-end-of-heading)
8288 (setq folded (outline-invisible-p)))
8289 (condition-case nil
8290 (org-forward-heading-same-level (1- n) t)
8291 (error nil))
8292 (org-end-of-subtree t t)))
8293 (setq end (point))
8294 (goto-char beg0)
8295 (when (> end beg)
8296 (setq org-subtree-clip-folded folded)
8297 (when (or cut force-store-markers)
8298 (org-save-markers-in-region beg end))
8299 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8300 (setq org-subtree-clip (current-kill 0))
8301 (message "%s: Subtree(s) with %d characters"
8302 (if cut "Cut" "Copied")
8303 (length org-subtree-clip)))))
8305 (defun org-paste-subtree (&optional level tree for-yank)
8306 "Paste the clipboard as a subtree, with modification of headline level.
8307 The entire subtree is promoted or demoted in order to match a new headline
8308 level.
8310 If the cursor is at the beginning of a headline, the same level as
8311 that headline is used to paste the tree.
8313 If not, the new level is derived from the *visible* headings
8314 before and after the insertion point, and taken to be the inferior headline
8315 level of the two. So if the previous visible heading is level 3 and the
8316 next is level 4 (or vice versa), level 4 will be used for insertion.
8317 This makes sure that the subtree remains an independent subtree and does
8318 not swallow low level entries.
8320 You can also force a different level, either by using a numeric prefix
8321 argument, or by inserting the heading marker by hand. For example, if the
8322 cursor is after \"*****\", then the tree will be shifted to level 5.
8324 If optional TREE is given, use this text instead of the kill ring.
8326 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8327 move back over whitespace before inserting, and move point to the end of
8328 the inserted text when done."
8329 (interactive "P")
8330 (setq tree (or tree (and kill-ring (current-kill 0))))
8331 (unless (org-kill-is-subtree-p tree)
8332 (user-error "%s"
8333 (substitute-command-keys
8334 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8335 (org-with-limited-levels
8336 (let* ((visp (not (outline-invisible-p)))
8337 (txt tree)
8338 (^re_ "\\(\\*+\\)[ \t]*")
8339 (old-level (if (string-match org-outline-regexp-bol txt)
8340 (- (match-end 0) (match-beginning 0) 1)
8341 -1))
8342 (force-level (cond (level (prefix-numeric-value level))
8343 ((and (looking-at "[ \t]*$")
8344 (string-match
8345 "^\\*+$" (buffer-substring
8346 (point-at-bol) (point))))
8347 (- (match-end 1) (match-beginning 1)))
8348 ((and (bolp)
8349 (looking-at org-outline-regexp))
8350 (- (match-end 0) (point) 1))))
8351 (previous-level (save-excursion
8352 (condition-case nil
8353 (progn
8354 (outline-previous-visible-heading 1)
8355 (if (looking-at ^re_)
8356 (- (match-end 0) (match-beginning 0) 1)
8358 (error 1))))
8359 (next-level (save-excursion
8360 (condition-case nil
8361 (progn
8362 (or (looking-at org-outline-regexp)
8363 (outline-next-visible-heading 1))
8364 (if (looking-at ^re_)
8365 (- (match-end 0) (match-beginning 0) 1)
8367 (error 1))))
8368 (new-level (or force-level (max previous-level next-level)))
8369 (shift (if (or (= old-level -1)
8370 (= new-level -1)
8371 (= old-level new-level))
8373 (- new-level old-level)))
8374 (delta (if (> shift 0) -1 1))
8375 (func (if (> shift 0) 'org-demote 'org-promote))
8376 (org-odd-levels-only nil)
8377 beg end newend)
8378 ;; Remove the forced level indicator
8379 (if force-level
8380 (delete-region (point-at-bol) (point)))
8381 ;; Paste
8382 (beginning-of-line (if (bolp) 1 2))
8383 (setq beg (point))
8384 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8385 (insert-before-markers txt)
8386 (unless (string-match "\n\\'" txt) (insert "\n"))
8387 (setq newend (point))
8388 (org-reinstall-markers-in-region beg)
8389 (setq end (point))
8390 (goto-char beg)
8391 (skip-chars-forward " \t\n\r")
8392 (setq beg (point))
8393 (if (and (outline-invisible-p) visp)
8394 (save-excursion (outline-show-heading)))
8395 ;; Shift if necessary
8396 (unless (= shift 0)
8397 (save-restriction
8398 (narrow-to-region beg end)
8399 (while (not (= shift 0))
8400 (org-map-region func (point-min) (point-max))
8401 (setq shift (+ delta shift)))
8402 (goto-char (point-min))
8403 (setq newend (point-max))))
8404 (when (or (org-called-interactively-p 'interactive) for-yank)
8405 (message "Clipboard pasted as level %d subtree" new-level))
8406 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8407 kill-ring
8408 (eq org-subtree-clip (current-kill 0))
8409 org-subtree-clip-folded)
8410 ;; The tree was folded before it was killed/copied
8411 (hide-subtree))
8412 (and for-yank (goto-char newend)))))
8414 (defun org-kill-is-subtree-p (&optional txt)
8415 "Check if the current kill is an outline subtree, or a set of trees.
8416 Returns nil if kill does not start with a headline, or if the first
8417 headline level is not the largest headline level in the tree.
8418 So this will actually accept several entries of equal levels as well,
8419 which is OK for `org-paste-subtree'.
8420 If optional TXT is given, check this string instead of the current kill."
8421 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8422 (re (org-get-limited-outline-regexp))
8423 (^re (concat "^" re))
8424 (start-level (and kill
8425 (string-match
8426 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8427 kill)
8428 (- (match-end 2) (match-beginning 2) 1)))
8429 (start (1+ (or (match-beginning 2) -1))))
8430 (if (not start-level)
8431 (progn
8432 nil) ;; does not even start with a heading
8433 (catch 'exit
8434 (while (setq start (string-match ^re kill (1+ start)))
8435 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8436 (throw 'exit nil)))
8437 t))))
8439 (defvar org-markers-to-move nil
8440 "Markers that should be moved with a cut-and-paste operation.
8441 Those markers are stored together with their positions relative to
8442 the start of the region.")
8444 (defun org-save-markers-in-region (beg end)
8445 "Check markers in region.
8446 If these markers are between BEG and END, record their position relative
8447 to BEG, so that after moving the block of text, we can put the markers back
8448 into place.
8449 This function gets called just before an entry or tree gets cut from the
8450 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8451 called immediately, to move the markers with the entries."
8452 (setq org-markers-to-move nil)
8453 (when (featurep 'org-clock)
8454 (org-clock-save-markers-for-cut-and-paste beg end))
8455 (when (featurep 'org-agenda)
8456 (org-agenda-save-markers-for-cut-and-paste beg end)))
8458 (defun org-check-and-save-marker (marker beg end)
8459 "Check if MARKER is between BEG and END.
8460 If yes, remember the marker and the distance to BEG."
8461 (when (and (marker-buffer marker)
8462 (equal (marker-buffer marker) (current-buffer)))
8463 (if (and (>= marker beg) (< marker end))
8464 (push (cons marker (- marker beg)) org-markers-to-move))))
8466 (defun org-reinstall-markers-in-region (beg)
8467 "Move all remembered markers to their position relative to BEG."
8468 (mapc (lambda (x)
8469 (move-marker (car x) (+ beg (cdr x))))
8470 org-markers-to-move)
8471 (setq org-markers-to-move nil))
8473 (defun org-narrow-to-subtree ()
8474 "Narrow buffer to the current subtree."
8475 (interactive)
8476 (save-excursion
8477 (save-match-data
8478 (org-with-limited-levels
8479 (narrow-to-region
8480 (progn (org-back-to-heading t) (point))
8481 (progn (org-end-of-subtree t t)
8482 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8483 (point)))))))
8485 (defun org-narrow-to-block ()
8486 "Narrow buffer to the current block."
8487 (interactive)
8488 (let* ((case-fold-search t)
8489 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8490 "^[ \t]*#\\+end_.*")))
8491 (if blockp
8492 (narrow-to-region (car blockp) (cdr blockp))
8493 (user-error "Not in a block"))))
8495 (eval-when-compile
8496 (defvar org-property-drawer-re))
8498 (defvar org-property-start-re) ;; defined below
8499 (defun org-clone-subtree-with-time-shift (n &optional shift)
8500 "Clone the task (subtree) at point N times.
8501 The clones will be inserted as siblings.
8503 In interactive use, the user will be prompted for the number of
8504 clones to be produced. If the entry has a timestamp, the user
8505 will also be prompted for a time shift, which may be a repeater
8506 as used in time stamps, for example `+3d'. To disable this,
8507 you can call the function with a universal prefix argument.
8509 When a valid repeater is given and the entry contains any time
8510 stamps, the clones will become a sequence in time, with time
8511 stamps in the subtree shifted for each clone produced. If SHIFT
8512 is nil or the empty string, time stamps will be left alone. The
8513 ID property of the original subtree is removed.
8515 If the original subtree did contain time stamps with a repeater,
8516 the following will happen:
8517 - the repeater will be removed in each clone
8518 - an additional clone will be produced, with the current, unshifted
8519 date(s) in the entry.
8520 - the original entry will be placed *after* all the clones, with
8521 repeater intact.
8522 - the start days in the repeater in the original entry will be shifted
8523 to past the last clone.
8524 In this way you can spell out a number of instances of a repeating task,
8525 and still retain the repeater to cover future instances of the task."
8526 (interactive "nNumber of clones to produce: ")
8527 (let ((shift
8528 (or shift
8529 (if (and (not (equal current-prefix-arg '(4)))
8530 (save-excursion
8531 (re-search-forward org-ts-regexp-both
8532 (save-excursion
8533 (org-end-of-subtree t)
8534 (point)) t)))
8535 (read-from-minibuffer
8536 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8537 ""))) ;; No time shift
8538 (n-no-remove -1)
8539 (drawer-re org-drawer-regexp)
8540 beg end template task idprop
8541 shift-n shift-what doshift nmin nmax)
8542 (if (not (and (integerp n) (> n 0)))
8543 (error "Invalid number of replications %s" n))
8544 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8545 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8546 shift)))
8547 (error "Invalid shift specification %s" shift))
8548 (when doshift
8549 (setq shift-n (string-to-number (match-string 1 shift))
8550 shift-what (cdr (assoc (match-string 2 shift)
8551 '(("d" . day) ("w" . week)
8552 ("m" . month) ("y" . year))))))
8553 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8554 (setq nmin 1 nmax n)
8555 (org-back-to-heading t)
8556 (setq beg (point))
8557 (setq idprop (org-entry-get nil "ID"))
8558 (org-end-of-subtree t t)
8559 (or (bolp) (insert "\n"))
8560 (setq end (point))
8561 (setq template (buffer-substring beg end))
8562 (when (and doshift
8563 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8564 (delete-region beg end)
8565 (setq end beg)
8566 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8567 (goto-char end)
8568 (loop for n from nmin to nmax do
8569 ;; prepare clone
8570 (with-temp-buffer
8571 (insert template)
8572 (org-mode)
8573 (goto-char (point-min))
8574 (org-show-subtree)
8575 (and idprop (if org-clone-delete-id
8576 (org-entry-delete nil "ID")
8577 (org-id-get-create t)))
8578 (unless (= n 0)
8579 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8580 (kill-whole-line))
8581 (goto-char (point-min))
8582 (while (re-search-forward drawer-re nil t)
8583 (org-remove-empty-drawer-at (point))))
8584 (goto-char (point-min))
8585 (when doshift
8586 (while (re-search-forward org-ts-regexp-both nil t)
8587 (org-timestamp-change (* n shift-n) shift-what))
8588 (unless (= n n-no-remove)
8589 (goto-char (point-min))
8590 (while (re-search-forward org-ts-regexp nil t)
8591 (save-excursion
8592 (goto-char (match-beginning 0))
8593 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8594 (delete-region (match-beginning 1) (match-end 1)))))))
8595 (setq task (buffer-string)))
8596 (insert task))
8597 (goto-char beg)))
8599 ;;; Outline Sorting
8601 (defun org-sort (with-case)
8602 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8603 Optional argument WITH-CASE means sort case-sensitively."
8604 (interactive "P")
8605 (cond
8606 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8607 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8609 (org-call-with-arg 'org-sort-entries with-case))))
8611 (defun org-sort-remove-invisible (s)
8612 "Remove invisible links from string S."
8613 (remove-text-properties 0 (length s) org-rm-props s)
8614 (while (string-match org-bracket-link-regexp s)
8615 (setq s (replace-match (if (match-end 2)
8616 (match-string 3 s)
8617 (match-string 1 s)) t t s)))
8618 (let ((st (format " %s " s)))
8619 (while (string-match org-emph-re st)
8620 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8621 (setq s (substring st 1 -1)))
8624 (defvar org-priority-regexp) ; defined later in the file
8626 (defvar org-after-sorting-entries-or-items-hook nil
8627 "Hook that is run after a bunch of entries or items have been sorted.
8628 When children are sorted, the cursor is in the parent line when this
8629 hook gets called. When a region or a plain list is sorted, the cursor
8630 will be in the first entry of the sorted region/list.")
8632 (defun org-sort-entries
8633 (&optional with-case sorting-type getkey-func compare-func property)
8634 "Sort entries on a certain level of an outline tree.
8635 If there is an active region, the entries in the region are sorted.
8636 Else, if the cursor is before the first entry, sort the top-level items.
8637 Else, the children of the entry at point are sorted.
8639 Sorting can be alphabetically, numerically, by date/time as given by
8640 a time stamp, by a property, by priority order, or by a custom function.
8642 The command prompts for the sorting type unless it has been given to the
8643 function through the SORTING-TYPE argument, which needs to be a character,
8644 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8645 precise meaning of each character:
8647 n Numerically, by converting the beginning of the entry/item to a number.
8648 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8649 o By order of TODO keywords.
8650 t By date/time, either the first active time stamp in the entry, or, if
8651 none exist, by the first inactive one.
8652 s By the scheduled date/time.
8653 d By deadline date/time.
8654 c By creation time, which is assumed to be the first inactive time stamp
8655 at the beginning of a line.
8656 p By priority according to the cookie.
8657 r By the value of a property.
8659 Capital letters will reverse the sort order.
8661 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8662 called with point at the beginning of the record. It must return either
8663 a string or a number that should serve as the sorting key for that record.
8665 Comparing entries ignores case by default. However, with an optional argument
8666 WITH-CASE, the sorting considers case as well.
8668 Sorting is done against the visible part of the headlines, it ignores hidden
8669 links.
8671 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8672 (interactive "P")
8673 (let ((case-func (if with-case 'identity 'downcase))
8674 (cmstr
8675 ;; The clock marker is lost when using `sort-subr', let's
8676 ;; store the clocking string.
8677 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8678 (save-excursion
8679 (goto-char org-clock-marker)
8680 (looking-back "^.*") (match-string-no-properties 0))))
8681 start beg end stars re re2
8682 txt what tmp)
8683 ;; Find beginning and end of region to sort
8684 (cond
8685 ((org-region-active-p)
8686 ;; we will sort the region
8687 (setq end (region-end)
8688 what "region")
8689 (goto-char (region-beginning))
8690 (if (not (org-at-heading-p)) (outline-next-heading))
8691 (setq start (point)))
8692 ((or (org-at-heading-p)
8693 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8694 ;; we will sort the children of the current headline
8695 (org-back-to-heading)
8696 (setq start (point)
8697 end (progn (org-end-of-subtree t t)
8698 (or (bolp) (insert "\n"))
8699 (org-back-over-empty-lines)
8700 (point))
8701 what "children")
8702 (goto-char start)
8703 (show-subtree)
8704 (outline-next-heading))
8706 ;; we will sort the top-level entries in this file
8707 (goto-char (point-min))
8708 (or (org-at-heading-p) (outline-next-heading))
8709 (setq start (point))
8710 (goto-char (point-max))
8711 (beginning-of-line 1)
8712 (when (looking-at ".*?\\S-")
8713 ;; File ends in a non-white line
8714 (end-of-line 1)
8715 (insert "\n"))
8716 (setq end (point-max))
8717 (setq what "top-level")
8718 (goto-char start)
8719 (show-all)))
8721 (setq beg (point))
8722 (if (>= beg end) (user-error "Nothing to sort"))
8724 (looking-at "\\(\\*+\\)")
8725 (setq stars (match-string 1)
8726 re (concat "^" (regexp-quote stars) " +")
8727 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8728 txt (buffer-substring beg end))
8729 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8730 (if (and (not (equal stars "*")) (string-match re2 txt))
8731 (user-error "Region to sort contains a level above the first entry"))
8733 (unless sorting-type
8734 (message
8735 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8736 [t]ime [s]cheduled [d]eadline [c]reated
8737 A/N/P/R/O/F/T/S/D/C means reversed:"
8738 what)
8739 (setq sorting-type (read-char-exclusive))
8741 (unless getkey-func
8742 (and (= (downcase sorting-type) ?f)
8743 (setq getkey-func
8744 (org-icompleting-read "Sort using function: "
8745 obarray 'fboundp t nil nil))
8746 (setq getkey-func (intern getkey-func))))
8748 (and (= (downcase sorting-type) ?r)
8749 (not property)
8750 (setq property
8751 (org-icompleting-read "Property: "
8752 (mapcar 'list (org-buffer-property-keys t))
8753 nil t))))
8755 (message "Sorting entries...")
8757 (save-restriction
8758 (narrow-to-region start end)
8759 (let ((dcst (downcase sorting-type))
8760 (case-fold-search nil)
8761 (now (current-time)))
8762 (sort-subr
8763 (/= dcst sorting-type)
8764 ;; This function moves to the beginning character of the "record" to
8765 ;; be sorted.
8766 (lambda nil
8767 (if (re-search-forward re nil t)
8768 (goto-char (match-beginning 0))
8769 (goto-char (point-max))))
8770 ;; This function moves to the last character of the "record" being
8771 ;; sorted.
8772 (lambda nil
8773 (save-match-data
8774 (condition-case nil
8775 (outline-forward-same-level 1)
8776 (error
8777 (goto-char (point-max))))))
8778 ;; This function returns the value that gets sorted against.
8779 (lambda nil
8780 (cond
8781 ((= dcst ?n)
8782 (if (looking-at org-complex-heading-regexp)
8783 (string-to-number (org-sort-remove-invisible (match-string 4)))
8784 nil))
8785 ((= dcst ?a)
8786 (if (looking-at org-complex-heading-regexp)
8787 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8788 nil))
8789 ((= dcst ?t)
8790 (let ((end (save-excursion (outline-next-heading) (point))))
8791 (if (or (re-search-forward org-ts-regexp end t)
8792 (re-search-forward org-ts-regexp-both end t))
8793 (org-time-string-to-seconds (match-string 0))
8794 (org-float-time now))))
8795 ((= dcst ?c)
8796 (let ((end (save-excursion (outline-next-heading) (point))))
8797 (if (re-search-forward
8798 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8799 end t)
8800 (org-time-string-to-seconds (match-string 0))
8801 (org-float-time now))))
8802 ((= dcst ?s)
8803 (let ((end (save-excursion (outline-next-heading) (point))))
8804 (if (re-search-forward org-scheduled-time-regexp end t)
8805 (org-time-string-to-seconds (match-string 1))
8806 (org-float-time now))))
8807 ((= dcst ?d)
8808 (let ((end (save-excursion (outline-next-heading) (point))))
8809 (if (re-search-forward org-deadline-time-regexp end t)
8810 (org-time-string-to-seconds (match-string 1))
8811 (org-float-time now))))
8812 ((= dcst ?p)
8813 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8814 (string-to-char (match-string 2))
8815 org-default-priority))
8816 ((= dcst ?r)
8817 (or (org-entry-get nil property) ""))
8818 ((= dcst ?o)
8819 (if (looking-at org-complex-heading-regexp)
8820 (- 9999 (length (member (match-string 2)
8821 org-todo-keywords-1)))))
8822 ((= dcst ?f)
8823 (if getkey-func
8824 (progn
8825 (setq tmp (funcall getkey-func))
8826 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8827 tmp)
8828 (error "Invalid key function `%s'" getkey-func)))
8829 (t (error "Invalid sorting type `%c'" sorting-type))))
8831 (cond
8832 ((= dcst ?a) 'string<)
8833 ((= dcst ?f) compare-func)
8834 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8835 (run-hooks 'org-after-sorting-entries-or-items-hook)
8836 ;; Reset the clock marker if needed
8837 (when cmstr
8838 (save-excursion
8839 (goto-char start)
8840 (search-forward cmstr nil t)
8841 (move-marker org-clock-marker (point))))
8842 (message "Sorting entries...done")))
8844 (defun org-do-sort (table what &optional with-case sorting-type)
8845 "Sort TABLE of WHAT according to SORTING-TYPE.
8846 The user will be prompted for the SORTING-TYPE if the call to this
8847 function does not specify it. WHAT is only for the prompt, to indicate
8848 what is being sorted. The sorting key will be extracted from
8849 the car of the elements of the table.
8850 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8851 (unless sorting-type
8852 (message
8853 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8854 what)
8855 (setq sorting-type (read-char-exclusive)))
8856 (let ((dcst (downcase sorting-type))
8857 extractfun comparefun)
8858 ;; Define the appropriate functions
8859 (cond
8860 ((= dcst ?n)
8861 (setq extractfun 'string-to-number
8862 comparefun (if (= dcst sorting-type) '< '>)))
8863 ((= dcst ?a)
8864 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8865 (lambda(x) (downcase (org-sort-remove-invisible x))))
8866 comparefun (if (= dcst sorting-type)
8867 'string<
8868 (lambda (a b) (and (not (string< a b))
8869 (not (string= a b)))))))
8870 ((= dcst ?t)
8871 (setq extractfun
8872 (lambda (x)
8873 (if (or (string-match org-ts-regexp x)
8874 (string-match org-ts-regexp-both x))
8875 (org-float-time
8876 (org-time-string-to-time (match-string 0 x)))
8878 comparefun (if (= dcst sorting-type) '< '>)))
8879 (t (error "Invalid sorting type `%c'" sorting-type)))
8881 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8882 table)
8883 (lambda (a b) (funcall comparefun (car a) (car b))))))
8886 ;;; The orgstruct minor mode
8888 ;; Define a minor mode which can be used in other modes in order to
8889 ;; integrate the org-mode structure editing commands.
8891 ;; This is really a hack, because the org-mode structure commands use
8892 ;; keys which normally belong to the major mode. Here is how it
8893 ;; works: The minor mode defines all the keys necessary to operate the
8894 ;; structure commands, but wraps the commands into a function which
8895 ;; tests if the cursor is currently at a headline or a plain list
8896 ;; item. If that is the case, the structure command is used,
8897 ;; temporarily setting many Org-mode variables like regular
8898 ;; expressions for filling etc. However, when any of those keys is
8899 ;; used at a different location, function uses `key-binding' to look
8900 ;; up if the key has an associated command in another currently active
8901 ;; keymap (minor modes, major mode, global), and executes that
8902 ;; command. There might be problems if any of the keys is otherwise
8903 ;; used as a prefix key.
8905 (defcustom orgstruct-heading-prefix-regexp ""
8906 "Regexp that matches the custom prefix of Org headlines in
8907 orgstruct(++)-mode."
8908 :group 'org
8909 :version "24.4"
8910 :package-version '(Org . "8.3")
8911 :type 'regexp)
8912 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8914 (defcustom orgstruct-setup-hook nil
8915 "Hook run after orgstruct-mode-map is filled."
8916 :group 'org
8917 :version "24.4"
8918 :package-version '(Org . "8.0")
8919 :type 'hook)
8921 (defvar orgstruct-initialized nil)
8923 (defvar org-local-vars nil
8924 "List of local variables, for use by `orgstruct-mode'.")
8926 ;;;###autoload
8927 (define-minor-mode orgstruct-mode
8928 "Toggle the minor mode `orgstruct-mode'.
8929 This mode is for using Org-mode structure commands in other
8930 modes. The following keys behave as if Org-mode were active, if
8931 the cursor is on a headline, or on a plain list item (both as
8932 defined by Org-mode)."
8933 nil " OrgStruct" (make-sparse-keymap)
8934 (funcall (if orgstruct-mode
8935 'add-to-invisibility-spec
8936 'remove-from-invisibility-spec)
8937 '(outline . t))
8938 (when orgstruct-mode
8939 (org-load-modules-maybe)
8940 (unless orgstruct-initialized
8941 (orgstruct-setup)
8942 (setq orgstruct-initialized t))))
8944 ;;;###autoload
8945 (defun turn-on-orgstruct ()
8946 "Unconditionally turn on `orgstruct-mode'."
8947 (orgstruct-mode 1))
8949 (defvar org-fb-vars nil)
8950 (make-variable-buffer-local 'org-fb-vars)
8951 (defun orgstruct++-mode (&optional arg)
8952 "Toggle `orgstruct-mode', the enhanced version of it.
8953 In addition to setting orgstruct-mode, this also exports all
8954 indentation and autofilling variables from org-mode into the
8955 buffer. It will also recognize item context in multiline items."
8956 (interactive "P")
8957 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8958 (if (< arg 1)
8959 (progn (orgstruct-mode -1)
8960 (mapc (lambda(v)
8961 (org-set-local (car v)
8962 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8963 org-fb-vars))
8964 (orgstruct-mode 1)
8965 (setq org-fb-vars nil)
8966 (unless org-local-vars
8967 (setq org-local-vars (org-get-local-variables)))
8968 (let (var val)
8969 (mapc
8970 (lambda (x)
8971 (when (string-match
8972 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8973 (symbol-name (car x)))
8974 (setq var (car x) val (nth 1 x))
8975 (push (list var `(quote ,(eval var))) org-fb-vars)
8976 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8977 org-local-vars)
8978 (org-set-local 'orgstruct-is-++ t))))
8980 (defvar orgstruct-is-++ nil
8981 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8982 (make-variable-buffer-local 'orgstruct-is-++)
8984 ;;;###autoload
8985 (defun turn-on-orgstruct++ ()
8986 "Unconditionally turn on `orgstruct++-mode'."
8987 (orgstruct++-mode 1))
8989 (defun orgstruct-error ()
8990 "Error when there is no default binding for a structure key."
8991 (interactive)
8992 (funcall (if (fboundp 'user-error)
8993 'user-error
8994 'error)
8995 "This key has no function outside structure elements"))
8997 (defun orgstruct-setup ()
8998 "Setup orgstruct keymap."
8999 (dolist (cell '((org-demote . t)
9000 (org-metaleft . t)
9001 (org-metaright . t)
9002 (org-promote . t)
9003 (org-shiftmetaleft . t)
9004 (org-shiftmetaright . t)
9005 org-backward-element
9006 org-backward-heading-same-level
9007 org-ctrl-c-ret
9008 org-ctrl-c-minus
9009 org-ctrl-c-star
9010 org-cycle
9011 org-forward-heading-same-level
9012 org-insert-heading
9013 org-insert-heading-respect-content
9014 org-kill-note-or-show-branches
9015 org-mark-subtree
9016 org-meta-return
9017 org-metadown
9018 org-metaup
9019 org-narrow-to-subtree
9020 org-promote-subtree
9021 org-reveal
9022 org-shiftdown
9023 org-shiftleft
9024 org-shiftmetadown
9025 org-shiftmetaup
9026 org-shiftright
9027 org-shifttab
9028 org-shifttab
9029 org-shiftup
9030 org-show-subtree
9031 org-sort
9032 org-up-element
9033 outline-demote
9034 outline-next-visible-heading
9035 outline-previous-visible-heading
9036 outline-promote
9037 outline-up-heading
9038 show-children))
9039 (let ((f (or (car-safe cell) cell))
9040 (disable-when-heading-prefix (cdr-safe cell)))
9041 (when (fboundp f)
9042 (let ((new-bindings))
9043 (dolist (binding (nconc (where-is-internal f org-mode-map)
9044 (where-is-internal f outline-mode-map)))
9045 (push binding new-bindings)
9046 ;; TODO use local-function-key-map
9047 (dolist (rep '(("<tab>" . "TAB")
9048 ("<return>" . "RET")
9049 ("<escape>" . "ESC")
9050 ("<delete>" . "DEL")))
9051 (setq binding (read-kbd-macro
9052 (let ((case-fold-search))
9053 (replace-regexp-in-string
9054 (regexp-quote (cdr rep))
9055 (car rep)
9056 (key-description binding)))))
9057 (pushnew binding new-bindings :test 'equal)))
9058 (dolist (binding new-bindings)
9059 (let ((key (lookup-key orgstruct-mode-map binding)))
9060 (when (or (not key) (numberp key))
9061 (condition-case nil
9062 (org-defkey orgstruct-mode-map
9063 binding
9064 (orgstruct-make-binding f binding disable-when-heading-prefix))
9065 (error nil)))))))))
9066 (run-hooks 'orgstruct-setup-hook))
9068 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9069 "Create a function for binding in the structure minor mode.
9070 FUN is the command to call inside a table. KEY is the key that
9071 should be checked in for a command to execute outside of tables.
9072 Non-nil `disable-when-heading-prefix' means to disable the command
9073 if `orgstruct-heading-prefix-regexp' is not empty."
9074 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9075 (let ((nname name)
9076 (i 0))
9077 (while (fboundp (intern nname))
9078 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9079 (setq name (intern nname)))
9080 (eval
9081 (let ((bindings '((org-heading-regexp
9082 (concat "^"
9083 orgstruct-heading-prefix-regexp
9084 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9085 (org-outline-regexp
9086 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9087 (org-outline-regexp-bol
9088 (concat "^" org-outline-regexp))
9089 (outline-regexp org-outline-regexp)
9090 (outline-heading-end-regexp "\n")
9091 (outline-level 'org-outline-level)
9092 (outline-heading-alist))))
9093 `(defun ,name (arg)
9094 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9095 "Outside of structure, run the binding of `"
9096 (key-description key) "'."
9097 (when disable-when-heading-prefix
9098 (concat
9099 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9100 "back to the default binding due to limitations of Org's implementation of\n"
9101 "`" (symbol-name fun) "'.")))
9102 (interactive "p")
9103 (let* ((disable
9104 ,(and disable-when-heading-prefix
9105 '(not (string= orgstruct-heading-prefix-regexp ""))))
9106 (fallback
9107 (or disable
9108 (not
9109 (let* ,bindings
9110 (org-context-p 'headline 'item
9111 ,(when (memq fun
9112 '(org-insert-heading
9113 org-insert-heading-respect-content
9114 org-meta-return))
9115 '(when orgstruct-is-++
9116 'item-body))))))))
9117 (if fallback
9118 (let* ((orgstruct-mode)
9119 (binding
9120 (loop with key = ,key
9121 for rep in
9122 '(nil
9123 ("<\\([^>]*\\)tab>" . "\\1TAB")
9124 ("<\\([^>]*\\)return>" . "\\1RET")
9125 ("<\\([^>]*\\)escape>" . "\\1ESC")
9126 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9128 (when rep
9129 (setq key (read-kbd-macro
9130 (let ((case-fold-search))
9131 (replace-regexp-in-string
9132 (car rep)
9133 (cdr rep)
9134 (key-description key))))))
9135 thereis (key-binding key))))
9136 (if (keymapp binding)
9137 (set-transient-map binding)
9138 (let ((func (or binding
9139 (unless disable
9140 'orgstruct-error))))
9141 (when func
9142 (call-interactively func)))))
9143 (org-run-like-in-org-mode
9144 (lambda ()
9145 (interactive)
9146 (let* ,bindings
9147 (call-interactively ',fun)))))))))
9148 name))
9150 (defun org-contextualize-keys (alist contexts)
9151 "Return valid elements in ALIST depending on CONTEXTS.
9153 `org-agenda-custom-commands' or `org-capture-templates' are the
9154 values used for ALIST, and `org-agenda-custom-commands-contexts'
9155 or `org-capture-templates-contexts' are the associated contexts
9156 definitions."
9157 (let ((contexts
9158 ;; normalize contexts
9159 (mapcar
9160 (lambda(c) (cond ((listp (cadr c))
9161 (list (car c) (car c) (cadr c)))
9162 ((string= "" (cadr c))
9163 (list (car c) (car c) (caddr c)))
9164 (t c))) contexts))
9165 (a alist) c r s)
9166 ;; loop over all commands or templates
9167 (while (setq c (pop a))
9168 (let (vrules repl)
9169 (cond
9170 ((not (assoc (car c) contexts))
9171 (push c r))
9172 ((and (assoc (car c) contexts)
9173 (setq vrules (org-contextualize-validate-key
9174 (car c) contexts)))
9175 (mapc (lambda (vr)
9176 (when (not (equal (car vr) (cadr vr)))
9177 (setq repl vr))) vrules)
9178 (if (not repl) (push c r)
9179 (push (cadr repl) s)
9180 (push
9181 (cons (car c)
9182 (cdr (or (assoc (cadr repl) alist)
9183 (error "Undefined key `%s' as contextual replacement for `%s'"
9184 (cadr repl) (car c)))))
9185 r))))))
9186 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9187 (delq
9189 (delete-dups
9190 (mapcar (lambda (x)
9191 (let ((tpl (car x)))
9192 (when (not (delq
9194 (mapcar (lambda(y)
9195 (equal y tpl)) s))) x)))
9196 (reverse r))))))
9198 (defun org-contextualize-validate-key (key contexts)
9199 "Check CONTEXTS for agenda or capture KEY."
9200 (let (r rr res)
9201 (while (setq r (pop contexts))
9202 (mapc
9203 (lambda (rr)
9204 (when
9205 (and (equal key (car r))
9206 (if (functionp rr) (funcall rr)
9207 (or (and (eq (car rr) 'in-file)
9208 (buffer-file-name)
9209 (string-match (cdr rr) (buffer-file-name)))
9210 (and (eq (car rr) 'in-mode)
9211 (string-match (cdr rr) (symbol-name major-mode)))
9212 (and (eq (car rr) 'in-buffer)
9213 (string-match (cdr rr) (buffer-name)))
9214 (when (and (eq (car rr) 'not-in-file)
9215 (buffer-file-name))
9216 (not (string-match (cdr rr) (buffer-file-name))))
9217 (when (eq (car rr) 'not-in-mode)
9218 (not (string-match (cdr rr) (symbol-name major-mode))))
9219 (when (eq (car rr) 'not-in-buffer)
9220 (not (string-match (cdr rr) (buffer-name)))))))
9221 (push r res)))
9222 (car (last r))))
9223 (delete-dups (delq nil res))))
9225 (defun org-context-p (&rest contexts)
9226 "Check if local context is any of CONTEXTS.
9227 Possible values in the list of contexts are `table', `headline', and `item'."
9228 (let ((pos (point)))
9229 (goto-char (point-at-bol))
9230 (prog1 (or (and (memq 'table contexts)
9231 (looking-at "[ \t]*|"))
9232 (and (memq 'headline contexts)
9233 (looking-at org-outline-regexp))
9234 (and (memq 'item contexts)
9235 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9236 (and (memq 'item-body contexts)
9237 (org-in-item-p)))
9238 (goto-char pos))))
9240 (defun org-get-local-variables ()
9241 "Return a list of all local variables in an Org mode buffer."
9242 (let (varlist)
9243 (with-current-buffer (get-buffer-create "*Org tmp*")
9244 (erase-buffer)
9245 (org-mode)
9246 (setq varlist (buffer-local-variables)))
9247 (kill-buffer "*Org tmp*")
9248 (delq nil
9249 (mapcar
9250 (lambda (x)
9251 (setq x
9252 (if (symbolp x)
9253 (list x)
9254 (list (car x) (cdr x))))
9255 (if (and (not (get (car x) 'org-state))
9256 (string-match
9257 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9258 (symbol-name (car x))))
9259 x nil))
9260 varlist))))
9262 (defun org-clone-local-variables (from-buffer &optional regexp)
9263 "Clone local variables from FROM-BUFFER.
9264 Optional argument REGEXP selects variables to clone."
9265 (mapc
9266 (lambda (pair)
9267 (and (symbolp (car pair))
9268 (or (null regexp)
9269 (string-match regexp (symbol-name (car pair))))
9270 (set (make-local-variable (car pair))
9271 (cdr pair))))
9272 (buffer-local-variables from-buffer)))
9274 ;;;###autoload
9275 (defun org-run-like-in-org-mode (cmd)
9276 "Run a command, pretending that the current buffer is in Org-mode.
9277 This will temporarily bind local variables that are typically bound in
9278 Org-mode to the values they have in Org-mode, and then interactively
9279 call CMD."
9280 (org-load-modules-maybe)
9281 (unless org-local-vars
9282 (setq org-local-vars (org-get-local-variables)))
9283 (let (binds)
9284 (dolist (var org-local-vars)
9285 (when (or (not (boundp (car var)))
9286 (eq (symbol-value (car var))
9287 (default-value (car var))))
9288 (push (list (car var) `(quote ,(cadr var))) binds)))
9289 (eval `(let ,binds
9290 (call-interactively (quote ,cmd))))))
9292 ;;;; Archiving
9294 (defun org-get-category (&optional pos force-refresh)
9295 "Get the category applying to position POS."
9296 (save-match-data
9297 (if force-refresh (org-refresh-category-properties))
9298 (let ((pos (or pos (point))))
9299 (or (get-text-property pos 'org-category)
9300 (progn (org-refresh-category-properties)
9301 (get-text-property pos 'org-category))))))
9303 (defun org-refresh-category-properties ()
9304 "Refresh category text properties in the buffer."
9305 (let ((case-fold-search t)
9306 (inhibit-read-only t)
9307 (def-cat (cond
9308 ((null org-category)
9309 (if buffer-file-name
9310 (file-name-sans-extension
9311 (file-name-nondirectory buffer-file-name))
9312 "???"))
9313 ((symbolp org-category) (symbol-name org-category))
9314 (t org-category)))
9315 beg end cat pos optionp)
9316 (org-with-silent-modifications
9317 (save-excursion
9318 (save-restriction
9319 (widen)
9320 (goto-char (point-min))
9321 (put-text-property (point) (point-max) 'org-category def-cat)
9322 (while (re-search-forward
9323 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9324 (setq pos (match-end 0)
9325 optionp (equal (char-after (match-beginning 0)) ?#)
9326 cat (org-trim (match-string 2)))
9327 (if optionp
9328 (setq beg (point-at-bol) end (point-max))
9329 (org-back-to-heading t)
9330 (setq beg (point) end (org-end-of-subtree t t)))
9331 (put-text-property beg end 'org-category cat)
9332 (put-text-property beg end 'org-category-position beg)
9333 (goto-char pos)))))))
9335 (defun org-refresh-properties (dprop tprop)
9336 "Refresh buffer text properties.
9337 DPROP is the drawer property and TPROP is the corresponding text
9338 property to set."
9339 (let ((case-fold-search t)
9340 (inhibit-read-only t) p)
9341 (org-with-silent-modifications
9342 (save-excursion
9343 (save-restriction
9344 (widen)
9345 (goto-char (point-min))
9346 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9347 (setq p (org-match-string-no-properties 1))
9348 (save-excursion
9349 (org-back-to-heading t)
9350 (put-text-property
9351 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9354 ;;;; Link Stuff
9356 ;;; Link abbreviations
9358 (defun org-link-expand-abbrev (link)
9359 "Apply replacements as defined in `org-link-abbrev-alist'."
9360 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9361 (let* ((key (match-string 1 link))
9362 (as (or (assoc key org-link-abbrev-alist-local)
9363 (assoc key org-link-abbrev-alist)))
9364 (tag (and (match-end 2) (match-string 3 link)))
9365 rpl)
9366 (if (not as)
9367 link
9368 (setq rpl (cdr as))
9369 (cond
9370 ((symbolp rpl) (funcall rpl tag))
9371 ((string-match "%(\\([^)]+\\))" rpl)
9372 (replace-match
9373 (save-match-data
9374 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9375 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9376 ((string-match "%h" rpl)
9377 (replace-match (url-hexify-string (or tag "")) t t rpl))
9378 (t (concat rpl tag)))))
9379 link))
9381 ;;; Storing and inserting links
9383 (defvar org-insert-link-history nil
9384 "Minibuffer history for links inserted with `org-insert-link'.")
9386 (defvar org-stored-links nil
9387 "Contains the links stored with `org-store-link'.")
9389 (defvar org-store-link-plist nil
9390 "Plist with info about the most recently link created with `org-store-link'.")
9392 (defvar org-link-protocols nil
9393 "Link protocols added to Org-mode using `org-add-link-type'.")
9395 (defvar org-store-link-functions nil
9396 "List of functions that are called to create and store a link.
9397 Each function will be called in turn until one returns a non-nil
9398 value. Each function should check if it is responsible for creating
9399 this link (for example by looking at the major mode).
9400 If not, it must exit and return nil.
9401 If yes, it should return a non-nil value after a calling
9402 `org-store-link-props' with a list of properties and values.
9403 Special properties are:
9405 :type The link prefix, like \"http\". This must be given.
9406 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9407 This is obligatory as well.
9408 :description Optional default description for the second pair
9409 of brackets in an Org-mode link. The user can still change
9410 this when inserting this link into an Org-mode buffer.
9412 In addition to these, any additional properties can be specified
9413 and then used in capture templates.")
9415 (defun org-add-link-type (type &optional follow export)
9416 "Add TYPE to the list of `org-link-types'.
9417 Re-compute all regular expressions depending on `org-link-types'
9419 FOLLOW and EXPORT are two functions.
9421 FOLLOW should take the link path as the single argument and do whatever
9422 is necessary to follow the link, for example find a file or display
9423 a mail message.
9425 EXPORT should format the link path for export to one of the export formats.
9426 It should be a function accepting three arguments:
9428 path the path of the link, the text after the prefix (like \"http:\")
9429 desc the description of the link, if any, or a description added by
9430 org-export-normalize-links if there is none
9431 format the export format, a symbol like `html' or `latex' or `ascii'..
9433 The function may use the FORMAT information to return different values
9434 depending on the format. The return value will be put literally into
9435 the exported file. If the return value is nil, this means Org should
9436 do what it normally does with links which do not have EXPORT defined.
9438 Org-mode has a built-in default for exporting links. If you are happy with
9439 this default, there is no need to define an export function for the link
9440 type. For a simple example of an export function, see `org-bbdb.el'."
9441 (add-to-list 'org-link-types type t)
9442 (org-make-link-regexps)
9443 (if (assoc type org-link-protocols)
9444 (setcdr (assoc type org-link-protocols) (list follow export))
9445 (push (list type follow export) org-link-protocols)))
9447 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9448 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9450 ;;;###autoload
9451 (defun org-store-link (arg)
9452 "\\<org-mode-map>Store an org-link to the current location.
9453 This link is added to `org-stored-links' and can later be inserted
9454 into an org-buffer with \\[org-insert-link].
9456 For some link types, a prefix arg is interpreted.
9457 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9458 For file links, arg negates `org-context-in-file-links'.
9460 A double prefix arg force skipping storing functions that are not
9461 part of Org's core.
9463 A triple prefix arg force storing a link for each line in the
9464 active region."
9465 (interactive "P")
9466 (org-load-modules-maybe)
9467 (if (and (equal arg '(64)) (org-region-active-p))
9468 (save-excursion
9469 (let ((end (region-end)))
9470 (goto-char (region-beginning))
9471 (set-mark (point))
9472 (while (< (point-at-eol) end)
9473 (move-end-of-line 1) (activate-mark)
9474 (let (current-prefix-arg)
9475 (call-interactively 'org-store-link))
9476 (move-beginning-of-line 2)
9477 (set-mark (point)))))
9478 (org-with-limited-levels
9479 (setq org-store-link-plist nil)
9480 (let (link cpltxt desc description search
9481 txt custom-id agenda-link sfuns sfunsn)
9482 (cond
9484 ;; Store a link using an external link type
9485 ((and (not (equal arg '(16)))
9486 (setq sfuns
9487 (delq
9488 nil (mapcar (lambda (f)
9489 (let (fs) (if (funcall f) (push f fs))))
9490 org-store-link-functions))
9491 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9492 (or (and (cdr sfuns)
9493 (funcall (intern
9494 (completing-read
9495 "Which function for creating the link? "
9496 sfunsn t (car sfunsn)))))
9497 (funcall (caar sfuns)))
9498 (setq link (plist-get org-store-link-plist :link)
9499 desc (or (plist-get org-store-link-plist
9500 :description) link))))
9502 ;; Store a link from a source code buffer
9503 ((org-src-edit-buffer-p)
9504 (let (label gc)
9505 (while (or (not label)
9506 (save-excursion
9507 (save-restriction
9508 (widen)
9509 (goto-char (point-min))
9510 (re-search-forward
9511 (regexp-quote (format org-coderef-label-format label))
9512 nil t))))
9513 (when label (message "Label exists already") (sit-for 2))
9514 (setq label (read-string "Code line label: " label)))
9515 (end-of-line 1)
9516 (setq link (format org-coderef-label-format label))
9517 (setq gc (- 79 (length link)))
9518 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9519 (insert link)
9520 (setq link (concat "(" label ")") desc nil)))
9522 ;; We are in the agenda, link to referenced location
9523 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9524 (let ((m (or (get-text-property (point) 'org-hd-marker)
9525 (get-text-property (point) 'org-marker))))
9526 (when m
9527 (org-with-point-at m
9528 (setq agenda-link
9529 (if (org-called-interactively-p 'any)
9530 (call-interactively 'org-store-link)
9531 (org-store-link nil)))))))
9533 ((eq major-mode 'calendar-mode)
9534 (let ((cd (calendar-cursor-to-date)))
9535 (setq link
9536 (format-time-string
9537 (car org-time-stamp-formats)
9538 (apply 'encode-time
9539 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9540 nil nil nil))))
9541 (org-store-link-props :type "calendar" :date cd)))
9543 ((eq major-mode 'help-mode)
9544 (setq link (concat "help:" (save-excursion
9545 (goto-char (point-min))
9546 (looking-at "^[^ ]+")
9547 (match-string 0))))
9548 (org-store-link-props :type "help"))
9550 ((eq major-mode 'w3-mode)
9551 (setq cpltxt (if (and (buffer-name)
9552 (not (string-match "Untitled" (buffer-name))))
9553 (buffer-name)
9554 (url-view-url t))
9555 link (url-view-url t))
9556 (org-store-link-props :type "w3" :url (url-view-url t)))
9558 ((eq major-mode 'image-mode)
9559 (setq cpltxt (concat "file:"
9560 (abbreviate-file-name buffer-file-name))
9561 link cpltxt)
9562 (org-store-link-props :type "image" :file buffer-file-name))
9564 ;; In dired, store a link to the file of the current line
9565 ((eq major-mode 'dired-mode)
9566 (let ((file (dired-get-filename nil t)))
9567 (setq file (if file
9568 (abbreviate-file-name
9569 (expand-file-name (dired-get-filename nil t)))
9570 ;; otherwise, no file so use current directory.
9571 default-directory))
9572 (setq cpltxt (concat "file:" file)
9573 link cpltxt)))
9575 ((setq search (run-hook-with-args-until-success
9576 'org-create-file-search-functions))
9577 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9578 "::" search))
9579 (setq cpltxt (or description link)))
9581 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9582 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9583 (cond
9584 ;; Store a link using the target at point
9585 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9586 (setq cpltxt
9587 (concat "file:"
9588 (abbreviate-file-name
9589 (buffer-file-name (buffer-base-buffer)))
9590 "::" (match-string 1))
9591 link cpltxt))
9592 ((and (featurep 'org-id)
9593 (or (eq org-id-link-to-org-use-id t)
9594 (and (org-called-interactively-p 'any)
9595 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9596 (and (eq org-id-link-to-org-use-id
9597 'create-if-interactive-and-no-custom-id)
9598 (not custom-id))))
9599 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9600 ;; Store a link using the ID at point
9601 (setq link (condition-case nil
9602 (prog1 (org-id-store-link)
9603 (setq desc (plist-get org-store-link-plist
9604 :description)))
9605 (error
9606 ;; Probably before first headline, link only to file
9607 (concat "file:"
9608 (abbreviate-file-name
9609 (buffer-file-name (buffer-base-buffer))))))))
9611 ;; Just link to current headline
9612 (setq cpltxt (concat "file:"
9613 (abbreviate-file-name
9614 (buffer-file-name (buffer-base-buffer)))))
9615 ;; Add a context search string
9616 (when (org-xor org-context-in-file-links arg)
9617 (let* ((ee (org-element-at-point))
9618 (et (org-element-type ee))
9619 (ev (plist-get (cadr ee) :value))
9620 (ek (plist-get (cadr ee) :key))
9621 (eok (and (stringp ek) (string-match "name" ek))))
9622 (setq txt (cond
9623 ((org-at-heading-p) nil)
9624 ((and (eq et 'keyword) eok) ev)
9625 ((org-region-active-p)
9626 (buffer-substring (region-beginning) (region-end)))))
9627 (when (or (null txt) (string-match "\\S-" txt))
9628 (setq cpltxt
9629 (concat cpltxt "::"
9630 (condition-case nil
9631 (org-make-org-heading-search-string txt)
9632 (error "")))
9633 desc (or (and (eq et 'keyword) eok ev)
9634 (nth 4 (ignore-errors (org-heading-components)))
9635 "NONE")))))
9636 (if (string-match "::\\'" cpltxt)
9637 (setq cpltxt (substring cpltxt 0 -2)))
9638 (setq link cpltxt))))
9640 ((buffer-file-name (buffer-base-buffer))
9641 ;; Just link to this file here.
9642 (setq cpltxt (concat "file:"
9643 (abbreviate-file-name
9644 (buffer-file-name (buffer-base-buffer)))))
9645 ;; Add a context string.
9646 (when (org-xor org-context-in-file-links arg)
9647 (setq txt (if (org-region-active-p)
9648 (buffer-substring (region-beginning) (region-end))
9649 (buffer-substring (point-at-bol) (point-at-eol))))
9650 ;; Only use search option if there is some text.
9651 (when (string-match "\\S-" txt)
9652 (setq cpltxt
9653 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9654 desc "NONE")))
9655 (setq link cpltxt))
9657 ((org-called-interactively-p 'interactive)
9658 (user-error "No method for storing a link from this buffer"))
9660 (t (setq link nil)))
9662 ;; We're done setting link and desc, clean up
9663 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9664 (setq link (or link cpltxt)
9665 desc (or desc cpltxt))
9666 (cond ((equal desc "NONE") (setq desc nil))
9667 ((string-match org-bracket-link-analytic-regexp desc)
9668 (let ((d0 (match-string 3 desc))
9669 (p0 (match-string 5 desc)))
9670 (setq desc
9671 (replace-regexp-in-string
9672 org-bracket-link-regexp
9673 (concat (or p0 d0)
9674 (if (equal (length (match-string 0 desc))
9675 (length desc)) "*" "")) desc)))))
9677 ;; Return the link
9678 (if (not (and (or (org-called-interactively-p 'any)
9679 executing-kbd-macro) link))
9680 (or agenda-link (and link (org-make-link-string link desc)))
9681 (push (list link desc) org-stored-links)
9682 (message "Stored: %s" (or desc link))
9683 (when custom-id
9684 (setq link (concat "file:" (abbreviate-file-name
9685 (buffer-file-name)) "::#" custom-id))
9686 (push (list link desc) org-stored-links))
9687 (car org-stored-links))))))
9689 (defun org-store-link-props (&rest plist)
9690 "Store link properties, extract names and addresses."
9691 (let (x adr)
9692 (when (setq x (plist-get plist :from))
9693 (setq adr (mail-extract-address-components x))
9694 (setq plist (plist-put plist :fromname (car adr)))
9695 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9696 (when (setq x (plist-get plist :to))
9697 (setq adr (mail-extract-address-components x))
9698 (setq plist (plist-put plist :toname (car adr)))
9699 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9700 (let ((from (plist-get plist :from))
9701 (to (plist-get plist :to)))
9702 (when (and from to org-from-is-user-regexp)
9703 (setq plist
9704 (plist-put plist :fromto
9705 (if (string-match org-from-is-user-regexp from)
9706 (concat "to %t")
9707 (concat "from %f"))))))
9708 (setq org-store-link-plist plist))
9710 (defun org-add-link-props (&rest plist)
9711 "Add these properties to the link property list."
9712 (let (key value)
9713 (while plist
9714 (setq key (pop plist) value (pop plist))
9715 (setq org-store-link-plist
9716 (plist-put org-store-link-plist key value)))))
9718 (defun org-email-link-description (&optional fmt)
9719 "Return the description part of an email link.
9720 This takes information from `org-store-link-plist' and formats it
9721 according to FMT (default from `org-email-link-description-format')."
9722 (setq fmt (or fmt org-email-link-description-format))
9723 (let* ((p org-store-link-plist)
9724 (to (plist-get p :toaddress))
9725 (from (plist-get p :fromaddress))
9726 (table
9727 (list
9728 (cons "%c" (plist-get p :fromto))
9729 (cons "%F" (plist-get p :from))
9730 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9731 (cons "%T" (plist-get p :to))
9732 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9733 (cons "%s" (plist-get p :subject))
9734 (cons "%d" (plist-get p :date))
9735 (cons "%m" (plist-get p :message-id)))))
9736 (when (string-match "%c" fmt)
9737 ;; Check if the user wrote this message
9738 (if (and org-from-is-user-regexp from to
9739 (save-match-data (string-match org-from-is-user-regexp from)))
9740 (setq fmt (replace-match "to %t" t t fmt))
9741 (setq fmt (replace-match "from %f" t t fmt))))
9742 (org-replace-escapes fmt table)))
9744 (defun org-make-org-heading-search-string (&optional string)
9745 "Make search string for the current headline or STRING."
9746 (let ((s (or string
9747 (and (derived-mode-p 'org-mode)
9748 (save-excursion
9749 (org-back-to-heading t)
9750 (org-element-property :raw-value (org-element-at-point))))))
9751 (lines org-context-in-file-links))
9752 (or string (setq s (concat "*" s))) ; Add * for headlines
9753 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9754 (when (and string (integerp lines) (> lines 0))
9755 (let ((slines (org-split-string s "\n")))
9756 (when (< lines (length slines))
9757 (setq s (mapconcat
9758 'identity
9759 (reverse (nthcdr (- (length slines) lines)
9760 (reverse slines))) "\n")))))
9761 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9763 (defun org-make-link-string (link &optional description)
9764 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9765 (unless (string-match "\\S-" link)
9766 (error "Empty link"))
9767 (when (and description
9768 (stringp description)
9769 (not (string-match "\\S-" description)))
9770 (setq description nil))
9771 (when (stringp description)
9772 ;; Remove brackets from the description, they are fatal.
9773 (while (string-match "\\[" description)
9774 (setq description (replace-match "{" t t description)))
9775 (while (string-match "\\]" description)
9776 (setq description (replace-match "}" t t description))))
9777 (when (equal link description)
9778 ;; No description needed, it is identical
9779 (setq description nil))
9780 (when (and (not description)
9781 (not (string-match (org-image-file-name-regexp) link))
9782 (not (equal link (org-link-escape link))))
9783 (setq description (org-extract-attributes link)))
9784 (setq link
9785 (cond ((string-match (org-image-file-name-regexp) link) link)
9786 ((string-match org-link-types-re link)
9787 (concat (match-string 1 link)
9788 (org-link-escape (substring link (match-end 1)))))
9789 (t (org-link-escape link))))
9790 (concat "[[" link "]"
9791 (if description (concat "[" description "]") "")
9792 "]"))
9794 (defconst org-link-escape-chars
9795 ;;%20 %2B %3B %3D %5B %5D
9796 '(?\ ?\+ ?\; ?\= ?\[ ?\])
9797 "List of characters that should be escaped in link.
9798 This is the list that is used for internal purposes.")
9800 (defconst org-link-escape-chars-browser
9801 ;;%20 %22
9802 '(?\ ?\")
9803 "List of escapes for characters that are problematic in links.
9804 This is the list that is used before handing over to the browser.")
9806 (defun org-link-escape (text &optional table merge)
9807 "Return percent escaped representation of TEXT.
9808 TEXT is a string with the text to escape.
9809 Optional argument TABLE is a list with characters that should be
9810 escaped. When nil, `org-link-escape-chars' is used.
9811 If optional argument MERGE is set, merge TABLE into
9812 `org-link-escape-chars'."
9813 (cond
9814 ((and table merge)
9815 (mapc (lambda (defchr)
9816 (unless (member defchr table)
9817 (setq table (cons defchr table)))) org-link-escape-chars))
9818 ((null table)
9819 (setq table org-link-escape-chars)))
9820 (mapconcat
9821 (lambda (char)
9822 (if (or (member char table)
9823 (and (or (< char 32) (= char ?\%) (> char 126))
9824 org-url-hexify-p))
9825 (mapconcat (lambda (sequence-element)
9826 (format "%%%.2X" sequence-element))
9827 (or (encode-coding-char char 'utf-8)
9828 (error "Unable to percent escape character: %s"
9829 (char-to-string char))) "")
9830 (char-to-string char))) text ""))
9832 (defun org-link-escape-browser (text)
9833 (if (org-string-match-p
9834 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
9835 text)
9836 (org-link-escape text org-link-escape-chars-browser)
9837 text))
9839 (defun org-link-unescape (str)
9840 "Unhex hexified Unicode strings as returned from the JavaScript function
9841 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9842 (unless (and (null str) (string= "" str))
9843 (let ((pos 0) (case-fold-search t) unhexed)
9844 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9845 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9846 (setq str (replace-match unhexed t t str))
9847 (setq pos (+ pos (length unhexed))))))
9848 str)
9850 (defun org-link-unescape-compound (hex)
9851 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9852 Note: this function also decodes single byte encodings like
9853 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9854 (save-match-data
9855 (let* ((bytes (cdr (split-string hex "%")))
9856 (ret "")
9857 (eat 0)
9858 (sum 0))
9859 (while bytes
9860 (let* ((val (string-to-number (pop bytes) 16))
9861 (shift-xor
9862 (if (= 0 eat)
9863 (cond
9864 ((>= val 252) (cons 6 252))
9865 ((>= val 248) (cons 5 248))
9866 ((>= val 240) (cons 4 240))
9867 ((>= val 224) (cons 3 224))
9868 ((>= val 192) (cons 2 192))
9869 (t (cons 0 0)))
9870 (cons 6 128))))
9871 (if (>= val 192) (setq eat (car shift-xor)))
9872 (setq val (logxor val (cdr shift-xor)))
9873 (setq sum (+ (lsh sum (car shift-xor)) val))
9874 (if (> eat 0) (setq eat (- eat 1)))
9875 (cond
9876 ((= 0 eat) ;multi byte
9877 (setq ret (concat ret (org-char-to-string sum)))
9878 (setq sum 0))
9879 ((not bytes) ; single byte(s)
9880 (setq ret (org-link-unescape-single-byte-sequence hex))))
9881 )) ;; end (while bytes
9882 ret )))
9884 (defun org-link-unescape-single-byte-sequence (hex)
9885 "Unhexify hex-encoded single byte character sequences."
9886 (mapconcat (lambda (byte)
9887 (char-to-string (string-to-number byte 16)))
9888 (cdr (split-string hex "%")) ""))
9890 (defun org-xor (a b)
9891 "Exclusive or."
9892 (if a (not b) b))
9894 (defun org-fixup-message-id-for-http (s)
9895 "Replace special characters in a message id, so it can be used in an http query."
9896 (when (string-match "%" s)
9897 (setq s (mapconcat (lambda (c)
9898 (if (eq c ?%)
9899 "%25"
9900 (char-to-string c)))
9901 s "")))
9902 (while (string-match "<" s)
9903 (setq s (replace-match "%3C" t t s)))
9904 (while (string-match ">" s)
9905 (setq s (replace-match "%3E" t t s)))
9906 (while (string-match "@" s)
9907 (setq s (replace-match "%40" t t s)))
9910 (defun org-link-prettify (link)
9911 "Return a human-readable representation of LINK.
9912 The car of LINK must be a raw link the cdr of LINK must be either
9913 a link description or nil."
9914 (let ((desc (or (cadr link) "<no description>")))
9915 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9916 "<" (car link) ">")))
9918 ;;;###autoload
9919 (defun org-insert-link-global ()
9920 "Insert a link like Org-mode does.
9921 This command can be called in any mode to insert a link in Org-mode syntax."
9922 (interactive)
9923 (org-load-modules-maybe)
9924 (org-run-like-in-org-mode 'org-insert-link))
9926 (defun org-insert-all-links (&optional keep)
9927 "Insert all links in `org-stored-links'."
9928 (interactive "P")
9929 (let ((links (copy-sequence org-stored-links)) l)
9930 (while (setq l (if keep (pop links) (pop org-stored-links)))
9931 (insert "- ")
9932 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9933 (insert "\n"))))
9935 (defun org-link-fontify-links-to-this-file ()
9936 "Fontify links to the current file in `org-stored-links'."
9937 (let ((f (buffer-file-name)) a b)
9938 (setq a (mapcar (lambda(l)
9939 (let ((ll (car l)))
9940 (when (and (string-match "^file:\\(.+\\)::" ll)
9941 (equal f (expand-file-name (match-string 1 ll))))
9942 ll)))
9943 org-stored-links))
9944 (when (featurep 'org-id)
9945 (setq b (mapcar (lambda(l)
9946 (let ((ll (car l)))
9947 (when (and (string-match "^id:\\(.+\\)$" ll)
9948 (equal f (expand-file-name
9949 (or (org-id-find-id-file
9950 (match-string 1 ll)) ""))))
9951 ll)))
9952 org-stored-links)))
9953 (mapcar (lambda(l)
9954 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9955 (delq nil (append a b)))))
9957 (defvar org-link-links-in-this-file nil)
9958 (defun org-insert-link (&optional complete-file link-location default-description)
9959 "Insert a link. At the prompt, enter the link.
9961 Completion can be used to insert any of the link protocol prefixes like
9962 http or ftp in use.
9964 The history can be used to select a link previously stored with
9965 `org-store-link'. When the empty string is entered (i.e. if you just
9966 press RET at the prompt), the link defaults to the most recently
9967 stored link. As SPC triggers completion in the minibuffer, you need to
9968 use M-SPC or C-q SPC to force the insertion of a space character.
9970 You will also be prompted for a description, and if one is given, it will
9971 be displayed in the buffer instead of the link.
9973 If there is already a link at point, this command will allow you to edit link
9974 and description parts.
9976 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9977 be selected using completion. The path to the file will be relative to the
9978 current directory if the file is in the current directory or a subdirectory.
9979 Otherwise, the link will be the absolute path as completed in the minibuffer
9980 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9981 option `org-link-file-path-type'.
9983 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9984 the current directory or below.
9986 With three \\[universal-argument] prefixes, negate the meaning of
9987 `org-keep-stored-link-after-insertion'.
9989 If `org-make-link-description-function' is non-nil, this function will be
9990 called with the link target, and the result will be the default
9991 link description.
9993 If the LINK-LOCATION parameter is non-nil, this value will be
9994 used as the link location instead of reading one interactively.
9996 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9997 be used as the default description."
9998 (interactive "P")
9999 (let* ((wcf (current-window-configuration))
10000 (origbuf (current-buffer))
10001 (region (if (org-region-active-p)
10002 (buffer-substring (region-beginning) (region-end))))
10003 (remove (and region (list (region-beginning) (region-end))))
10004 (desc region)
10005 tmphist ; byte-compile incorrectly complains about this
10006 (link link-location)
10007 (abbrevs org-link-abbrev-alist-local)
10008 entry file all-prefixes auto-desc)
10009 (cond
10010 (link-location) ; specified by arg, just use it.
10011 ((org-in-regexp org-bracket-link-regexp 1)
10012 ;; We do have a link at point, and we are going to edit it.
10013 (setq remove (list (match-beginning 0) (match-end 0)))
10014 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10015 (setq link (read-string "Link: "
10016 (org-link-unescape
10017 (org-match-string-no-properties 1)))))
10018 ((or (org-in-regexp org-angle-link-re)
10019 (org-in-regexp org-plain-link-re))
10020 ;; Convert to bracket link
10021 (setq remove (list (match-beginning 0) (match-end 0))
10022 link (read-string "Link: "
10023 (org-remove-angle-brackets (match-string 0)))))
10024 ((member complete-file '((4) (16)))
10025 ;; Completing read for file names.
10026 (setq link (org-file-complete-link complete-file)))
10028 ;; Read link, with completion for stored links.
10029 (org-link-fontify-links-to-this-file)
10030 (org-switch-to-buffer-other-window "*Org Links*")
10031 (with-current-buffer "*Org Links*"
10032 (erase-buffer)
10033 (insert "Insert a link.
10034 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10035 (when org-stored-links
10036 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10037 (insert (mapconcat 'org-link-prettify
10038 (reverse org-stored-links) "\n")))
10039 (goto-char (point-min)))
10040 (let ((cw (selected-window)))
10041 (select-window (get-buffer-window "*Org Links*" 'visible))
10042 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10043 (unless (pos-visible-in-window-p (point-max))
10044 (org-fit-window-to-buffer))
10045 (and (window-live-p cw) (select-window cw)))
10046 ;; Fake a link history, containing the stored links.
10047 (setq tmphist (append (mapcar 'car org-stored-links)
10048 org-insert-link-history))
10049 (setq all-prefixes (append (mapcar 'car abbrevs)
10050 (mapcar 'car org-link-abbrev-alist)
10051 org-link-types))
10052 (unwind-protect
10053 (progn
10054 (setq link
10055 (org-completing-read
10056 "Link: "
10057 (append
10058 (mapcar (lambda (x) (concat x ":"))
10059 all-prefixes)
10060 (mapcar 'car org-stored-links))
10061 nil nil nil
10062 'tmphist
10063 (caar org-stored-links)))
10064 (if (not (string-match "\\S-" link))
10065 (user-error "No link selected"))
10066 (mapc (lambda(l)
10067 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10068 org-stored-links)
10069 (if (or (member link all-prefixes)
10070 (and (equal ":" (substring link -1))
10071 (member (substring link 0 -1) all-prefixes)
10072 (setq link (substring link 0 -1))))
10073 (setq link (with-current-buffer origbuf
10074 (org-link-try-special-completion link)))))
10075 (set-window-configuration wcf)
10076 (kill-buffer "*Org Links*"))
10077 (setq entry (assoc link org-stored-links))
10078 (or entry (push link org-insert-link-history))
10079 (setq desc (or desc (nth 1 entry)))))
10081 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10082 (not org-keep-stored-link-after-insertion))
10083 (setq org-stored-links (delq (assoc link org-stored-links)
10084 org-stored-links)))
10086 (if (and (string-match org-plain-link-re link)
10087 (not (string-match org-ts-regexp link)))
10088 ;; URL-like link, normalize the use of angular brackets.
10089 (setq link (org-remove-angle-brackets link)))
10091 ;; Check if we are linking to the current file with a search
10092 ;; option If yes, simplify the link by using only the search
10093 ;; option.
10094 (when (and buffer-file-name
10095 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10096 (let* ((path (match-string 1 link))
10097 (case-fold-search nil)
10098 (search (match-string 2 link)))
10099 (save-match-data
10100 (if (equal (file-truename buffer-file-name) (file-truename path))
10101 ;; We are linking to this same file, with a search option
10102 (setq link search)))))
10104 ;; Check if we can/should use a relative path. If yes, simplify the link
10105 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10106 (let* ((type (match-string 1 link))
10107 (path (match-string 2 link))
10108 (origpath path)
10109 (case-fold-search nil))
10110 (cond
10111 ((or (eq org-link-file-path-type 'absolute)
10112 (equal complete-file '(16)))
10113 (setq path (abbreviate-file-name (expand-file-name path))))
10114 ((eq org-link-file-path-type 'noabbrev)
10115 (setq path (expand-file-name path)))
10116 ((eq org-link-file-path-type 'relative)
10117 (setq path (file-relative-name path)))
10119 (save-match-data
10120 (if (string-match (concat "^" (regexp-quote
10121 (expand-file-name
10122 (file-name-as-directory
10123 default-directory))))
10124 (expand-file-name path))
10125 ;; We are linking a file with relative path name.
10126 (setq path (substring (expand-file-name path)
10127 (match-end 0)))
10128 (setq path (abbreviate-file-name (expand-file-name path)))))))
10129 (setq link (concat type path))
10130 (if (equal desc origpath)
10131 (setq desc path))))
10133 (if org-make-link-description-function
10134 (setq desc
10135 (or (condition-case nil
10136 (funcall org-make-link-description-function link desc)
10137 (error (progn (message "Can't get link description from `%s'"
10138 (symbol-name org-make-link-description-function))
10139 (sit-for 2) nil)))
10140 (read-string "Description: " default-description)))
10141 (if default-description (setq desc default-description)
10142 (setq desc (or (and auto-desc desc)
10143 (read-string "Description: " desc)))))
10145 (unless (string-match "\\S-" desc) (setq desc nil))
10146 (if remove (apply 'delete-region remove))
10147 (insert (org-make-link-string link desc))))
10149 (defun org-link-try-special-completion (type)
10150 "If there is completion support for link type TYPE, offer it."
10151 (let ((fun (intern (concat "org-" type "-complete-link"))))
10152 (if (functionp fun)
10153 (funcall fun)
10154 (read-string "Link (no completion support): " (concat type ":")))))
10156 (defun org-file-complete-link (&optional arg)
10157 "Create a file link using completion."
10158 (let (file link)
10159 (setq file (org-iread-file-name "File: "))
10160 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10161 (pwd1 (file-name-as-directory (abbreviate-file-name
10162 (expand-file-name ".")))))
10163 (cond
10164 ((equal arg '(16))
10165 (setq link (concat
10166 "file:"
10167 (abbreviate-file-name (expand-file-name file)))))
10168 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10169 (setq link (concat "file:" (match-string 1 file))))
10170 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10171 (expand-file-name file))
10172 (setq link (concat
10173 "file:" (match-string 1 (expand-file-name file)))))
10174 (t (setq link (concat "file:" file)))))
10175 link))
10177 (defun org-iread-file-name (&rest args)
10178 "Read-file-name using `ido-mode' speedup if available.
10179 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10180 See `read-file-name' for a description of parameters."
10181 (org-without-partial-completion
10182 (if (and org-completion-use-ido
10183 (fboundp 'ido-read-file-name)
10184 (boundp 'ido-mode) ido-mode
10185 (listp (second args)))
10186 (let ((ido-enter-matching-directory nil))
10187 (apply 'ido-read-file-name args))
10188 (apply 'read-file-name args))))
10190 (defun org-completing-read (&rest args)
10191 "Completing-read with SPACE being a normal character."
10192 (let ((enable-recursive-minibuffers t)
10193 (minibuffer-local-completion-map
10194 (copy-keymap minibuffer-local-completion-map)))
10195 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10196 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10197 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10198 (apply 'org-icompleting-read args)))
10200 (defun org-completing-read-no-i (&rest args)
10201 (let (org-completion-use-ido org-completion-use-iswitchb)
10202 (apply 'org-completing-read args)))
10204 (defun org-iswitchb-completing-read (prompt choices &rest args)
10205 "Use iswitch as a completing-read replacement to choose from choices.
10206 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10207 from."
10208 (let* ((iswitchb-use-virtual-buffers nil)
10209 (iswitchb-make-buflist-hook
10210 (lambda ()
10211 (setq iswitchb-temp-buflist choices))))
10212 (iswitchb-read-buffer prompt)))
10214 (defun org-icompleting-read (&rest args)
10215 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10216 (org-without-partial-completion
10217 (if (and org-completion-use-ido
10218 (fboundp 'ido-completing-read)
10219 (boundp 'ido-mode) ido-mode
10220 (listp (second args)))
10221 (let ((ido-enter-matching-directory nil))
10222 (apply 'ido-completing-read (concat (car args))
10223 (if (consp (car (nth 1 args)))
10224 (mapcar 'car (nth 1 args))
10225 (nth 1 args))
10226 (cddr args)))
10227 (if (and org-completion-use-iswitchb
10228 (boundp 'iswitchb-mode) iswitchb-mode
10229 (listp (second args)))
10230 (apply 'org-iswitchb-completing-read (concat (car args))
10231 (if (consp (car (nth 1 args)))
10232 (mapcar 'car (nth 1 args))
10233 (nth 1 args))
10234 (cddr args))
10235 (apply 'completing-read args)))))
10237 (defun org-extract-attributes (s)
10238 "Extract the attributes cookie from a string and set as text property."
10239 (let (a attr (start 0) key value)
10240 (save-match-data
10241 (when (string-match "{{\\([^}]+\\)}}$" s)
10242 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10243 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10244 (setq key (match-string 1 a) value (match-string 2 a)
10245 start (match-end 0)
10246 attr (plist-put attr (intern key) value))))
10247 (org-add-props s nil 'org-attr attr))
10250 ;;; Opening/following a link
10252 (defvar org-link-search-failed nil)
10254 (defvar org-open-link-functions nil
10255 "Hook for functions finding a plain text link.
10256 These functions must take a single argument, the link content.
10257 They will be called for links that look like [[link text][description]]
10258 when LINK TEXT does not have a protocol like \"http:\" and does not look
10259 like a filename (e.g. \"./blue.png\").
10261 These functions will be called *before* Org attempts to resolve the
10262 link by doing text searches in the current buffer - so if you want a
10263 link \"[[target]]\" to still find \"<<target>>\", your function should
10264 handle this as a special case.
10266 When the function does handle the link, it must return a non-nil value.
10267 If it decides that it is not responsible for this link, it must return
10268 nil to indicate that that Org-mode can continue with other options
10269 like exact and fuzzy text search.")
10271 (defun org-next-link (&optional search-backward)
10272 "Move forward to the next link.
10273 If the link is in hidden text, expose it."
10274 (interactive "P")
10275 (when (and org-link-search-failed (eq this-command last-command))
10276 (goto-char (point-min))
10277 (message "Link search wrapped back to beginning of buffer"))
10278 (setq org-link-search-failed nil)
10279 (let* ((pos (point))
10280 (ct (org-context))
10281 (a (assoc :link ct))
10282 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10283 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10284 ((looking-at org-any-link-re)
10285 ;; Don't stay stuck at link without an org-link face
10286 (forward-char (if search-backward -1 1))))
10287 (if (funcall srch-fun org-any-link-re nil t)
10288 (progn
10289 (goto-char (match-beginning 0))
10290 (if (outline-invisible-p) (org-show-context)))
10291 (goto-char pos)
10292 (setq org-link-search-failed t)
10293 (message "No further link found"))))
10295 (defun org-previous-link ()
10296 "Move backward to the previous link.
10297 If the link is in hidden text, expose it."
10298 (interactive)
10299 (funcall 'org-next-link t))
10301 (defun org-translate-link (s)
10302 "Translate a link string if a translation function has been defined."
10303 (if (and org-link-translation-function
10304 (fboundp org-link-translation-function)
10305 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10306 (progn
10307 (setq s (funcall org-link-translation-function
10308 (match-string 1 s) (match-string 2 s)))
10309 (concat (car s) ":" (cdr s)))
10312 (defun org-translate-link-from-planner (type path)
10313 "Translate a link from Emacs Planner syntax so that Org can follow it.
10314 This is still an experimental function, your mileage may vary."
10315 (cond
10316 ((member type '("http" "https" "news" "ftp"))
10317 ;; standard Internet links are the same.
10318 nil)
10319 ((and (equal type "irc") (string-match "^//" path))
10320 ;; Planner has two / at the beginning of an irc link, we have 1.
10321 ;; We should have zero, actually....
10322 (setq path (substring path 1)))
10323 ((and (equal type "lisp") (string-match "^/" path))
10324 ;; Planner has a slash, we do not.
10325 (setq type "elisp" path (substring path 1)))
10326 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10327 ;; A typical message link. Planner has the id after the final slash,
10328 ;; we separate it with a hash mark
10329 (setq path (concat (match-string 1 path) "#"
10330 (org-remove-angle-brackets (match-string 2 path))))))
10331 (cons type path))
10333 (defun org-find-file-at-mouse (ev)
10334 "Open file link or URL at mouse."
10335 (interactive "e")
10336 (mouse-set-point ev)
10337 (org-open-at-point 'in-emacs))
10339 (defun org-open-at-mouse (ev)
10340 "Open file link or URL at mouse.
10341 See the docstring of `org-open-file' for details."
10342 (interactive "e")
10343 (mouse-set-point ev)
10344 (if (eq major-mode 'org-agenda-mode)
10345 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10346 (org-open-at-point))
10348 (defvar org-window-config-before-follow-link nil
10349 "The window configuration before following a link.
10350 This is saved in case the need arises to restore it.")
10352 (defvar org-open-link-marker (make-marker)
10353 "Marker pointing to the location where `org-open-at-point; was called.")
10355 ;;;###autoload
10356 (defun org-open-at-point-global ()
10357 "Follow a link like Org-mode does.
10358 This command can be called in any mode to follow a link that has
10359 Org-mode syntax."
10360 (interactive)
10361 (org-run-like-in-org-mode 'org-open-at-point))
10363 ;;;###autoload
10364 (defun org-open-link-from-string (s &optional arg reference-buffer)
10365 "Open a link in the string S, as if it was in Org-mode."
10366 (interactive "sLink: \nP")
10367 (let ((reference-buffer (or reference-buffer (current-buffer))))
10368 (with-temp-buffer
10369 (let ((org-inhibit-startup (not reference-buffer)))
10370 (org-mode)
10371 (insert s)
10372 (goto-char (point-min))
10373 (when reference-buffer
10374 (setq org-link-abbrev-alist-local
10375 (with-current-buffer reference-buffer
10376 org-link-abbrev-alist-local)))
10377 (org-open-at-point arg reference-buffer)))))
10379 (defvar org-open-at-point-functions nil
10380 "Hook that is run when following a link at point.
10382 Functions in this hook must return t if they identify and follow
10383 a link at point. If they don't find anything interesting at point,
10384 they must return nil.")
10386 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10387 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10388 (defun org-open-at-point (&optional arg reference-buffer)
10389 "Open link at or after point.
10390 If there is no link at point, this function will search forward up to
10391 the end of the current line.
10392 Normally, files will be opened by an appropriate application. If the
10393 optional prefix argument ARG is non-nil, Emacs will visit the file.
10394 With a double prefix argument, try to open outside of Emacs, in the
10395 application the system uses for this file type."
10396 (interactive "P")
10397 ;; if in a code block, then open the block's results
10398 (unless (call-interactively #'org-babel-open-src-block-result)
10399 (org-load-modules-maybe)
10400 (move-marker org-open-link-marker (point))
10401 (setq org-window-config-before-follow-link (current-window-configuration))
10402 (org-remove-occur-highlights nil nil t)
10403 (cond
10404 ((and (org-at-heading-p)
10405 (not (org-at-timestamp-p t))
10406 (not (org-in-regexp
10407 (concat org-plain-link-re "\\|"
10408 org-bracket-link-regexp "\\|"
10409 org-angle-link-re "\\|"
10410 "[ \t]:[^ \t\n]+:[ \t]*$")))
10411 (not (get-text-property (point) 'org-linked-text)))
10412 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10413 (lk0 (car lkall))
10414 (lk (if (stringp lk0) (list lk0) lk0))
10415 (lkend (cdr lkall)))
10416 (mapcar (lambda(l)
10417 (search-forward l nil lkend)
10418 (goto-char (match-beginning 0))
10419 (org-open-at-point))
10420 lk))
10421 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10422 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10423 ((and (org-at-timestamp-p t)
10424 (not (org-in-regexp org-bracket-link-regexp)))
10425 (org-follow-timestamp-link))
10426 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10427 (not (org-in-regexp org-any-link-re)))
10428 (org-footnote-action))
10430 (let (type path link line search (pos (point)))
10431 (catch 'match
10432 (save-excursion
10433 (skip-chars-forward "^]\n\r")
10434 (when (org-in-regexp org-bracket-link-regexp 1)
10435 (setq link (org-extract-attributes
10436 (org-link-unescape (org-match-string-no-properties 1))))
10437 (while (string-match " *\n *" link)
10438 (setq link (replace-match " " t t link)))
10439 (setq link (org-link-expand-abbrev link))
10440 (cond
10441 ((or (file-name-absolute-p link)
10442 (string-match "^\\.\\.?/" link))
10443 (setq type "file" path link))
10444 ((string-match org-link-re-with-space3 link)
10445 (setq type (match-string 1 link) path (match-string 2 link)))
10446 ((string-match "^help:+\\(.+\\)" link)
10447 (setq type "help" path (match-string 1 link)))
10448 (t (setq type "thisfile" path link)))
10449 (throw 'match t)))
10451 (when (get-text-property (point) 'org-linked-text)
10452 (setq type "thisfile"
10453 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10454 (1+ (point)) (point))
10455 path (buffer-substring
10456 (or (previous-single-property-change pos 'org-linked-text)
10457 (point-min))
10458 (or (next-single-property-change pos 'org-linked-text)
10459 (point-max)))
10460 ;; Ensure we will search for a <<<radio>>> link, not
10461 ;; a simple reference like <<ref>>
10462 path (concat "<" path))
10463 (throw 'match t))
10465 (save-excursion
10466 (when (or (org-in-regexp org-angle-link-re)
10467 (let ((match (org-in-regexp org-plain-link-re)))
10468 ;; Check a plain link is not within a bracket link
10469 (and match
10470 (save-excursion
10471 (progn
10472 (goto-char (car match))
10473 (not (org-in-regexp org-bracket-link-regexp))))))
10474 (let ((line_ending (save-excursion (end-of-line) (point))))
10475 ;; We are in a line before a plain or bracket link
10476 (or (re-search-forward org-plain-link-re line_ending t)
10477 (re-search-forward org-bracket-link-regexp line_ending t))))
10478 (setq type (match-string 1)
10479 path (org-link-unescape (match-string 2)))
10480 (throw 'match t)))
10481 (save-excursion
10482 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10483 (setq type "tags"
10484 path (match-string 1))
10485 (while (string-match ":" path)
10486 (setq path (replace-match "+" t t path)))
10487 (throw 'match t)))
10488 (when (org-in-regexp "<\\([^><\n]+\\)>")
10489 (setq type "tree-match"
10490 path (match-string 1))
10491 (throw 'match t)))
10492 (unless path
10493 (user-error "No link found"))
10495 ;; switch back to reference buffer
10496 ;; needed when if called in a temporary buffer through
10497 ;; org-open-link-from-string
10498 (with-current-buffer (or reference-buffer (current-buffer))
10500 ;; Remove any trailing spaces in path
10501 (if (string-match " +\\'" path)
10502 (setq path (replace-match "" t t path)))
10503 (if (and org-link-translation-function
10504 (fboundp org-link-translation-function))
10505 ;; Check if we need to translate the link
10506 (let ((tmp (funcall org-link-translation-function type path)))
10507 (setq type (car tmp) path (cdr tmp))))
10509 (cond
10511 ((assoc type org-link-protocols)
10512 (funcall (nth 1 (assoc type org-link-protocols)) path))
10514 ((equal type "help")
10515 (let ((f-or-v (intern path)))
10516 (cond ((fboundp f-or-v)
10517 (describe-function f-or-v))
10518 ((boundp f-or-v)
10519 (describe-variable f-or-v))
10520 (t (error "Not a known function or variable")))))
10522 ((equal type "mailto")
10523 (let ((cmd (car org-link-mailto-program))
10524 (args (cdr org-link-mailto-program)) args1
10525 (address path) (subject "") a)
10526 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10527 (setq address (match-string 1 path)
10528 subject (org-link-escape (match-string 2 path))))
10529 (while args
10530 (cond
10531 ((not (stringp (car args))) (push (pop args) args1))
10532 (t (setq a (pop args))
10533 (if (string-match "%a" a)
10534 (setq a (replace-match address t t a)))
10535 (if (string-match "%s" a)
10536 (setq a (replace-match subject t t a)))
10537 (push a args1))))
10538 (apply cmd (nreverse args1))))
10540 ((member type '("http" "https" "ftp" "news"))
10541 ;; In the example of the http Org link
10542 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10543 ;; to open a browser with +subject:"Release 8.2" in the
10544 ;; query field the variable `path' contains
10545 ;; [...]=%2Bsubject:"Release+8.2", `url-encode-url'
10546 ;; converts correct to [...]=%2Bsubject:%22Release+8.2%22
10547 ;; and `org-link-escape-browser' converts wrong to
10548 ;; [...]=%252Bsubject:%22Release+8.2%22.
10550 ;; `url-encode-url' is available since Emacs 24.3.1 and
10551 ;; `org-link-escape-browser' can be removed altogether
10552 ;; once Org drops support for Emacs 24.1 and 24.2.
10553 (browse-url (funcall (if (fboundp 'url-encode-url)
10554 #'url-encode-url
10555 #'org-link-escape-browser)
10556 (concat type ":" path))))
10558 ((string= type "doi")
10559 ;; See comments for type http above
10560 (browse-url (funcall (if (fboundp 'url-encode-url)
10561 #'url-encode-url
10562 #'org-link-escape-browser)
10563 (concat org-doi-server-url path))))
10565 ((member type '("message"))
10566 (browse-url (concat type ":" path)))
10568 ((string= type "tags")
10569 (org-tags-view arg path))
10571 ((string= type "tree-match")
10572 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10574 ((string= type "file")
10575 (if (string-match "::\\([0-9]+\\)\\'" path)
10576 (setq line (string-to-number (match-string 1 path))
10577 path (substring path 0 (match-beginning 0)))
10578 (if (string-match "::\\(.+\\)\\'" path)
10579 (setq search (match-string 1 path)
10580 path (substring path 0 (match-beginning 0)))))
10581 (if (string-match "[*?{]" (file-name-nondirectory path))
10582 (dired path)
10583 (org-open-file path arg line search)))
10585 ((string= type "shell")
10586 (let ((buf (generate-new-buffer "*Org Shell Output"))
10587 (cmd path))
10588 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10589 (string-match org-confirm-shell-link-not-regexp cmd))
10590 (not org-confirm-shell-link-function)
10591 (funcall org-confirm-shell-link-function
10592 (format "Execute \"%s\" in shell? "
10593 (org-add-props cmd nil
10594 'face 'org-warning))))
10595 (progn
10596 (message "Executing %s" cmd)
10597 (shell-command cmd buf)
10598 (if (featurep 'midnight)
10599 (setq clean-buffer-list-kill-buffer-names
10600 (cons buf clean-buffer-list-kill-buffer-names))))
10601 (error "Abort"))))
10603 ((string= type "elisp")
10604 (let ((cmd path))
10605 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10606 (string-match org-confirm-elisp-link-not-regexp cmd))
10607 (not org-confirm-elisp-link-function)
10608 (funcall org-confirm-elisp-link-function
10609 (format "Execute \"%s\" as elisp? "
10610 (org-add-props cmd nil
10611 'face 'org-warning))))
10612 (message "%s => %s" cmd
10613 (if (equal (string-to-char cmd) ?\()
10614 (eval (read cmd))
10615 (call-interactively (read cmd))))
10616 (error "Abort"))))
10618 ((and (string= type "thisfile")
10619 (or (run-hook-with-args-until-success
10620 'org-open-link-functions path)
10621 (and link
10622 (string-match "^id:" link)
10623 (or (featurep 'org-id) (require 'org-id))
10624 (progn
10625 (funcall (nth 1 (assoc "id" org-link-protocols))
10626 (substring path 3))
10627 t)))))
10629 ((string= type "thisfile")
10630 (if arg
10631 (switch-to-buffer-other-window
10632 (org-get-buffer-for-internal-link (current-buffer)))
10633 (org-mark-ring-push))
10634 (let ((cmd `(org-link-search
10635 ,path
10636 ,(cond ((equal arg '(4)) ''occur)
10637 ((equal arg '(16)) ''org-occur))
10638 ,pos)))
10639 (condition-case nil (let ((org-link-search-inhibit-query t))
10640 (eval cmd))
10641 (error (progn (widen) (eval cmd))))))
10643 (t (browse-url-at-point)))))))
10644 (move-marker org-open-link-marker nil)
10645 (run-hook-with-args 'org-follow-link-hook)))
10647 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10648 "Offer links in the current entry and return the selected link.
10649 If there is only one link, return it.
10650 If NTH is an integer, return the NTH link found.
10651 If ZERO is a string, check also this string for a link, and if
10652 there is one, return it."
10653 (with-current-buffer buffer
10654 (save-excursion
10655 (save-restriction
10656 (widen)
10657 (goto-char marker)
10658 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10659 "\\(" org-angle-link-re "\\)\\|"
10660 "\\(" org-plain-link-re "\\)"))
10661 (cnt ?0)
10662 (in-emacs (if (integerp nth) nil nth))
10663 have-zero end links link c)
10664 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10665 (push (match-string 0 zero) links)
10666 (setq cnt (1- cnt) have-zero t))
10667 (save-excursion
10668 (org-back-to-heading t)
10669 (setq end (save-excursion (outline-next-heading) (point)))
10670 (while (re-search-forward re end t)
10671 (push (match-string 0) links))
10672 (setq links (org-uniquify (reverse links))))
10673 (cond
10674 ((null links)
10675 (message "No links"))
10676 ((equal (length links) 1)
10677 (setq link (car links)))
10678 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10679 (setq link (nth (if have-zero nth (1- nth)) links)))
10680 (t ; we have to select a link
10681 (save-excursion
10682 (save-window-excursion
10683 (delete-other-windows)
10684 (with-output-to-temp-buffer "*Select Link*"
10685 (mapc (lambda (l)
10686 (if (not (string-match org-bracket-link-regexp l))
10687 (princ (format "[%c] %s\n" (incf cnt)
10688 (org-remove-angle-brackets l)))
10689 (if (match-end 3)
10690 (princ (format "[%c] %s (%s)\n" (incf cnt)
10691 (match-string 3 l) (match-string 1 l)))
10692 (princ (format "[%c] %s\n" (incf cnt)
10693 (match-string 1 l))))))
10694 links))
10695 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10696 (message "Select link to open, RET to open all:")
10697 (setq c (read-char-exclusive))
10698 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10699 (when (equal c ?q) (error "Abort"))
10700 (if (equal c ?\C-m)
10701 (setq link links)
10702 (setq nth (- c ?0))
10703 (if have-zero (setq nth (1+ nth)))
10704 (unless (and (integerp nth) (>= (length links) nth))
10705 (user-error "Invalid link selection"))
10706 (setq link (nth (1- nth) links)))))
10707 (cons link end))))))
10709 ;; Add special file links that specify the way of opening
10711 (org-add-link-type "file+sys" 'org-open-file-with-system)
10712 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10713 (defun org-open-file-with-system (path)
10714 "Open file at PATH using the system way of opening it."
10715 (org-open-file path 'system))
10716 (defun org-open-file-with-emacs (path)
10717 "Open file at PATH in Emacs."
10718 (org-open-file path 'emacs))
10721 ;;; File search
10723 (defvar org-create-file-search-functions nil
10724 "List of functions to construct the right search string for a file link.
10725 These functions are called in turn with point at the location to
10726 which the link should point.
10728 A function in the hook should first test if it would like to
10729 handle this file type, for example by checking the `major-mode'
10730 or the file extension. If it decides not to handle this file, it
10731 should just return nil to give other functions a chance. If it
10732 does handle the file, it must return the search string to be used
10733 when following the link. The search string will be part of the
10734 file link, given after a double colon, and `org-open-at-point'
10735 will automatically search for it. If special measures must be
10736 taken to make the search successful, another function should be
10737 added to the companion hook `org-execute-file-search-functions',
10738 which see.
10740 A function in this hook may also use `setq' to set the variable
10741 `description' to provide a suggestion for the descriptive text to
10742 be used for this link when it gets inserted into an Org-mode
10743 buffer with \\[org-insert-link].")
10745 (defvar org-execute-file-search-functions nil
10746 "List of functions to execute a file search triggered by a link.
10748 Functions added to this hook must accept a single argument, the
10749 search string that was part of the file link, the part after the
10750 double colon. The function must first check if it would like to
10751 handle this search, for example by checking the `major-mode' or
10752 the file extension. If it decides not to handle this search, it
10753 should just return nil to give other functions a chance. If it
10754 does handle the search, it must return a non-nil value to keep
10755 other functions from trying.
10757 Each function can access the current prefix argument through the
10758 variable `current-prefix-arg'. Note that a single prefix is used
10759 to force opening a link in Emacs, so it may be good to only use a
10760 numeric or double prefix to guide the search function.
10762 In case this is needed, a function in this hook can also restore
10763 the window configuration before `org-open-at-point' was called using:
10765 (set-window-configuration org-window-config-before-follow-link)")
10767 (defun org-link-search (s &optional type avoid-pos stealth)
10768 "Search for a link search option.
10769 If S is surrounded by forward slashes, it is interpreted as a
10770 regular expression. In org-mode files, this will create an `org-occur'
10771 sparse tree. In ordinary files, `occur' will be used to list matches.
10772 If the current buffer is in `dired-mode', grep will be used to search
10773 in all files. If AVOID-POS is given, ignore matches near that position.
10775 When optional argument STEALTH is non-nil, do not modify
10776 visibility around point, thus ignoring
10777 `org-show-hierarchy-above', `org-show-following-heading' and
10778 `org-show-siblings' variables."
10779 (let ((case-fold-search t)
10780 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10781 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10782 (append '(("") (" ") ("\t") ("\n"))
10783 org-emphasis-alist)
10784 "\\|") "\\)"))
10785 (pos (point))
10786 (pre nil) (post nil)
10787 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10788 (cond
10789 ;; First check if there are any special search functions
10790 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10791 ;; Now try the builtin stuff
10792 ((and (equal (string-to-char s0) ?#)
10793 (> (length s0) 1)
10794 (save-excursion
10795 (goto-char (point-min))
10796 (and
10797 (re-search-forward
10798 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10799 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10800 (setq type 'dedicated
10801 pos (match-beginning 0))))
10802 ;; There is an exact target for this
10803 (goto-char pos)
10804 (org-back-to-heading t)))
10805 ((save-excursion
10806 (goto-char (point-min))
10807 (and
10808 (re-search-forward
10809 (concat "<<" (regexp-quote s0) ">>") nil t)
10810 (setq type 'dedicated
10811 pos (match-beginning 0))))
10812 ;; There is an exact target for this
10813 (goto-char pos))
10814 ((save-excursion
10815 (goto-char (point-min))
10816 (and
10817 (re-search-forward
10818 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10819 (setq type 'dedicated pos (match-beginning 0))))
10820 ;; Found an element with a matching #+name affiliated keyword.
10821 (goto-char pos))
10822 ((and (string-match "^(\\(.*\\))$" s0)
10823 (save-excursion
10824 (goto-char (point-min))
10825 (and
10826 (re-search-forward
10827 (concat "[^[]" (regexp-quote
10828 (format org-coderef-label-format
10829 (match-string 1 s0))))
10830 nil t)
10831 (setq type 'dedicated
10832 pos (1+ (match-beginning 0))))))
10833 ;; There is a coderef target for this
10834 (goto-char pos))
10835 ((string-match "^/\\(.*\\)/$" s)
10836 ;; A regular expression
10837 (cond
10838 ((derived-mode-p 'org-mode)
10839 (org-occur (match-string 1 s)))
10840 (t (org-do-occur (match-string 1 s)))))
10841 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10842 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10843 (goto-char (point-min))
10844 (cond
10845 ((let (case-fold-search)
10846 (re-search-forward (format org-complex-heading-regexp-format
10847 (regexp-quote s))
10848 nil t))
10849 ;; OK, found a match
10850 (setq type 'dedicated)
10851 (goto-char (match-beginning 0)))
10852 ((and (not org-link-search-inhibit-query)
10853 (eq org-link-search-must-match-exact-headline 'query-to-create)
10854 (y-or-n-p "No match - create this as a new heading? "))
10855 (goto-char (point-max))
10856 (or (bolp) (newline))
10857 (insert "* " s "\n")
10858 (beginning-of-line 0))
10860 (goto-char pos)
10861 (error "No match"))))
10863 ;; A normal search string
10864 (when (equal (string-to-char s) ?*)
10865 ;; Anchor on headlines, post may include tags.
10866 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10867 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10868 s (substring s 1)))
10869 (remove-text-properties
10870 0 (length s)
10871 '(face nil mouse-face nil keymap nil fontified nil) s)
10872 ;; Make a series of regular expressions to find a match
10873 (setq words (org-split-string s "[ \n\r\t]+")
10875 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10876 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10877 "\\)" markers)
10878 re2a_ (concat "\\(" (mapconcat 'downcase words
10879 "[ \t\r\n]+") "\\)[ \t\r\n]")
10880 re2a (concat "[ \t\r\n]" re2a_)
10881 re4_ (concat "\\(" (mapconcat 'downcase words
10882 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10883 re4 (concat "[^a-zA-Z_]" re4_)
10885 re1 (concat pre re2 post)
10886 re3 (concat pre (if pre re4_ re4) post)
10887 re5 (concat pre ".*" re4)
10888 re2 (concat pre re2)
10889 re2a (concat pre (if pre re2a_ re2a))
10890 re4 (concat pre (if pre re4_ re4))
10891 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10892 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10893 re5 "\\)"))
10894 (cond
10895 ((eq type 'org-occur) (org-occur reall))
10896 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10897 (t (goto-char (point-min))
10898 (setq type 'fuzzy)
10899 (if (or (and (org-search-not-self 1 re0 nil t)
10900 (setq type 'dedicated))
10901 (org-search-not-self 1 re1 nil t)
10902 (org-search-not-self 1 re2 nil t)
10903 (org-search-not-self 1 re2a nil t)
10904 (org-search-not-self 1 re3 nil t)
10905 (org-search-not-self 1 re4 nil t)
10906 (org-search-not-self 1 re5 nil t))
10907 (goto-char (match-beginning 1))
10908 (goto-char pos)
10909 (error "No match"))))))
10910 (and (derived-mode-p 'org-mode)
10911 (not stealth)
10912 (org-show-context 'link-search))
10913 type))
10915 (defun org-search-not-self (group &rest args)
10916 "Execute `re-search-forward', but only accept matches that do not
10917 enclose the position of `org-open-link-marker'."
10918 (let ((m org-open-link-marker))
10919 (catch 'exit
10920 (while (apply 're-search-forward args)
10921 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10922 (goto-char (match-end group))
10923 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10924 (> (match-beginning 0) (marker-position m))
10925 (< (match-end 0) (marker-position m)))
10926 (save-match-data
10927 (or (not (org-in-regexp
10928 org-bracket-link-analytic-regexp 1))
10929 (not (match-end 4)) ; no description
10930 (and (<= (match-beginning 4) (point))
10931 (>= (match-end 4) (point))))))
10932 (throw 'exit (point))))))))
10934 (defun org-get-buffer-for-internal-link (buffer)
10935 "Return a buffer to be used for displaying the link target of internal links."
10936 (cond
10937 ((not org-display-internal-link-with-indirect-buffer)
10938 buffer)
10939 ((string-match "(Clone)$" (buffer-name buffer))
10940 (message "Buffer is already a clone, not making another one")
10941 ;; we also do not modify visibility in this case
10942 buffer)
10943 (t ; make a new indirect buffer for displaying the link
10944 (let* ((bn (buffer-name buffer))
10945 (ibn (concat bn "(Clone)"))
10946 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10947 (with-current-buffer ib (org-overview))
10948 ib))))
10950 (defun org-do-occur (regexp &optional cleanup)
10951 "Call the Emacs command `occur'.
10952 If CLEANUP is non-nil, remove the printout of the regular expression
10953 in the *Occur* buffer. This is useful if the regex is long and not useful
10954 to read."
10955 (occur regexp)
10956 (when cleanup
10957 (let ((cwin (selected-window)) win beg end)
10958 (when (setq win (get-buffer-window "*Occur*"))
10959 (select-window win))
10960 (goto-char (point-min))
10961 (when (re-search-forward "match[a-z]+" nil t)
10962 (setq beg (match-end 0))
10963 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10964 (setq end (1- (match-beginning 0)))))
10965 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10966 (goto-char (point-min))
10967 (select-window cwin))))
10969 ;;; The mark ring for links jumps
10971 (defvar org-mark-ring nil
10972 "Mark ring for positions before jumps in Org-mode.")
10973 (defvar org-mark-ring-last-goto nil
10974 "Last position in the mark ring used to go back.")
10975 ;; Fill and close the ring
10976 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10977 (loop for i from 1 to org-mark-ring-length do
10978 (push (make-marker) org-mark-ring))
10979 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10980 org-mark-ring)
10982 (defun org-mark-ring-push (&optional pos buffer)
10983 "Put the current position or POS into the mark ring and rotate it."
10984 (interactive)
10985 (setq pos (or pos (point)))
10986 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10987 (move-marker (car org-mark-ring)
10988 (or pos (point))
10989 (or buffer (current-buffer)))
10990 (message "%s"
10991 (substitute-command-keys
10992 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10994 (defun org-mark-ring-goto (&optional n)
10995 "Jump to the previous position in the mark ring.
10996 With prefix arg N, jump back that many stored positions. When
10997 called several times in succession, walk through the entire ring.
10998 Org-mode commands jumping to a different position in the current file,
10999 or to another Org-mode file, automatically push the old position
11000 onto the ring."
11001 (interactive "p")
11002 (let (p m)
11003 (if (eq last-command this-command)
11004 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11005 (setq p org-mark-ring))
11006 (setq org-mark-ring-last-goto p)
11007 (setq m (car p))
11008 (org-pop-to-buffer-same-window (marker-buffer m))
11009 (goto-char m)
11010 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11012 (defun org-remove-angle-brackets (s)
11013 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11014 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11016 (defun org-add-angle-brackets (s)
11017 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11018 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11020 (defun org-remove-double-quotes (s)
11021 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11022 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11025 ;;; Following specific links
11027 (defun org-follow-timestamp-link ()
11028 "Open an agenda view for the time-stamp date/range at point."
11029 (cond
11030 ((org-at-date-range-p t)
11031 (let ((org-agenda-start-on-weekday)
11032 (t1 (match-string 1))
11033 (t2 (match-string 2)) tt1 tt2)
11034 (setq tt1 (time-to-days (org-time-string-to-time t1))
11035 tt2 (time-to-days (org-time-string-to-time t2)))
11036 (let ((org-agenda-buffer-tmp-name
11037 (format "*Org Agenda(a:%s)"
11038 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11039 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11040 ((org-at-timestamp-p t)
11041 (let ((org-agenda-buffer-tmp-name
11042 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11043 (org-agenda-list nil (time-to-days (org-time-string-to-time
11044 (substring (match-string 1) 0 10)))
11045 1)))
11046 (t (error "This should not happen"))))
11049 ;;; Following file links
11050 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11051 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11052 (declare-function mailcap-mime-info
11053 "mailcap" (string &optional request no-decode))
11054 (defvar org-wait nil)
11055 (defun org-open-file (path &optional in-emacs line search)
11056 "Open the file at PATH.
11057 First, this expands any special file name abbreviations. Then the
11058 configuration variable `org-file-apps' is checked if it contains an
11059 entry for this file type, and if yes, the corresponding command is launched.
11061 If no application is found, Emacs simply visits the file.
11063 With optional prefix argument IN-EMACS, Emacs will visit the file.
11064 With a double \\[universal-argument] \\[universal-argument] \
11065 prefix arg, Org tries to avoid opening in Emacs
11066 and to use an external application to visit the file.
11068 Optional LINE specifies a line to go to, optional SEARCH a string
11069 to search for. If LINE or SEARCH is given, the file will be
11070 opened in Emacs, unless an entry from org-file-apps that makes
11071 use of groups in a regexp matches.
11073 If you want to change the way frames are used when following a
11074 link, please customize `org-link-frame-setup'.
11076 If the file does not exist, an error is thrown."
11077 (let* ((file (if (equal path "")
11078 buffer-file-name
11079 (substitute-in-file-name (expand-file-name path))))
11080 (file-apps (append org-file-apps (org-default-apps)))
11081 (apps (org-remove-if
11082 'org-file-apps-entry-match-against-dlink-p file-apps))
11083 (apps-dlink (org-remove-if-not
11084 'org-file-apps-entry-match-against-dlink-p file-apps))
11085 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11086 (dirp (if remp nil (file-directory-p file)))
11087 (file (if (and dirp org-open-directory-means-index-dot-org)
11088 (concat (file-name-as-directory file) "index.org")
11089 file))
11090 (a-m-a-p (assq 'auto-mode apps))
11091 (dfile (downcase file))
11092 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11093 (link (cond ((and (eq line nil)
11094 (eq search nil))
11095 file)
11096 (line
11097 (concat file "::" (number-to-string line)))
11098 (search
11099 (concat file "::" search))))
11100 (dlink (downcase link))
11101 (old-buffer (current-buffer))
11102 (old-pos (point))
11103 (old-mode major-mode)
11104 ext cmd link-match-data)
11105 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11106 (setq ext (match-string 1 dfile))
11107 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11108 (setq ext (match-string 1 dfile))))
11109 (cond
11110 ((member in-emacs '((16) system))
11111 (setq cmd (cdr (assoc 'system apps))))
11112 (in-emacs (setq cmd 'emacs))
11114 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11115 (and dirp (cdr (assoc 'directory apps)))
11116 ; first, try matching against apps-dlink
11117 ; if we get a match here, store the match data for later
11118 (let ((match (assoc-default dlink apps-dlink
11119 'string-match)))
11120 (if match
11121 (progn (setq link-match-data (match-data))
11122 match)
11123 (progn (setq in-emacs (or in-emacs line search))
11124 nil))) ; if we have no match in apps-dlink,
11125 ; always open the file in emacs if line or search
11126 ; is given (for backwards compatibility)
11127 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11128 'string-match)
11129 (cdr (assoc ext apps))
11130 (cdr (assoc t apps))))))
11131 (when (eq cmd 'system)
11132 (setq cmd (cdr (assoc 'system apps))))
11133 (when (eq cmd 'default)
11134 (setq cmd (cdr (assoc t apps))))
11135 (when (eq cmd 'mailcap)
11136 (require 'mailcap)
11137 (mailcap-parse-mailcaps)
11138 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11139 (command (mailcap-mime-info mime-type)))
11140 (if (stringp command)
11141 (setq cmd command)
11142 (setq cmd 'emacs))))
11143 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11144 (not (file-exists-p file))
11145 (not org-open-non-existing-files))
11146 (user-error "No such file: %s" file))
11147 (cond
11148 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11149 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11150 (while (string-match "['\"]%s['\"]" cmd)
11151 (setq cmd (replace-match "%s" t t cmd)))
11152 (while (string-match "%s" cmd)
11153 (setq cmd (replace-match
11154 (save-match-data
11155 (shell-quote-argument
11156 (convert-standard-filename file)))
11157 t t cmd)))
11159 ;; Replace "%1", "%2" etc. in command with group matches from regex
11160 (save-match-data
11161 (let ((match-index 1)
11162 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11163 (set-match-data link-match-data)
11164 (while (<= match-index number-of-groups)
11165 (let ((regex (concat "%" (number-to-string match-index)))
11166 (replace-with (match-string match-index dlink)))
11167 (while (string-match regex cmd)
11168 (setq cmd (replace-match replace-with t t cmd))))
11169 (setq match-index (+ match-index 1)))))
11171 (save-window-excursion
11172 (message "Running %s...done" cmd)
11173 (start-process-shell-command cmd nil cmd)
11174 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11175 ((or (stringp cmd)
11176 (eq cmd 'emacs))
11177 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11178 (widen)
11179 (if line (progn (org-goto-line line)
11180 (if (derived-mode-p 'org-mode)
11181 (org-reveal)))
11182 (if search (org-link-search search))))
11183 ((consp cmd)
11184 (let ((file (convert-standard-filename file)))
11185 (save-match-data
11186 (set-match-data link-match-data)
11187 (eval cmd))))
11188 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11189 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11190 (or (not (equal old-buffer (current-buffer)))
11191 (not (equal old-pos (point))))
11192 (org-mark-ring-push old-pos old-buffer))))
11194 (defun org-file-apps-entry-match-against-dlink-p (entry)
11195 "This function returns non-nil if `entry' uses a regular
11196 expression which should be matched against the whole link by
11197 org-open-file.
11199 It assumes that is the case when the entry uses a regular
11200 expression which has at least one grouping construct and the
11201 action is either a lisp form or a command string containing
11202 '%1', i.e. using at least one subexpression match as a
11203 parameter."
11204 (let ((selector (car entry))
11205 (action (cdr entry)))
11206 (if (stringp selector)
11207 (and (> (regexp-opt-depth selector) 0)
11208 (or (and (stringp action)
11209 (string-match "%[0-9]" action))
11210 (consp action)))
11211 nil)))
11213 (defun org-default-apps ()
11214 "Return the default applications for this operating system."
11215 (cond
11216 ((eq system-type 'darwin)
11217 org-file-apps-defaults-macosx)
11218 ((eq system-type 'windows-nt)
11219 org-file-apps-defaults-windowsnt)
11220 (t org-file-apps-defaults-gnu)))
11222 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11223 "Convert extensions to regular expressions in the cars of LIST.
11224 Also, weed out any non-string entries, because the return value is used
11225 only for regexp matching.
11226 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11227 point to the symbol `emacs', indicating that the file should
11228 be opened in Emacs."
11229 (append
11230 (delq nil
11231 (mapcar (lambda (x)
11232 (if (not (stringp (car x)))
11234 (if (string-match "\\W" (car x))
11236 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11237 list))
11238 (if add-auto-mode
11239 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11241 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11242 (defun org-file-remote-p (file)
11243 "Test whether FILE specifies a location on a remote system.
11244 Return non-nil if the location is indeed remote.
11246 For example, the filename \"/user@host:/foo\" specifies a location
11247 on the system \"/user@host:\"."
11248 (cond ((fboundp 'file-remote-p)
11249 (file-remote-p file))
11250 ((fboundp 'tramp-handle-file-remote-p)
11251 (tramp-handle-file-remote-p file))
11252 ((and (boundp 'ange-ftp-name-format)
11253 (string-match (car ange-ftp-name-format) file))
11254 t)))
11257 ;;;; Refiling
11259 (defun org-get-org-file ()
11260 "Read a filename, with default directory `org-directory'."
11261 (let ((default (or org-default-notes-file remember-data-file)))
11262 (read-file-name (format "File name [%s]: " default)
11263 (file-name-as-directory org-directory)
11264 default)))
11266 (defun org-notes-order-reversed-p ()
11267 "Check if the current file should receive notes in reversed order."
11268 (cond
11269 ((not org-reverse-note-order) nil)
11270 ((eq t org-reverse-note-order) t)
11271 ((not (listp org-reverse-note-order)) nil)
11272 (t (catch 'exit
11273 (let ((all org-reverse-note-order)
11274 entry)
11275 (while (setq entry (pop all))
11276 (if (string-match (car entry) buffer-file-name)
11277 (throw 'exit (cdr entry))))
11278 nil)))))
11280 (defvar org-refile-target-table nil
11281 "The list of refile targets, created by `org-refile'.")
11283 (defvar org-agenda-new-buffers nil
11284 "Buffers created to visit agenda files.")
11286 (defvar org-refile-cache nil
11287 "Cache for refile targets.")
11289 (defvar org-refile-markers nil
11290 "All the markers used for caching refile locations.")
11292 (defun org-refile-marker (pos)
11293 "Get a new refile marker, but only if caching is in use."
11294 (if (not org-refile-use-cache)
11296 (let ((m (make-marker)))
11297 (move-marker m pos)
11298 (push m org-refile-markers)
11299 m)))
11301 (defun org-refile-cache-clear ()
11302 "Clear the refile cache and disable all the markers."
11303 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11304 (setq org-refile-markers nil)
11305 (setq org-refile-cache nil)
11306 (message "Refile cache has been cleared"))
11308 (defun org-refile-cache-check-set (set)
11309 "Check if all the markers in the cache still have live buffers."
11310 (let (marker)
11311 (catch 'exit
11312 (while (and set (setq marker (nth 3 (pop set))))
11313 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11314 (when (and marker (null (marker-buffer marker)))
11315 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11316 (sit-for 3)
11317 (throw 'exit nil)))
11318 t)))
11320 (defun org-refile-cache-put (set &rest identifiers)
11321 "Push the refile targets SET into the cache, under IDENTIFIERS."
11322 (let* ((key (sha1 (prin1-to-string identifiers)))
11323 (entry (assoc key org-refile-cache)))
11324 (if entry
11325 (setcdr entry set)
11326 (push (cons key set) org-refile-cache))))
11328 (defun org-refile-cache-get (&rest identifiers)
11329 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11330 (cond
11331 ((not org-refile-cache) nil)
11332 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11334 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11335 org-refile-cache))))
11336 (and set (org-refile-cache-check-set set) set)))))
11338 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11339 "Produce a table with refile targets."
11340 (let ((case-fold-search nil)
11341 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11342 (entries (or org-refile-targets '((nil . (:level . 1)))))
11343 targets tgs txt re files f desc descre fast-path-p level pos0)
11344 (message "Getting targets...")
11345 (with-current-buffer (or default-buffer (current-buffer))
11346 (while (setq entry (pop entries))
11347 (setq files (car entry) desc (cdr entry))
11348 (setq fast-path-p nil)
11349 (cond
11350 ((null files) (setq files (list (current-buffer))))
11351 ((eq files 'org-agenda-files)
11352 (setq files (org-agenda-files 'unrestricted)))
11353 ((and (symbolp files) (fboundp files))
11354 (setq files (funcall files)))
11355 ((and (symbolp files) (boundp files))
11356 (setq files (symbol-value files))))
11357 (if (stringp files) (setq files (list files)))
11358 (cond
11359 ((eq (car desc) :tag)
11360 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11361 ((eq (car desc) :todo)
11362 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11363 ((eq (car desc) :regexp)
11364 (setq descre (cdr desc)))
11365 ((eq (car desc) :level)
11366 (setq descre (concat "^\\*\\{" (number-to-string
11367 (if org-odd-levels-only
11368 (1- (* 2 (cdr desc)))
11369 (cdr desc)))
11370 "\\}[ \t]")))
11371 ((eq (car desc) :maxlevel)
11372 (setq fast-path-p t)
11373 (setq descre (concat "^\\*\\{1," (number-to-string
11374 (if org-odd-levels-only
11375 (1- (* 2 (cdr desc)))
11376 (cdr desc)))
11377 "\\}[ \t]")))
11378 (t (error "Bad refiling target description %s" desc)))
11379 (while (setq f (pop files))
11380 (with-current-buffer
11381 (if (bufferp f) f (org-get-agenda-file-buffer f))
11383 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11384 (progn
11385 (if (bufferp f) (setq f (buffer-file-name
11386 (buffer-base-buffer f))))
11387 (setq f (and f (expand-file-name f)))
11388 (if (eq org-refile-use-outline-path 'file)
11389 (push (list (file-name-nondirectory f) f nil nil) tgs))
11390 (save-excursion
11391 (save-restriction
11392 (widen)
11393 (goto-char (point-min))
11394 (while (re-search-forward descre nil t)
11395 (goto-char (setq pos0 (point-at-bol)))
11396 (catch 'next
11397 (when org-refile-target-verify-function
11398 (save-match-data
11399 (or (funcall org-refile-target-verify-function)
11400 (throw 'next t))))
11401 (when (and (looking-at org-complex-heading-regexp)
11402 (not (member (match-string 4) excluded-entries))
11403 (match-string 4))
11404 (setq level (org-reduced-level
11405 (- (match-end 1) (match-beginning 1)))
11406 txt (org-link-display-format (match-string 4))
11407 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11408 re (format org-complex-heading-regexp-format
11409 (regexp-quote (match-string 4))))
11410 (when org-refile-use-outline-path
11411 (setq txt (mapconcat
11412 'org-protect-slash
11413 (append
11414 (if (eq org-refile-use-outline-path
11415 'file)
11416 (list (file-name-nondirectory
11417 (buffer-file-name
11418 (buffer-base-buffer))))
11419 (if (eq org-refile-use-outline-path
11420 'full-file-path)
11421 (list (buffer-file-name
11422 (buffer-base-buffer)))))
11423 (org-get-outline-path fast-path-p
11424 level txt)
11425 (list txt))
11426 "/")))
11427 (push (list txt f re (org-refile-marker (point)))
11428 tgs)))
11429 (when (= (point) pos0)
11430 ;; verification function has not moved point
11431 (goto-char (point-at-eol))))))))
11432 (when org-refile-use-cache
11433 (org-refile-cache-put tgs (buffer-file-name) descre))
11434 (setq targets (append tgs targets))))))
11435 (message "Getting targets...done")
11436 (nreverse targets)))
11438 (defun org-protect-slash (s)
11439 (while (string-match "/" s)
11440 (setq s (replace-match "\\" t t s)))
11443 (defvar org-olpa (make-vector 20 nil))
11445 (defun org-get-outline-path (&optional fastp level heading)
11446 "Return the outline path to the current entry, as a list.
11448 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11449 routine which makes outline path derivations for an entire file,
11450 avoiding backtracing. Refile target collection makes use of that."
11451 (if fastp
11452 (progn
11453 (if (> level 19)
11454 (error "Outline path failure, more than 19 levels"))
11455 (loop for i from level upto 19 do
11456 (aset org-olpa i nil))
11457 (prog1
11458 (delq nil (append org-olpa nil))
11459 (aset org-olpa level heading)))
11460 (let (rtn case-fold-search)
11461 (save-excursion
11462 (save-restriction
11463 (widen)
11464 (while (org-up-heading-safe)
11465 (when (looking-at org-complex-heading-regexp)
11466 (push (org-trim
11467 (replace-regexp-in-string
11468 ;; Remove statistical/checkboxes cookies
11469 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11470 (org-match-string-no-properties 4)))
11471 rtn)))
11472 rtn)))))
11474 (defun org-format-outline-path (path &optional width prefix separator)
11475 "Format the outline path PATH for display.
11476 WIDTH is the maximum number of characters that is available.
11477 PREFIX is a prefix to be included in the returned string,
11478 such as the file name.
11479 SEPARATOR is inserted between the different parts of the path,
11480 the default is \"/\"."
11481 (setq width (or width 79))
11482 (if prefix (setq width (- width (length prefix))))
11483 (if (not path)
11484 (or prefix "")
11485 (let* ((nsteps (length path))
11486 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11487 (maxwidth (if (<= total-width width)
11488 10000 ;; everything fits
11489 ;; we need to shorten the level headings
11490 (/ (- width nsteps) nsteps)))
11491 (org-odd-levels-only nil)
11492 (n 0)
11493 (total (1+ (length prefix))))
11494 (setq maxwidth (max maxwidth 10))
11495 (concat prefix
11496 (if prefix (or separator "/"))
11497 (mapconcat
11498 (lambda (h)
11499 (setq n (1+ n))
11500 (if (and (= n nsteps) (< maxwidth 10000))
11501 (setq maxwidth (- total-width total)))
11502 (if (< (length h) maxwidth)
11503 (progn (setq total (+ total (length h) 1)) h)
11504 (setq h (substring h 0 (- maxwidth 2))
11505 total (+ total maxwidth 1))
11506 (if (string-match "[ \t]+\\'" h)
11507 (setq h (substring h 0 (match-beginning 0))))
11508 (setq h (concat h "..")))
11509 (org-add-props h nil 'face
11510 (nth (% (1- n) org-n-level-faces)
11511 org-level-faces))
11513 path (or separator "/"))))))
11515 (defun org-display-outline-path (&optional file current separator just-return-string)
11516 "Display the current outline path in the echo area.
11518 If FILE is non-nil, prepend the output with the file name.
11519 If CURRENT is non-nil, append the current heading to the output.
11520 SEPARATOR is passed through to `org-format-outline-path'. It separates
11521 the different parts of the path and defaults to \"/\".
11522 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11523 (interactive "P")
11524 (let* (case-fold-search
11525 (bfn (buffer-file-name (buffer-base-buffer)))
11526 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11527 res)
11528 (if current (setq path (append path
11529 (save-excursion
11530 (org-back-to-heading t)
11531 (if (looking-at org-complex-heading-regexp)
11532 (list (match-string 4)))))))
11533 (setq res
11534 (org-format-outline-path
11535 path
11536 (1- (frame-width))
11537 (and file bfn (concat (file-name-nondirectory bfn) separator))
11538 separator))
11539 (if just-return-string
11540 (org-no-properties res)
11541 (org-unlogged-message "%s" res))))
11543 (defvar org-refile-history nil
11544 "History for refiling operations.")
11546 (defvar org-after-refile-insert-hook nil
11547 "Hook run after `org-refile' has inserted its stuff at the new location.
11548 Note that this is still *before* the stuff will be removed from
11549 the *old* location.")
11551 (defvar org-capture-last-stored-marker)
11552 (defvar org-refile-keep nil
11553 "Non-nil means `org-refile' will copy instead of refile.")
11555 (defun org-copy ()
11556 "Like `org-refile', but copy."
11557 (interactive)
11558 (let ((org-refile-keep t))
11559 (funcall 'org-refile nil nil nil "Copy")))
11561 (defun org-refile (&optional goto default-buffer rfloc msg)
11562 "Move the entry or entries at point to another heading.
11563 The list of target headings is compiled using the information in
11564 `org-refile-targets', which see.
11566 At the target location, the entry is filed as a subitem of the target
11567 heading. Depending on `org-reverse-note-order', the new subitem will
11568 either be the first or the last subitem.
11570 If there is an active region, all entries in that region will be moved.
11571 However, the region must fulfill the requirement that the first heading
11572 is the first one sets the top-level of the moved text - at most siblings
11573 below it are allowed.
11575 With prefix arg GOTO, the command will only visit the target location
11576 and not actually move anything.
11578 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11579 go to the location where the last refiling operation has put the subtree.
11581 With a numeric prefix argument of `2', refile to the running clock.
11583 With a numeric prefix argument of `3', emulate `org-refile-keep'
11584 being set to `t' and copy to the target location, don't move it.
11585 Beware that keeping refiled entries may result in duplicated ID
11586 properties.
11588 RFLOC can be a refile location obtained in a different way.
11590 MSG is a string to replace \"Refile\" in the default prompt with
11591 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11593 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11595 If you are using target caching (see `org-refile-use-cache'),
11596 you have to clear the target cache in order to find new targets.
11597 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11598 prefix argument (`C-u C-u C-u C-c C-w')."
11600 (interactive "P")
11601 (if (member goto '(0 (64)))
11602 (org-refile-cache-clear)
11603 (let* ((actionmsg (or msg "Refile"))
11604 (cbuf (current-buffer))
11605 (regionp (org-region-active-p))
11606 (region-start (and regionp (region-beginning)))
11607 (region-end (and regionp (region-end)))
11608 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11609 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11610 pos it nbuf file re level reversed)
11611 (setq last-command nil)
11612 (when regionp
11613 (goto-char region-start)
11614 (or (bolp) (goto-char (point-at-bol)))
11615 (setq region-start (point))
11616 (unless (or (org-kill-is-subtree-p
11617 (buffer-substring region-start region-end))
11618 (prog1 org-refile-active-region-within-subtree
11619 (let ((s (point-at-eol)))
11620 (org-toggle-heading)
11621 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11622 (user-error "The region is not a (sequence of) subtree(s)")))
11623 (if (equal goto '(16))
11624 (org-refile-goto-last-stored)
11625 (when (or
11626 (and (equal goto 2)
11627 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11628 (prog1
11629 (setq it (list (or org-clock-heading "running clock")
11630 (buffer-file-name
11631 (marker-buffer org-clock-hd-marker))
11633 (marker-position org-clock-hd-marker)))
11634 (setq goto nil)))
11635 (setq it (or rfloc
11636 (let (heading-text)
11637 (save-excursion
11638 (unless goto
11639 (org-back-to-heading t)
11640 (setq heading-text
11641 (nth 4 (org-heading-components))))
11643 (org-refile-get-location
11644 (cond (goto "Goto")
11645 (regionp (concat actionmsg " region to"))
11646 (t (concat actionmsg " subtree \""
11647 heading-text "\" to")))
11648 default-buffer
11649 (and (not (equal '(4) goto))
11650 org-refile-allow-creating-parent-nodes)
11651 goto))))))
11652 (setq file (nth 1 it)
11653 re (nth 2 it)
11654 pos (nth 3 it))
11655 (if (and (not goto)
11657 (equal (buffer-file-name) file)
11658 (if regionp
11659 (and (>= pos region-start)
11660 (<= pos region-end))
11661 (and (>= pos (point))
11662 (< pos (save-excursion
11663 (org-end-of-subtree t t))))))
11664 (error "Cannot refile to position inside the tree or region"))
11666 (setq nbuf (or (find-buffer-visiting file)
11667 (find-file-noselect file)))
11668 (if (and goto (not (equal goto 3)))
11669 (progn
11670 (org-pop-to-buffer-same-window nbuf)
11671 (goto-char pos)
11672 (org-show-context 'org-goto))
11673 (if regionp
11674 (progn
11675 (org-kill-new (buffer-substring region-start region-end))
11676 (org-save-markers-in-region region-start region-end))
11677 (org-copy-subtree 1 nil t))
11678 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11679 (find-file-noselect file)))
11680 (setq reversed (org-notes-order-reversed-p))
11681 (save-excursion
11682 (save-restriction
11683 (widen)
11684 (if pos
11685 (progn
11686 (goto-char pos)
11687 (looking-at org-outline-regexp)
11688 (setq level (org-get-valid-level (funcall outline-level) 1))
11689 (goto-char
11690 (if reversed
11691 (or (outline-next-heading) (point-max))
11692 (or (save-excursion (org-get-next-sibling))
11693 (org-end-of-subtree t t)
11694 (point-max)))))
11695 (setq level 1)
11696 (if (not reversed)
11697 (goto-char (point-max))
11698 (goto-char (point-min))
11699 (or (outline-next-heading) (goto-char (point-max)))))
11700 (if (not (bolp)) (newline))
11701 (org-paste-subtree level)
11702 (when org-log-refile
11703 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11704 (unless (eq org-log-refile 'note)
11705 (save-excursion (org-add-log-note))))
11706 (and org-auto-align-tags
11707 (let ((org-loop-over-headlines-in-active-region nil))
11708 (org-set-tags nil t)))
11709 (let ((bookmark-name (plist-get org-bookmark-names-plist
11710 :last-refile)))
11711 (when bookmark-name
11712 (with-demoted-errors
11713 (bookmark-set bookmark-name))))
11714 ;; If we are refiling for capture, make sure that the
11715 ;; last-capture pointers point here
11716 (when (org-bound-and-true-p org-refile-for-capture)
11717 (let ((bookmark-name (plist-get org-bookmark-names-plist
11718 :last-capture-marker)))
11719 (when bookmark-name
11720 (with-demoted-errors
11721 (bookmark-set bookmark-name))))
11722 (move-marker org-capture-last-stored-marker (point)))
11723 (if (fboundp 'deactivate-mark) (deactivate-mark))
11724 (run-hooks 'org-after-refile-insert-hook))))
11725 (unless org-refile-keep
11726 (if regionp
11727 (delete-region (point) (+ (point) (- region-end region-start)))
11728 (delete-region
11729 (and (org-back-to-heading t) (point))
11730 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11731 (when (featurep 'org-inlinetask)
11732 (org-inlinetask-remove-END-maybe))
11733 (setq org-markers-to-move nil)
11734 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11736 (defun org-refile-goto-last-stored ()
11737 "Go to the location where the last refile was stored."
11738 (interactive)
11739 (bookmark-jump "org-refile-last-stored")
11740 (message "This is the location of the last refile"))
11742 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11743 no-exclude)
11744 "Prompt the user for a refile location, using PROMPT.
11745 PROMPT should not be suffixed with a colon and a space, because
11746 this function appends the default value from
11747 `org-refile-history' automatically, if that is not empty.
11748 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11749 this is used for the GOTO interface."
11750 (let ((org-refile-targets org-refile-targets)
11751 (org-refile-use-outline-path org-refile-use-outline-path)
11752 excluded-entries)
11753 (when (and (derived-mode-p 'org-mode)
11754 (not org-refile-use-cache)
11755 (not no-exclude))
11756 (org-map-tree
11757 (lambda()
11758 (setq excluded-entries
11759 (append excluded-entries (list (org-get-heading t t)))))))
11760 (setq org-refile-target-table
11761 (org-refile-get-targets default-buffer excluded-entries)))
11762 (unless org-refile-target-table
11763 (user-error "No refile targets"))
11764 (let* ((cbuf (current-buffer))
11765 (partial-completion-mode nil)
11766 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11767 (cfunc (if (and org-refile-use-outline-path
11768 org-outline-path-complete-in-steps)
11769 'org-olpath-completing-read
11770 'org-icompleting-read))
11771 (extra (if org-refile-use-outline-path "/" ""))
11772 (cbnex (concat (buffer-name) extra))
11773 (filename (and cfn (expand-file-name cfn)))
11774 (tbl (mapcar
11775 (lambda (x)
11776 (if (and (not (member org-refile-use-outline-path
11777 '(file full-file-path)))
11778 (not (equal filename (nth 1 x))))
11779 (cons (concat (car x) extra " ("
11780 (file-name-nondirectory (nth 1 x)) ")")
11781 (cdr x))
11782 (cons (concat (car x) extra) (cdr x))))
11783 org-refile-target-table))
11784 (completion-ignore-case t)
11785 cdef
11786 (prompt (concat prompt
11787 (or (and (car org-refile-history)
11788 (concat " (default " (car org-refile-history) ")"))
11789 (and (assoc cbnex tbl) (setq cdef cbnex)
11790 (concat " (default " cbnex ")"))) ": "))
11791 pa answ parent-target child parent old-hist)
11792 (setq old-hist org-refile-history)
11793 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11794 nil 'org-refile-history (or cdef (car org-refile-history))))
11795 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11796 (if pa
11797 (progn
11798 (org-refile-check-position pa)
11799 (when (or (not org-refile-history)
11800 (not (eq old-hist org-refile-history))
11801 (not (equal (car pa) (car org-refile-history))))
11802 (setq org-refile-history
11803 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11804 org-refile-history
11805 (cdr org-refile-history))))
11806 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11807 (pop org-refile-history)))
11809 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11810 (progn
11811 (setq parent (match-string 1 answ)
11812 child (match-string 2 answ))
11813 (setq parent-target (or (assoc parent tbl)
11814 (assoc (concat parent "/") tbl)))
11815 (when (and parent-target
11816 (or (eq new-nodes t)
11817 (and (eq new-nodes 'confirm)
11818 (y-or-n-p (format "Create new node \"%s\"? "
11819 child)))))
11820 (org-refile-new-child parent-target child)))
11821 (user-error "Invalid target location")))))
11823 (declare-function org-string-nw-p "org-macs" (s))
11824 (defun org-refile-check-position (refile-pointer)
11825 "Check if the refile pointer matches the headline to which it points."
11826 (let* ((file (nth 1 refile-pointer))
11827 (re (nth 2 refile-pointer))
11828 (pos (nth 3 refile-pointer))
11829 buffer)
11830 (if (and (not (markerp pos)) (not file))
11831 (if file
11832 (user-error "Please save the buffer to a file before refiling")
11833 (user-error "Please indicate a target file in the refile path"))
11834 (when (org-string-nw-p re)
11835 (setq buffer (if (markerp pos)
11836 (marker-buffer pos)
11837 (or (find-buffer-visiting file)
11838 (find-file-noselect file))))
11839 (with-current-buffer buffer
11840 (save-excursion
11841 (save-restriction
11842 (widen)
11843 (goto-char pos)
11844 (beginning-of-line 1)
11845 (unless (org-looking-at-p re)
11846 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11848 (defun org-refile-new-child (parent-target child)
11849 "Use refile target PARENT-TARGET to add new CHILD below it."
11850 (unless parent-target
11851 (error "Cannot find parent for new node"))
11852 (let ((file (nth 1 parent-target))
11853 (pos (nth 3 parent-target))
11854 level)
11855 (with-current-buffer (or (find-buffer-visiting file)
11856 (find-file-noselect file))
11857 (save-excursion
11858 (save-restriction
11859 (widen)
11860 (if pos
11861 (goto-char pos)
11862 (goto-char (point-max))
11863 (if (not (bolp)) (newline)))
11864 (when (looking-at org-outline-regexp)
11865 (setq level (funcall outline-level))
11866 (org-end-of-subtree t t))
11867 (org-back-over-empty-lines)
11868 (insert "\n" (make-string
11869 (if pos (org-get-valid-level level 1) 1) ?*)
11870 " " child "\n")
11871 (beginning-of-line 0)
11872 (list (concat (car parent-target) "/" child) file "" (point)))))))
11874 (defun org-olpath-completing-read (prompt collection &rest args)
11875 "Read an outline path like a file name."
11876 (let ((thetable collection)
11877 (org-completion-use-ido nil) ; does not work with ido.
11878 (org-completion-use-iswitchb nil)) ; or iswitchb
11879 (apply
11880 'org-icompleting-read prompt
11881 (lambda (string predicate &optional flag)
11882 (let (rtn r f (l (length string)))
11883 (cond
11884 ((eq flag nil)
11885 ;; try completion
11886 (try-completion string thetable))
11887 ((eq flag t)
11888 ;; all-completions
11889 (setq rtn (all-completions string thetable predicate))
11890 (mapcar
11891 (lambda (x)
11892 (setq r (substring x l))
11893 (if (string-match " ([^)]*)$" x)
11894 (setq f (match-string 0 x))
11895 (setq f ""))
11896 (if (string-match "/" r)
11897 (concat string (substring r 0 (match-end 0)) f)
11899 rtn))
11900 ((eq flag 'lambda)
11901 ;; exact match?
11902 (assoc string thetable)))))
11903 args)))
11905 ;;;; Dynamic blocks
11907 (defun org-find-dblock (name)
11908 "Find the first dynamic block with name NAME in the buffer.
11909 If not found, stay at current position and return nil."
11910 (let ((case-fold-search t) pos)
11911 (save-excursion
11912 (goto-char (point-min))
11913 (setq pos (and (re-search-forward
11914 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11915 (match-beginning 0))))
11916 (if pos (goto-char pos))
11917 pos))
11919 (defun org-create-dblock (plist)
11920 "Create a dynamic block section, with parameters taken from PLIST.
11921 PLIST must contain a :name entry which is used as name of the block."
11922 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11923 (end-of-line 1)
11924 (newline))
11925 (let ((col (current-column))
11926 (name (plist-get plist :name)))
11927 (insert "#+BEGIN: " name)
11928 (while plist
11929 (if (eq (car plist) :name)
11930 (setq plist (cddr plist))
11931 (insert " " (prin1-to-string (pop plist)))))
11932 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11933 (beginning-of-line -2)))
11935 (defun org-prepare-dblock ()
11936 "Prepare dynamic block for refresh.
11937 This empties the block, puts the cursor at the insert position and returns
11938 the property list including an extra property :name with the block name."
11939 (unless (looking-at org-dblock-start-re)
11940 (user-error "Not at a dynamic block"))
11941 (let* ((begdel (1+ (match-end 0)))
11942 (name (org-no-properties (match-string 1)))
11943 (params (append (list :name name)
11944 (read (concat "(" (match-string 3) ")")))))
11945 (save-excursion
11946 (beginning-of-line 1)
11947 (skip-chars-forward " \t")
11948 (setq params (plist-put params :indentation-column (current-column))))
11949 (unless (re-search-forward org-dblock-end-re nil t)
11950 (error "Dynamic block not terminated"))
11951 (setq params
11952 (append params
11953 (list :content (buffer-substring
11954 begdel (match-beginning 0)))))
11955 (delete-region begdel (match-beginning 0))
11956 (goto-char begdel)
11957 (open-line 1)
11958 params))
11960 (defun org-map-dblocks (&optional command)
11961 "Apply COMMAND to all dynamic blocks in the current buffer.
11962 If COMMAND is not given, use `org-update-dblock'."
11963 (let ((cmd (or command 'org-update-dblock)))
11964 (save-excursion
11965 (goto-char (point-min))
11966 (while (re-search-forward org-dblock-start-re nil t)
11967 (goto-char (match-beginning 0))
11968 (save-excursion
11969 (condition-case nil
11970 (funcall cmd)
11971 (error (message "Error during update of dynamic block"))))
11972 (unless (re-search-forward org-dblock-end-re nil t)
11973 (error "Dynamic block not terminated"))))))
11975 (defun org-dblock-update (&optional arg)
11976 "User command for updating dynamic blocks.
11977 Update the dynamic block at point. With prefix ARG, update all dynamic
11978 blocks in the buffer."
11979 (interactive "P")
11980 (if arg
11981 (org-update-all-dblocks)
11982 (or (looking-at org-dblock-start-re)
11983 (org-beginning-of-dblock))
11984 (org-update-dblock)))
11986 (defun org-update-dblock ()
11987 "Update the dynamic block at point.
11988 This means to empty the block, parse for parameters and then call
11989 the correct writing function."
11990 (interactive)
11991 (save-window-excursion
11992 (let* ((pos (point))
11993 (line (org-current-line))
11994 (params (org-prepare-dblock))
11995 (name (plist-get params :name))
11996 (indent (plist-get params :indentation-column))
11997 (cmd (intern (concat "org-dblock-write:" name))))
11998 (message "Updating dynamic block `%s' at line %d..." name line)
11999 (funcall cmd params)
12000 (message "Updating dynamic block `%s' at line %d...done" name line)
12001 (goto-char pos)
12002 (when (and indent (> indent 0))
12003 (setq indent (make-string indent ?\ ))
12004 (save-excursion
12005 (org-beginning-of-dblock)
12006 (forward-line 1)
12007 (while (not (looking-at org-dblock-end-re))
12008 (insert indent)
12009 (beginning-of-line 2))
12010 (when (looking-at org-dblock-end-re)
12011 (and (looking-at "[ \t]+")
12012 (replace-match ""))
12013 (insert indent)))))))
12015 (defun org-beginning-of-dblock ()
12016 "Find the beginning of the dynamic block at point.
12017 Error if there is no such block at point."
12018 (let ((pos (point))
12019 beg)
12020 (end-of-line 1)
12021 (if (and (re-search-backward org-dblock-start-re nil t)
12022 (setq beg (match-beginning 0))
12023 (re-search-forward org-dblock-end-re nil t)
12024 (> (match-end 0) pos))
12025 (goto-char beg)
12026 (goto-char pos)
12027 (error "Not in a dynamic block"))))
12029 (defun org-update-all-dblocks ()
12030 "Update all dynamic blocks in the buffer.
12031 This function can be used in a hook."
12032 (interactive)
12033 (when (derived-mode-p 'org-mode)
12034 (org-map-dblocks 'org-update-dblock)))
12037 ;;;; Completion
12039 (declare-function org-export-backend-name "org-export" (cl-x))
12040 (declare-function org-export-backend-options "org-export" (cl-x))
12041 (defun org-get-export-keywords ()
12042 "Return a list of all currently understood export keywords.
12043 Export keywords include options, block names, attributes and
12044 keywords relative to each registered export back-end."
12045 (let (keywords)
12046 (dolist (backend
12047 (org-bound-and-true-p org-export--registered-backends)
12048 (delq nil keywords))
12049 ;; Back-end name (for keywords, like #+LATEX:)
12050 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12051 (dolist (option-entry (org-export-backend-options backend))
12052 ;; Back-end options.
12053 (push (nth 1 option-entry) keywords)))))
12055 (defconst org-options-keywords
12056 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12057 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12058 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12059 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12060 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12062 (defcustom org-structure-template-alist
12063 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12064 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12065 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12066 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12067 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12068 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12069 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12070 "<literal style=\"latex\">\n?\n</literal>")
12071 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12072 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12073 "<literal style=\"html\">\n?\n</literal>")
12074 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12075 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12076 ("A" "#+ASCII: " "")
12077 ("i" "#+INDEX: ?" "#+INDEX: ?")
12078 ("I" "#+INCLUDE: %file ?"
12079 "<include file=%file markup=\"?\">"))
12080 "Structure completion elements.
12081 This is a list of abbreviation keys and values. The value gets inserted
12082 if you type `<' followed by the key and then press the completion key,
12083 usually `M-TAB'. %file will be replaced by a file name after prompting
12084 for the file using completion. The cursor will be placed at the position
12085 of the `?` in the template.
12086 There are two templates for each key, the first uses the original Org syntax,
12087 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12088 the default when the /org-mtags.el/ module has been loaded. See also the
12089 variable `org-mtags-prefer-muse-templates'."
12090 :group 'org-completion
12091 :type '(repeat
12092 (list
12093 (string :tag "Key")
12094 (string :tag "Template")
12095 (string :tag "Muse Template"))))
12097 (defun org-try-structure-completion ()
12098 "Try to complete a structure template before point.
12099 This looks for strings like \"<e\" on an otherwise empty line and
12100 expands them."
12101 (let ((l (buffer-substring (point-at-bol) (point)))
12103 (when (and (looking-at "[ \t]*$")
12104 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12105 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12106 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12107 (match-beginning 1)) a)
12108 t)))
12110 (defun org-complete-expand-structure-template (start cell)
12111 "Expand a structure template."
12112 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12113 (rpl (nth (if musep 2 1) cell))
12114 (ind ""))
12115 (delete-region start (point))
12116 (when (string-match "\\`#\\+" rpl)
12117 (cond
12118 ((bolp))
12119 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12120 (setq ind (buffer-substring (point-at-bol) (point))))
12121 (t (newline))))
12122 (setq start (point))
12123 (if (string-match "%file" rpl)
12124 (setq rpl (replace-match
12125 (concat
12126 "\""
12127 (save-match-data
12128 (abbreviate-file-name (read-file-name "Include file: ")))
12129 "\"")
12130 t t rpl)))
12131 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12132 (concat "\n" ind)))
12133 (insert rpl)
12134 (if (re-search-backward "\\?" start t) (delete-char 1))))
12136 ;;;; TODO, DEADLINE, Comments
12138 (defun org-toggle-comment ()
12139 "Change the COMMENT state of an entry."
12140 (interactive)
12141 (save-excursion
12142 (org-back-to-heading)
12143 (let (case-fold-search)
12144 (cond
12145 ((looking-at (format org-heading-keyword-regexp-format
12146 org-comment-string))
12147 (goto-char (match-end 1))
12148 (looking-at (concat " +" org-comment-string))
12149 (replace-match "" t t)
12150 (when (eolp) (insert " ")))
12151 ((looking-at org-outline-regexp)
12152 (goto-char (match-end 0))
12153 (insert org-comment-string " "))))))
12155 (defvar org-last-todo-state-is-todo nil
12156 "This is non-nil when the last TODO state change led to a TODO state.
12157 If the last change removed the TODO tag or switched to DONE, then
12158 this is nil.")
12160 (defvar org-setting-tags nil) ; dynamically skipped
12162 (defvar org-todo-setup-filter-hook nil
12163 "Hook for functions that pre-filter todo specs.
12164 Each function takes a todo spec and returns either nil or the spec
12165 transformed into canonical form." )
12167 (defvar org-todo-get-default-hook nil
12168 "Hook for functions that get a default item for todo.
12169 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12170 nil or a string to be used for the todo mark." )
12172 (defvar org-agenda-headline-snapshot-before-repeat)
12174 (defun org-current-effective-time ()
12175 "Return current time adjusted for `org-extend-today-until' variable."
12176 (let* ((ct (org-current-time))
12177 (dct (decode-time ct))
12178 (ct1
12179 (cond
12180 (org-use-last-clock-out-time-as-effective-time
12181 (or (org-clock-get-last-clock-out-time) ct))
12182 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12183 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12184 (t ct))))
12185 ct1))
12187 (defun org-todo-yesterday (&optional arg)
12188 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12189 (interactive "P")
12190 (if (eq major-mode 'org-agenda-mode)
12191 (apply 'org-agenda-todo-yesterday arg)
12192 (let* ((hour (third (decode-time
12193 (org-current-time))))
12194 (org-extend-today-until (1+ hour)))
12195 (org-todo arg))))
12197 (defvar org-block-entry-blocking ""
12198 "First entry preventing the TODO state change.")
12200 (defun org-cancel-repeater ()
12201 "Cancel a repeater by setting its numeric value to zero."
12202 (interactive)
12203 (save-excursion
12204 (org-back-to-heading t)
12205 (let ((bound1 (point))
12206 (bound0 (save-excursion (outline-next-heading) (point))))
12207 (when (re-search-forward
12208 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12209 org-deadline-time-regexp "\\)\\|\\("
12210 org-ts-regexp "\\)")
12211 bound0 t)
12212 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12213 (replace-match "0" t nil nil 1))))))
12215 (defun org-todo (&optional arg)
12216 "Change the TODO state of an item.
12217 The state of an item is given by a keyword at the start of the heading,
12218 like
12219 *** TODO Write paper
12220 *** DONE Call mom
12222 The different keywords are specified in the variable `org-todo-keywords'.
12223 By default the available states are \"TODO\" and \"DONE\".
12224 So for this example: when the item starts with TODO, it is changed to DONE.
12225 When it starts with DONE, the DONE is removed. And when neither TODO nor
12226 DONE are present, add TODO at the beginning of the heading.
12228 With \\[universal-argument] prefix arg, use completion to determine the new \
12229 state.
12230 With numeric prefix arg, switch to that state.
12231 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12232 keywords (nextset).
12233 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12234 With a numeric prefix arg of 0, inhibit note taking for the change.
12235 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12237 When called through ELisp, arg is also interpreted in the following way:
12238 'none -> empty state
12239 \"\"(empty string) -> switch to empty state
12240 'done -> switch to DONE
12241 'nextset -> switch to the next set of keywords
12242 'previousset -> switch to the previous set of keywords
12243 \"WAITING\" -> switch to the specified keyword, but only if it
12244 really is a member of `org-todo-keywords'."
12245 (interactive "P")
12246 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12247 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12248 'region-start-level 'region))
12249 org-loop-over-headlines-in-active-region)
12250 (org-map-entries
12251 `(org-todo ,arg)
12252 org-loop-over-headlines-in-active-region
12253 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12254 (if (equal arg '(16)) (setq arg 'nextset))
12255 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12256 (let ((org-blocker-hook org-blocker-hook)
12257 commentp
12258 case-fold-search)
12259 (when (equal arg '(64))
12260 (setq arg nil org-blocker-hook nil))
12261 (when (and org-blocker-hook
12262 (or org-inhibit-blocking
12263 (org-entry-get nil "NOBLOCKING")))
12264 (setq org-blocker-hook nil))
12265 (save-excursion
12266 (catch 'exit
12267 (org-back-to-heading t)
12268 (when (looking-at (concat "^\\*+ " org-comment-string))
12269 (org-toggle-comment)
12270 (setq commentp t))
12271 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12272 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12273 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12274 (let* ((match-data (match-data))
12275 (startpos (point-at-bol))
12276 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12277 (org-log-done org-log-done)
12278 (org-log-repeat org-log-repeat)
12279 (org-todo-log-states org-todo-log-states)
12280 (org-inhibit-logging
12281 (if (equal arg 0)
12282 (progn (setq arg nil) 'note) org-inhibit-logging))
12283 (this (match-string 1))
12284 (hl-pos (match-beginning 0))
12285 (head (org-get-todo-sequence-head this))
12286 (ass (assoc head org-todo-kwd-alist))
12287 (interpret (nth 1 ass))
12288 (done-word (nth 3 ass))
12289 (final-done-word (nth 4 ass))
12290 (org-last-state (or this ""))
12291 (completion-ignore-case t)
12292 (member (member this org-todo-keywords-1))
12293 (tail (cdr member))
12294 (org-state (cond
12295 ((and org-todo-key-trigger
12296 (or (and (equal arg '(4))
12297 (eq org-use-fast-todo-selection 'prefix))
12298 (and (not arg) org-use-fast-todo-selection
12299 (not (eq org-use-fast-todo-selection
12300 'prefix)))))
12301 ;; Use fast selection
12302 (org-fast-todo-selection))
12303 ((and (equal arg '(4))
12304 (or (not org-use-fast-todo-selection)
12305 (not org-todo-key-trigger)))
12306 ;; Read a state with completion
12307 (org-icompleting-read
12308 "State: " (mapcar 'list org-todo-keywords-1)
12309 nil t))
12310 ((eq arg 'right)
12311 (if this
12312 (if tail (car tail) nil)
12313 (car org-todo-keywords-1)))
12314 ((eq arg 'left)
12315 (if (equal member org-todo-keywords-1)
12317 (if this
12318 (nth (- (length org-todo-keywords-1)
12319 (length tail) 2)
12320 org-todo-keywords-1)
12321 (org-last org-todo-keywords-1))))
12322 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12323 (setq arg nil))) ; hack to fall back to cycling
12324 (arg
12325 ;; user or caller requests a specific state
12326 (cond
12327 ((equal arg "") nil)
12328 ((eq arg 'none) nil)
12329 ((eq arg 'done) (or done-word (car org-done-keywords)))
12330 ((eq arg 'nextset)
12331 (or (car (cdr (member head org-todo-heads)))
12332 (car org-todo-heads)))
12333 ((eq arg 'previousset)
12334 (let ((org-todo-heads (reverse org-todo-heads)))
12335 (or (car (cdr (member head org-todo-heads)))
12336 (car org-todo-heads))))
12337 ((car (member arg org-todo-keywords-1)))
12338 ((stringp arg)
12339 (user-error "State `%s' not valid in this file" arg))
12340 ((nth (1- (prefix-numeric-value arg))
12341 org-todo-keywords-1))))
12342 ((null member) (or head (car org-todo-keywords-1)))
12343 ((equal this final-done-word) nil) ;; -> make empty
12344 ((null tail) nil) ;; -> first entry
12345 ((memq interpret '(type priority))
12346 (if (eq this-command last-command)
12347 (car tail)
12348 (if (> (length tail) 0)
12349 (or done-word (car org-done-keywords))
12350 nil)))
12352 (car tail))))
12353 (org-state (or
12354 (run-hook-with-args-until-success
12355 'org-todo-get-default-hook org-state org-last-state)
12356 org-state))
12357 (next (if org-state (concat " " org-state " ") " "))
12358 (change-plist (list :type 'todo-state-change :from this :to org-state
12359 :position startpos))
12360 dolog now-done-p)
12361 (when org-blocker-hook
12362 (setq org-last-todo-state-is-todo
12363 (not (member this org-done-keywords)))
12364 (unless (save-excursion
12365 (save-match-data
12366 (org-with-wide-buffer
12367 (run-hook-with-args-until-failure
12368 'org-blocker-hook change-plist))))
12369 (if (org-called-interactively-p 'interactive)
12370 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12371 this org-state org-block-entry-blocking)
12372 ;; fail silently
12373 (message "TODO state change from %s to %s blocked (by \"%s\")"
12374 this org-state org-block-entry-blocking)
12375 (throw 'exit nil))))
12376 (store-match-data match-data)
12377 (replace-match next t t)
12378 (unless (pos-visible-in-window-p hl-pos)
12379 (message "TODO state changed to %s" (org-trim next)))
12380 (unless head
12381 (setq head (org-get-todo-sequence-head org-state)
12382 ass (assoc head org-todo-kwd-alist)
12383 interpret (nth 1 ass)
12384 done-word (nth 3 ass)
12385 final-done-word (nth 4 ass)))
12386 (when (memq arg '(nextset previousset))
12387 (message "Keyword-Set %d/%d: %s"
12388 (- (length org-todo-sets) -1
12389 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12390 (length org-todo-sets)
12391 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12392 (setq org-last-todo-state-is-todo
12393 (not (member org-state org-done-keywords)))
12394 (setq now-done-p (and (member org-state org-done-keywords)
12395 (not (member this org-done-keywords))))
12396 (and logging (org-local-logging logging))
12397 (when (and (or org-todo-log-states org-log-done)
12398 (not (eq org-inhibit-logging t))
12399 (not (memq arg '(nextset previousset))))
12400 ;; we need to look at recording a time and note
12401 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12402 (nth 2 (assoc this org-todo-log-states))))
12403 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12404 (setq dolog 'time))
12405 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12406 (and org-state
12407 (member org-state org-not-done-keywords)
12408 (not (member this org-not-done-keywords))))
12409 ;; This is now a todo state and was not one before
12410 ;; If there was a CLOSED time stamp, get rid of it.
12411 (org-add-planning-info nil nil 'closed))
12412 (when (and now-done-p org-log-done)
12413 ;; It is now done, and it was not done before
12414 (org-add-planning-info 'closed (org-current-effective-time))
12415 (if (and (not dolog) (eq 'note org-log-done))
12416 (org-add-log-setup 'done org-state this 'findpos 'note)))
12417 (when (and org-state dolog)
12418 ;; This is a non-nil state, and we need to log it
12419 (org-add-log-setup 'state org-state this 'findpos dolog)))
12420 ;; Fixup tag positioning
12421 (org-todo-trigger-tag-changes org-state)
12422 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12423 (when org-provide-todo-statistics
12424 (org-update-parent-todo-statistics))
12425 (run-hooks 'org-after-todo-state-change-hook)
12426 (if (and arg (not (member org-state org-done-keywords)))
12427 (setq head (org-get-todo-sequence-head org-state)))
12428 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12429 ;; Do we need to trigger a repeat?
12430 (when now-done-p
12431 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12432 ;; This is for the agenda, take a snapshot of the headline.
12433 (save-match-data
12434 (setq org-agenda-headline-snapshot-before-repeat
12435 (org-get-heading))))
12436 (org-auto-repeat-maybe org-state))
12437 ;; Fixup cursor location if close to the keyword
12438 (if (and (outline-on-heading-p)
12439 (not (bolp))
12440 (save-excursion (beginning-of-line 1)
12441 (looking-at org-todo-line-regexp))
12442 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12443 (progn
12444 (goto-char (or (match-end 2) (match-end 1)))
12445 (and (looking-at " ") (just-one-space))))
12446 (when org-trigger-hook
12447 (save-excursion
12448 (run-hook-with-args 'org-trigger-hook change-plist)))
12449 (when commentp (org-toggle-comment))))))))
12451 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12452 "Block turning an entry into a TODO, using the hierarchy.
12453 This checks whether the current task should be blocked from state
12454 changes. Such blocking occurs when:
12456 1. The task has children which are not all in a completed state.
12458 2. A task has a parent with the property :ORDERED:, and there
12459 are siblings prior to the current task with incomplete
12460 status.
12462 3. The parent of the task is blocked because it has siblings that should
12463 be done first, or is child of a block grandparent TODO entry."
12465 (if (not org-enforce-todo-dependencies)
12466 t ; if locally turned off don't block
12467 (catch 'dont-block
12468 ;; If this is not a todo state change, or if this entry is already DONE,
12469 ;; do not block
12470 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12471 (member (plist-get change-plist :from)
12472 (cons 'done org-done-keywords))
12473 (member (plist-get change-plist :to)
12474 (cons 'todo org-not-done-keywords))
12475 (not (plist-get change-plist :to)))
12476 (throw 'dont-block t))
12477 ;; If this task has children, and any are undone, it's blocked
12478 (save-excursion
12479 (org-back-to-heading t)
12480 (let ((this-level (funcall outline-level)))
12481 (outline-next-heading)
12482 (let ((child-level (funcall outline-level)))
12483 (while (and (not (eobp))
12484 (> child-level this-level))
12485 ;; this todo has children, check whether they are all
12486 ;; completed
12487 (if (and (not (org-entry-is-done-p))
12488 (org-entry-is-todo-p))
12489 (progn (setq org-block-entry-blocking (org-get-heading))
12490 (throw 'dont-block nil)))
12491 (outline-next-heading)
12492 (setq child-level (funcall outline-level))))))
12493 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12494 ;; any previous siblings are undone, it's blocked
12495 (save-excursion
12496 (org-back-to-heading t)
12497 (let* ((pos (point))
12498 (parent-pos (and (org-up-heading-safe) (point))))
12499 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12500 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12501 (forward-line 1)
12502 (re-search-forward org-not-done-heading-regexp pos t))
12503 (setq org-block-entry-blocking (match-string 0))
12504 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12505 ;; Search further up the hierarchy, to see if an ancestor is blocked
12506 (while t
12507 (goto-char parent-pos)
12508 (if (not (looking-at org-not-done-heading-regexp))
12509 (throw 'dont-block t)) ; do not block, parent is not a TODO
12510 (setq pos (point))
12511 (setq parent-pos (and (org-up-heading-safe) (point)))
12512 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12513 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12514 (forward-line 1)
12515 (re-search-forward org-not-done-heading-regexp pos t)
12516 (setq org-block-entry-blocking (org-get-heading)))
12517 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12519 (defcustom org-track-ordered-property-with-tag nil
12520 "Should the ORDERED property also be shown as a tag?
12521 The ORDERED property decides if an entry should require subtasks to be
12522 completed in sequence. Since a property is not very visible, setting
12523 this option means that toggling the ORDERED property with the command
12524 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12525 not relevant for the behavior, but it makes things more visible.
12527 Note that toggling the tag with tags commands will not change the property
12528 and therefore not influence behavior!
12530 This can be t, meaning the tag ORDERED should be used, It can also be a
12531 string to select a different tag for this task."
12532 :group 'org-todo
12533 :type '(choice
12534 (const :tag "No tracking" nil)
12535 (const :tag "Track with ORDERED tag" t)
12536 (string :tag "Use other tag")))
12538 (defun org-toggle-ordered-property ()
12539 "Toggle the ORDERED property of the current entry.
12540 For better visibility, you can track the value of this property with a tag.
12541 See variable `org-track-ordered-property-with-tag'."
12542 (interactive)
12543 (let* ((t1 org-track-ordered-property-with-tag)
12544 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12545 (save-excursion
12546 (org-back-to-heading)
12547 (if (org-entry-get nil "ORDERED")
12548 (progn
12549 (org-delete-property "ORDERED")
12550 (and tag (org-toggle-tag tag 'off))
12551 (message "Subtasks can be completed in arbitrary order"))
12552 (org-entry-put nil "ORDERED" "t")
12553 (and tag (org-toggle-tag tag 'on))
12554 (message "Subtasks must be completed in sequence")))))
12556 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12557 (defun org-block-todo-from-checkboxes (change-plist)
12558 "Block turning an entry into a TODO, using checkboxes.
12559 This checks whether the current task should be blocked from state
12560 changes because there are unchecked boxes in this entry."
12561 (if (not org-enforce-todo-checkbox-dependencies)
12562 t ; if locally turned off don't block
12563 (catch 'dont-block
12564 ;; If this is not a todo state change, or if this entry is already DONE,
12565 ;; do not block
12566 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12567 (member (plist-get change-plist :from)
12568 (cons 'done org-done-keywords))
12569 (member (plist-get change-plist :to)
12570 (cons 'todo org-not-done-keywords))
12571 (not (plist-get change-plist :to)))
12572 (throw 'dont-block t))
12573 ;; If this task has checkboxes that are not checked, it's blocked
12574 (save-excursion
12575 (org-back-to-heading t)
12576 (let ((beg (point)) end)
12577 (outline-next-heading)
12578 (setq end (point))
12579 (goto-char beg)
12580 (if (org-list-search-forward
12581 (concat (org-item-beginning-re)
12582 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12583 "\\[[- ]\\]")
12584 end t)
12585 (progn
12586 (if (boundp 'org-blocked-by-checkboxes)
12587 (setq org-blocked-by-checkboxes t))
12588 (throw 'dont-block nil)))))
12589 t))) ; do not block
12591 (defun org-entry-blocked-p ()
12592 "Is the current entry blocked?"
12593 (org-with-silent-modifications
12594 (if (org-entry-get nil "NOBLOCKING")
12595 nil ;; Never block this entry
12596 (not (run-hook-with-args-until-failure
12597 'org-blocker-hook
12598 (list :type 'todo-state-change
12599 :position (point)
12600 :from 'todo
12601 :to 'done))))))
12603 (defun org-update-statistics-cookies (all)
12604 "Update the statistics cookie, either from TODO or from checkboxes.
12605 This should be called with the cursor in a line with a statistics cookie."
12606 (interactive "P")
12607 (if all
12608 (progn
12609 (org-update-checkbox-count 'all)
12610 (org-map-entries 'org-update-parent-todo-statistics))
12611 (if (not (org-at-heading-p))
12612 (org-update-checkbox-count)
12613 (let ((pos (point-marker))
12614 end l1 l2)
12615 (ignore-errors (org-back-to-heading t))
12616 (if (not (org-at-heading-p))
12617 (org-update-checkbox-count)
12618 (setq l1 (org-outline-level))
12619 (setq end (save-excursion
12620 (outline-next-heading)
12621 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12622 (point)))
12623 (if (and (save-excursion
12624 (re-search-forward
12625 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12626 (not (save-excursion (re-search-forward
12627 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12628 (org-update-checkbox-count)
12629 (if (and l2 (> l2 l1))
12630 (progn
12631 (goto-char end)
12632 (org-update-parent-todo-statistics))
12633 (goto-char pos)
12634 (beginning-of-line 1)
12635 (while (re-search-forward
12636 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12637 (point-at-eol) t)
12638 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12639 (goto-char pos)
12640 (move-marker pos nil)))))
12642 (defvar org-entry-property-inherited-from) ;; defined below
12643 (defun org-update-parent-todo-statistics ()
12644 "Update any statistics cookie in the parent of the current headline.
12645 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12646 the entire subtree and this will travel up the hierarchy and update
12647 statistics everywhere."
12648 (let* ((prop (save-excursion (org-up-heading-safe)
12649 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12650 (recursive (or (not org-hierarchical-todo-statistics)
12651 (and prop (string-match "\\<recursive\\>" prop))))
12652 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12654 (first t)
12655 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12656 level ltoggle l1 new ndel
12657 (cnt-all 0) (cnt-done 0) is-percent kwd
12658 checkbox-beg ov ovs ove cookie-present)
12659 (catch 'exit
12660 (save-excursion
12661 (beginning-of-line 1)
12662 (setq ltoggle (funcall outline-level))
12663 ;; Three situations are to consider:
12665 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12666 ;; to the top-level ancestor on the headline;
12668 ;; 2. If parent has "recursive" property, repeat up to the
12669 ;; headline setting that property, taking inheritance into
12670 ;; account;
12672 ;; 3. Else, move up to direct parent and proceed only once.
12673 (while (and (setq level (org-up-heading-safe))
12674 (or recursive first)
12675 (>= (point) lim))
12676 (setq first nil cookie-present nil)
12677 (unless (and level
12678 (not (string-match
12679 "\\<checkbox\\>"
12680 (downcase (or (org-entry-get nil "COOKIE_DATA")
12681 "")))))
12682 (throw 'exit nil))
12683 (while (re-search-forward box-re (point-at-eol) t)
12684 (setq cnt-all 0 cnt-done 0 cookie-present t)
12685 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12686 (save-match-data
12687 (unless (outline-next-heading) (throw 'exit nil))
12688 (while (and (looking-at org-complex-heading-regexp)
12689 (> (setq l1 (length (match-string 1))) level))
12690 (setq kwd (and (or recursive (= l1 ltoggle))
12691 (match-string 2)))
12692 (if (or (eq org-provide-todo-statistics 'all-headlines)
12693 (and (listp org-provide-todo-statistics)
12694 (or (member kwd org-provide-todo-statistics)
12695 (member kwd org-done-keywords))))
12696 (setq cnt-all (1+ cnt-all))
12697 (if (eq org-provide-todo-statistics t)
12698 (and kwd (setq cnt-all (1+ cnt-all)))))
12699 (and (member kwd org-done-keywords)
12700 (setq cnt-done (1+ cnt-done)))
12701 (outline-next-heading)))
12702 (setq new
12703 (if is-percent
12704 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12705 (format "[%d/%d]" cnt-done cnt-all))
12706 ndel (- (match-end 0) checkbox-beg))
12707 ;; handle overlays when updating cookie from column view
12708 (when (setq ov (car (overlays-at checkbox-beg)))
12709 (setq ovs (overlay-start ov) ove (overlay-end ov))
12710 (delete-overlay ov))
12711 (goto-char checkbox-beg)
12712 (insert new)
12713 (delete-region (point) (+ (point) ndel))
12714 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12715 (when ov (move-overlay ov ovs ove)))
12716 (when cookie-present
12717 (run-hook-with-args 'org-after-todo-statistics-hook
12718 cnt-done (- cnt-all cnt-done))))))
12719 (run-hooks 'org-todo-statistics-hook)))
12721 (defvar org-after-todo-statistics-hook nil
12722 "Hook that is called after a TODO statistics cookie has been updated.
12723 Each function is called with two arguments: the number of not-done entries
12724 and the number of done entries.
12726 For example, the following function, when added to this hook, will switch
12727 an entry to DONE when all children are done, and back to TODO when new
12728 entries are set to a TODO status. Note that this hook is only called
12729 when there is a statistics cookie in the headline!
12731 (defun org-summary-todo (n-done n-not-done)
12732 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12733 (let (org-log-done org-log-states) ; turn off logging
12734 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12737 (defvar org-todo-statistics-hook nil
12738 "Hook that is run whenever Org thinks TODO statistics should be updated.
12739 This hook runs even if there is no statistics cookie present, in which case
12740 `org-after-todo-statistics-hook' would not run.")
12742 (defun org-todo-trigger-tag-changes (state)
12743 "Apply the changes defined in `org-todo-state-tags-triggers'."
12744 (let ((l org-todo-state-tags-triggers)
12745 changes)
12746 (when (or (not state) (equal state ""))
12747 (setq changes (append changes (cdr (assoc "" l)))))
12748 (when (and (stringp state) (> (length state) 0))
12749 (setq changes (append changes (cdr (assoc state l)))))
12750 (when (member state org-not-done-keywords)
12751 (setq changes (append changes (cdr (assoc 'todo l)))))
12752 (when (member state org-done-keywords)
12753 (setq changes (append changes (cdr (assoc 'done l)))))
12754 (dolist (c changes)
12755 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12757 (defun org-local-logging (value)
12758 "Get logging settings from a property VALUE."
12759 (let* (words w a)
12760 ;; directly set the variables, they are already local.
12761 (setq org-log-done nil
12762 org-log-repeat nil
12763 org-todo-log-states nil)
12764 (setq words (org-split-string value))
12765 (while (setq w (pop words))
12766 (cond
12767 ((setq a (assoc w org-startup-options))
12768 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12769 (set (nth 1 a) (nth 2 a))))
12770 ((setq a (org-extract-log-state-settings w))
12771 (and (member (car a) org-todo-keywords-1)
12772 (push a org-todo-log-states)))))))
12774 (defun org-get-todo-sequence-head (kwd)
12775 "Return the head of the TODO sequence to which KWD belongs.
12776 If KWD is not set, check if there is a text property remembering the
12777 right sequence."
12778 (let (p)
12779 (cond
12780 ((not kwd)
12781 (or (get-text-property (point-at-bol) 'org-todo-head)
12782 (progn
12783 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12784 nil (point-at-eol)))
12785 (get-text-property p 'org-todo-head))))
12786 ((not (member kwd org-todo-keywords-1))
12787 (car org-todo-keywords-1))
12788 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12790 (defun org-fast-todo-selection ()
12791 "Fast TODO keyword selection with single keys.
12792 Returns the new TODO keyword, or nil if no state change should occur."
12793 (let* ((fulltable org-todo-key-alist)
12794 (done-keywords org-done-keywords) ;; needed for the faces.
12795 (maxlen (apply 'max (mapcar
12796 (lambda (x)
12797 (if (stringp (car x)) (string-width (car x)) 0))
12798 fulltable)))
12799 (expert nil)
12800 (fwidth (+ maxlen 3 1 3))
12801 (ncol (/ (- (window-width) 4) fwidth))
12802 tg cnt e c tbl
12803 groups ingroup)
12804 (save-excursion
12805 (save-window-excursion
12806 (if expert
12807 (set-buffer (get-buffer-create " *Org todo*"))
12808 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12809 (erase-buffer)
12810 (org-set-local 'org-done-keywords done-keywords)
12811 (setq tbl fulltable cnt 0)
12812 (while (setq e (pop tbl))
12813 (cond
12814 ((equal e '(:startgroup))
12815 (push '() groups) (setq ingroup t)
12816 (when (not (= cnt 0))
12817 (setq cnt 0)
12818 (insert "\n"))
12819 (insert "{ "))
12820 ((equal e '(:endgroup))
12821 (setq ingroup nil cnt 0)
12822 (insert "}\n"))
12823 ((equal e '(:newline))
12824 (when (not (= cnt 0))
12825 (setq cnt 0)
12826 (insert "\n")
12827 (setq e (car tbl))
12828 (while (equal (car tbl) '(:newline))
12829 (insert "\n")
12830 (setq tbl (cdr tbl)))))
12832 (setq tg (car e) c (cdr e))
12833 (if ingroup (push tg (car groups)))
12834 (setq tg (org-add-props tg nil 'face
12835 (org-get-todo-face tg)))
12836 (if (and (= cnt 0) (not ingroup)) (insert " "))
12837 (insert "[" c "] " tg (make-string
12838 (- fwidth 4 (length tg)) ?\ ))
12839 (when (= (setq cnt (1+ cnt)) ncol)
12840 (insert "\n")
12841 (if ingroup (insert " "))
12842 (setq cnt 0)))))
12843 (insert "\n")
12844 (goto-char (point-min))
12845 (if (not expert) (org-fit-window-to-buffer))
12846 (message "[a-z..]:Set [SPC]:clear")
12847 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12848 (cond
12849 ((or (= c ?\C-g)
12850 (and (= c ?q) (not (rassoc c fulltable))))
12851 (setq quit-flag t))
12852 ((= c ?\ ) nil)
12853 ((setq e (rassoc c fulltable) tg (car e))
12855 (t (setq quit-flag t)))))))
12857 (defun org-entry-is-todo-p ()
12858 (member (org-get-todo-state) org-not-done-keywords))
12860 (defun org-entry-is-done-p ()
12861 (member (org-get-todo-state) org-done-keywords))
12863 (defun org-get-todo-state ()
12864 "Return the TODO keyword of the current subtree."
12865 (save-excursion
12866 (org-back-to-heading t)
12867 (and (looking-at org-todo-line-regexp)
12868 (match-end 2)
12869 (match-string 2))))
12871 (defun org-at-date-range-p (&optional inactive-ok)
12872 "Is the cursor inside a date range?"
12873 (interactive)
12874 (save-excursion
12875 (catch 'exit
12876 (let ((pos (point)))
12877 (skip-chars-backward "^[<\r\n")
12878 (skip-chars-backward "<[")
12879 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12880 (>= (match-end 0) pos)
12881 (throw 'exit t))
12882 (skip-chars-backward "^<[\r\n")
12883 (skip-chars-backward "<[")
12884 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12885 (>= (match-end 0) pos)
12886 (throw 'exit t)))
12887 nil)))
12889 (defun org-get-repeat (&optional tagline)
12890 "Check if there is a deadline/schedule with repeater in this entry."
12891 (save-match-data
12892 (save-excursion
12893 (org-back-to-heading t)
12894 (and (re-search-forward (if tagline
12895 (concat tagline "\\s-*" org-repeat-re)
12896 org-repeat-re)
12897 (org-entry-end-position) t)
12898 (match-string-no-properties 1)))))
12900 (defvar org-last-changed-timestamp)
12901 (defvar org-last-inserted-timestamp)
12902 (defvar org-log-post-message)
12903 (defvar org-log-note-purpose)
12904 (defvar org-log-note-how)
12905 (defvar org-log-note-extra)
12906 (defun org-auto-repeat-maybe (done-word)
12907 "Check if the current headline contains a repeated deadline/schedule.
12908 If yes, set TODO state back to what it was and change the base date
12909 of repeating deadline/scheduled time stamps to new date.
12910 This function is run automatically after each state change to a DONE state."
12911 ;; last-state is dynamically scoped into this function
12912 (let* ((repeat (org-get-repeat))
12913 (aa (assoc org-last-state org-todo-kwd-alist))
12914 (interpret (nth 1 aa))
12915 (head (nth 2 aa))
12916 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12917 (msg "Entry repeats: ")
12918 (org-log-done nil)
12919 (org-todo-log-states nil)
12920 re type n what ts time to-state)
12921 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12922 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12923 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12924 org-todo-repeat-to-state))
12925 (unless (and to-state (member to-state org-todo-keywords-1))
12926 (setq to-state (if (eq interpret 'type) org-last-state head)))
12927 (org-todo to-state)
12928 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12929 (org-entry-put nil "LAST_REPEAT" (format-time-string
12930 (org-time-stamp-format t t))))
12931 (when org-log-repeat
12932 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12933 (memq 'org-add-log-note post-command-hook))
12934 ;; OK, we are already setup for some record
12935 (if (eq org-log-repeat 'note)
12936 ;; make sure we take a note, not only a time stamp
12937 (setq org-log-note-how 'note))
12938 ;; Set up for taking a record
12939 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12940 org-last-state
12941 'findpos org-log-repeat)))
12942 (org-back-to-heading t)
12943 (org-add-planning-info nil nil 'closed)
12944 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12945 org-deadline-time-regexp "\\)\\|\\("
12946 org-ts-regexp "\\)"))
12947 (while (re-search-forward
12948 re (save-excursion (outline-next-heading) (point)) t)
12949 (setq type (if (match-end 1) org-scheduled-string
12950 (if (match-end 3) org-deadline-string "Plain:"))
12951 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12952 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12953 (setq n (string-to-number (match-string 2 ts))
12954 what (match-string 3 ts))
12955 (if (equal what "w") (setq n (* n 7) what "d"))
12956 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12957 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12958 ;; Preparation, see if we need to modify the start date for the change
12959 (when (match-end 1)
12960 (setq time (save-match-data (org-time-string-to-time ts)))
12961 (cond
12962 ((equal (match-string 1 ts) ".")
12963 ;; Shift starting date to today
12964 (org-timestamp-change
12965 (- (org-today) (time-to-days time))
12966 'day))
12967 ((equal (match-string 1 ts) "+")
12968 (let ((nshiftmax 10) (nshift 0))
12969 (while (or (= nshift 0)
12970 (<= (time-to-days time)
12971 (time-to-days (current-time))))
12972 (when (= (incf nshift) nshiftmax)
12973 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12974 (error "Abort")))
12975 (org-timestamp-change n (cdr (assoc what whata)))
12976 (org-at-timestamp-p t)
12977 (setq ts (match-string 1))
12978 (setq time (save-match-data (org-time-string-to-time ts)))))
12979 (org-timestamp-change (- n) (cdr (assoc what whata)))
12980 ;; rematch, so that we have everything in place for the real shift
12981 (org-at-timestamp-p t)
12982 (setq ts (match-string 1))
12983 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12984 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12985 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12986 (setq org-log-post-message msg)
12987 (message "%s" msg))))
12989 (defun org-show-todo-tree (arg)
12990 "Make a compact tree which shows all headlines marked with TODO.
12991 The tree will show the lines where the regexp matches, and all higher
12992 headlines above the match.
12993 With a \\[universal-argument] prefix, prompt for a regexp to match.
12994 With a numeric prefix N, construct a sparse tree for the Nth element
12995 of `org-todo-keywords-1'."
12996 (interactive "P")
12997 (let ((case-fold-search nil)
12998 (kwd-re
12999 (cond ((null arg) org-not-done-regexp)
13000 ((equal arg '(4))
13001 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13002 (mapcar 'list org-todo-keywords-1))))
13003 (concat "\\("
13004 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13005 "\\)\\>")))
13006 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13007 (regexp-quote (nth (1- (prefix-numeric-value arg))
13008 org-todo-keywords-1)))
13009 (t (user-error "Invalid prefix argument: %s" arg)))))
13010 (message "%d TODO entries found"
13011 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13013 (defun org-deadline (arg &optional time)
13014 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13015 With one universal prefix argument, remove any deadline from the item.
13016 With two universal prefix arguments, prompt for a warning delay.
13017 With argument TIME, set the deadline at the corresponding date. TIME
13018 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13019 (interactive "P")
13020 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13021 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13022 'region-start-level 'region))
13023 org-loop-over-headlines-in-active-region)
13024 (org-map-entries
13025 `(org-deadline ',arg ,time)
13026 org-loop-over-headlines-in-active-region
13027 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13028 (let* ((old-date (org-entry-get nil "DEADLINE"))
13029 (old-date-time (if old-date (org-time-string-to-time old-date)))
13030 (repeater (and old-date
13031 (string-match
13032 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13033 old-date)
13034 (match-string 1 old-date))))
13035 (cond
13036 ((equal arg '(4))
13037 (when (and old-date org-log-redeadline)
13038 (org-add-log-setup 'deldeadline nil old-date 'findpos
13039 org-log-redeadline))
13040 (org-remove-timestamp-with-keyword org-deadline-string)
13041 (message "Item no longer has a deadline."))
13042 ((equal arg '(16))
13043 (save-excursion
13044 (org-back-to-heading t)
13045 (if (re-search-forward
13046 org-deadline-time-regexp
13047 (save-excursion (outline-next-heading) (point)) t)
13048 (let* ((rpl0 (match-string 1))
13049 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13050 (replace-match
13051 (concat org-deadline-string
13052 " <" rpl
13053 (format " -%dd"
13054 (abs
13055 (- (time-to-days
13056 (save-match-data
13057 (org-read-date nil t nil "Warn starting from" old-date-time)))
13058 (time-to-days old-date-time))))
13059 ">") t t))
13060 (user-error "No deadline information to update"))))
13062 (org-add-planning-info 'deadline time 'closed)
13063 (when (and old-date org-log-redeadline
13064 (not (equal old-date
13065 (substring org-last-inserted-timestamp 1 -1))))
13066 (org-add-log-setup 'redeadline nil old-date 'findpos
13067 org-log-redeadline))
13068 (when repeater
13069 (save-excursion
13070 (org-back-to-heading t)
13071 (when (re-search-forward (concat org-deadline-string " "
13072 org-last-inserted-timestamp)
13073 (save-excursion
13074 (outline-next-heading) (point)) t)
13075 (goto-char (1- (match-end 0)))
13076 (insert " " repeater)
13077 (setq org-last-inserted-timestamp
13078 (concat (substring org-last-inserted-timestamp 0 -1)
13079 " " repeater
13080 (substring org-last-inserted-timestamp -1))))))
13081 (message "Deadline on %s" org-last-inserted-timestamp))))))
13083 (defun org-schedule (arg &optional time)
13084 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13085 With one universal prefix argument, remove any scheduling date from the item.
13086 With two universal prefix arguments, prompt for a delay cookie.
13087 With argument TIME, scheduled at the corresponding date. TIME can
13088 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13089 (interactive "P")
13090 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13091 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13092 'region-start-level 'region))
13093 org-loop-over-headlines-in-active-region)
13094 (org-map-entries
13095 `(org-schedule ',arg ,time)
13096 org-loop-over-headlines-in-active-region
13097 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13098 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13099 (old-date-time (if old-date (org-time-string-to-time old-date)))
13100 (repeater (and old-date
13101 (string-match
13102 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13103 old-date)
13104 (match-string 1 old-date))))
13105 (cond
13106 ((equal arg '(4))
13107 (progn
13108 (when (and old-date org-log-reschedule)
13109 (org-add-log-setup 'delschedule nil old-date 'findpos
13110 org-log-reschedule))
13111 (org-remove-timestamp-with-keyword org-scheduled-string)
13112 (message "Item is no longer scheduled.")))
13113 ((equal arg '(16))
13114 (save-excursion
13115 (org-back-to-heading t)
13116 (if (re-search-forward
13117 org-scheduled-time-regexp
13118 (save-excursion (outline-next-heading) (point)) t)
13119 (let* ((rpl0 (match-string 1))
13120 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13121 (replace-match
13122 (concat org-scheduled-string
13123 " <" rpl
13124 (format " -%dd"
13125 (abs
13126 (- (time-to-days
13127 (save-match-data
13128 (org-read-date nil t nil "Delay until" old-date-time)))
13129 (time-to-days old-date-time))))
13130 ">") t t))
13131 (user-error "No scheduled information to update"))))
13133 (org-add-planning-info 'scheduled time 'closed)
13134 (when (and old-date org-log-reschedule
13135 (not (equal old-date
13136 (substring org-last-inserted-timestamp 1 -1))))
13137 (org-add-log-setup 'reschedule nil old-date 'findpos
13138 org-log-reschedule))
13139 (when repeater
13140 (save-excursion
13141 (org-back-to-heading t)
13142 (when (re-search-forward (concat org-scheduled-string " "
13143 org-last-inserted-timestamp)
13144 (save-excursion
13145 (outline-next-heading) (point)) t)
13146 (goto-char (1- (match-end 0)))
13147 (insert " " repeater)
13148 (setq org-last-inserted-timestamp
13149 (concat (substring org-last-inserted-timestamp 0 -1)
13150 " " repeater
13151 (substring org-last-inserted-timestamp -1))))))
13152 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13154 (defun org-get-scheduled-time (pom &optional inherit)
13155 "Get the scheduled time as a time tuple, of a format suitable
13156 for calling org-schedule with, or if there is no scheduling,
13157 returns nil."
13158 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13159 (when time
13160 (apply 'encode-time (org-parse-time-string time)))))
13162 (defun org-get-deadline-time (pom &optional inherit)
13163 "Get the deadline as a time tuple, of a format suitable for
13164 calling org-deadline with, or if there is no scheduling, returns
13165 nil."
13166 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13167 (when time
13168 (apply 'encode-time (org-parse-time-string time)))))
13170 (defun org-remove-timestamp-with-keyword (keyword)
13171 "Remove all time stamps with KEYWORD in the current entry."
13172 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13173 beg)
13174 (save-excursion
13175 (org-back-to-heading t)
13176 (setq beg (point))
13177 (outline-next-heading)
13178 (while (re-search-backward re beg t)
13179 (replace-match "")
13180 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13181 (equal (char-before) ?\ ))
13182 (backward-delete-char 1)
13183 (if (string-match "^[ \t]*$" (buffer-substring
13184 (point-at-bol) (point-at-eol)))
13185 (delete-region (point-at-bol)
13186 (min (point-max) (1+ (point-at-eol))))))))))
13188 (defvar org-time-was-given) ; dynamically scoped parameter
13189 (defvar org-end-time-was-given) ; dynamically scoped parameter
13191 (defun org-add-planning-info (what &optional time &rest remove)
13192 "Insert new timestamp with keyword in the line directly after the headline.
13193 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13194 If non is given, the user is prompted for a date.
13195 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13196 be removed."
13197 (interactive)
13198 (let (org-time-was-given org-end-time-was-given ts
13199 end default-time default-input)
13201 (catch 'exit
13202 (when (and (memq what '(scheduled deadline))
13203 (or (not time)
13204 (and (stringp time)
13205 (string-match "^[-+]+[0-9]" time))))
13206 ;; Try to get a default date/time from existing timestamp
13207 (save-excursion
13208 (org-back-to-heading t)
13209 (setq end (save-excursion (outline-next-heading) (point)))
13210 (when (re-search-forward (if (eq what 'scheduled)
13211 org-scheduled-time-regexp
13212 org-deadline-time-regexp)
13213 end t)
13214 (setq ts (match-string 1)
13215 default-time
13216 (apply 'encode-time (org-parse-time-string ts))
13217 default-input (and ts (org-get-compact-tod ts))))))
13218 (when what
13219 (setq time
13220 (if (stringp time)
13221 ;; This is a string (relative or absolute), set proper date
13222 (apply 'encode-time
13223 (org-read-date-analyze
13224 time default-time (decode-time default-time)))
13225 ;; If necessary, get the time from the user
13226 (or time (org-read-date nil 'to-time nil nil
13227 default-time default-input)))))
13229 (when (and org-insert-labeled-timestamps-at-point
13230 (member what '(scheduled deadline)))
13231 (insert
13232 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13233 (org-insert-time-stamp time org-time-was-given
13234 nil nil nil (list org-end-time-was-given))
13235 (setq what nil))
13236 (save-excursion
13237 (save-restriction
13238 (let (col list elt ts buffer-invisibility-spec)
13239 (org-back-to-heading t)
13240 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13241 (goto-char (match-end 1))
13242 (setq col (current-column))
13243 (goto-char (match-end 0))
13244 (if (eobp) (insert "\n") (forward-char 1))
13245 (when (and (not what)
13246 (not (looking-at
13247 (concat "[ \t]*"
13248 org-keyword-time-not-clock-regexp))))
13249 ;; Nothing to add, nothing to remove...... :-)
13250 (throw 'exit nil))
13251 (if (and (not (looking-at org-outline-regexp))
13252 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13253 "[^\r\n]*"))
13254 (not (equal (match-string 1) org-clock-string)))
13255 (narrow-to-region (match-beginning 0) (match-end 0))
13256 (insert-before-markers "\n")
13257 (backward-char 1)
13258 (narrow-to-region (point) (point))
13259 (and org-adapt-indentation (org-indent-to-column col)))
13260 ;; Check if we have to remove something.
13261 (setq list (cons what remove))
13262 (while list
13263 (setq elt (pop list))
13264 (when (or (and (eq elt 'scheduled)
13265 (re-search-forward org-scheduled-time-regexp nil t))
13266 (and (eq elt 'deadline)
13267 (re-search-forward org-deadline-time-regexp nil t))
13268 (and (eq elt 'closed)
13269 (re-search-forward org-closed-time-regexp nil t)))
13270 (replace-match "")
13271 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13272 (and (looking-at "[ \t]+") (replace-match ""))
13273 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13274 (when what
13275 (insert
13276 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13277 (cond ((eq what 'scheduled) org-scheduled-string)
13278 ((eq what 'deadline) org-deadline-string)
13279 ((eq what 'closed) org-closed-string))
13280 " ")
13281 (setq ts (org-insert-time-stamp
13282 time
13283 (or org-time-was-given
13284 (and (eq what 'closed) org-log-done-with-time))
13285 (eq what 'closed)
13286 nil nil (list org-end-time-was-given)))
13287 (insert
13288 (if (not (or (bolp) (eq (char-before) ?\ )
13289 (memq (char-after) '(32 10))
13290 (eobp))) " " ""))
13291 (end-of-line 1))
13292 (goto-char (point-min))
13293 (widen)
13294 (if (and (looking-at "[ \t]*\n")
13295 (equal (char-before) ?\n))
13296 (delete-region (1- (point)) (point-at-eol)))
13297 ts))))))
13299 (defvar org-log-note-marker (make-marker))
13300 (defvar org-log-note-purpose nil)
13301 (defvar org-log-note-state nil)
13302 (defvar org-log-note-previous-state nil)
13303 (defvar org-log-note-how nil)
13304 (defvar org-log-note-extra nil)
13305 (defvar org-log-note-window-configuration nil)
13306 (defvar org-log-note-return-to (make-marker))
13307 (defvar org-log-note-effective-time nil
13308 "Remembered current time so that dynamically scoped
13309 `org-extend-today-until' affects tha timestamps in state change
13310 log")
13312 (defvar org-log-post-message nil
13313 "Message to be displayed after a log note has been stored.
13314 The auto-repeater uses this.")
13316 (defun org-add-note ()
13317 "Add a note to the current entry.
13318 This is done in the same way as adding a state change note."
13319 (interactive)
13320 (org-add-log-setup 'note nil nil 'findpos nil))
13322 (defvar org-property-end-re)
13323 (defun org-add-log-setup (&optional purpose state prev-state
13324 findpos how extra)
13325 "Set up the post command hook to take a note.
13326 If this is about to TODO state change, the new state is expected in STATE.
13327 When FINDPOS is non-nil, find the correct position for the note in
13328 the current entry. If not, assume that it can be inserted at point.
13329 HOW is an indicator what kind of note should be created.
13330 EXTRA is additional text that will be inserted into the notes buffer."
13331 (let* ((org-log-into-drawer (org-log-into-drawer))
13332 (drawer (cond ((stringp org-log-into-drawer)
13333 org-log-into-drawer)
13334 (org-log-into-drawer "LOGBOOK"))))
13335 (save-restriction
13336 (save-excursion
13337 (when findpos
13338 (org-back-to-heading t)
13339 (narrow-to-region (point) (save-excursion
13340 (outline-next-heading) (point)))
13341 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13342 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13343 "[^\r\n]*\\)?"))
13344 (goto-char (match-end 0))
13345 (cond
13346 (drawer
13347 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13348 nil t)
13349 (progn
13350 (goto-char (match-end 0))
13351 (or org-log-states-order-reversed
13352 (and (re-search-forward org-property-end-re nil t)
13353 (goto-char (1- (match-beginning 0))))))
13354 (insert "\n:" drawer ":\n:END:")
13355 (beginning-of-line 0)
13356 (org-indent-line)
13357 (beginning-of-line 2)
13358 (org-indent-line)
13359 (end-of-line 0)))
13360 ((and org-log-state-notes-insert-after-drawers
13361 (save-excursion
13362 (forward-line) (looking-at org-drawer-regexp)))
13363 (forward-line)
13364 (while (looking-at org-drawer-regexp)
13365 (goto-char (match-end 0))
13366 (re-search-forward org-property-end-re (point-max) t)
13367 (forward-line))
13368 (forward-line -1)))
13369 (unless org-log-states-order-reversed
13370 (and (= (char-after) ?\n) (forward-char 1))
13371 (org-skip-over-state-notes)
13372 (skip-chars-backward " \t\n\r")))
13373 (move-marker org-log-note-marker (point))
13374 (setq org-log-note-purpose purpose
13375 org-log-note-state state
13376 org-log-note-previous-state prev-state
13377 org-log-note-how how
13378 org-log-note-extra extra
13379 org-log-note-effective-time (org-current-effective-time))
13380 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13382 (defun org-skip-over-state-notes ()
13383 "Skip past the list of State notes in an entry."
13384 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13385 (when (ignore-errors (goto-char (org-in-item-p)))
13386 (let* ((struct (org-list-struct))
13387 (prevs (org-list-prevs-alist struct)))
13388 (while (looking-at "[ \t]*- State")
13389 (goto-char (or (org-list-get-next-item (point) struct prevs)
13390 (org-list-get-item-end (point) struct)))))))
13392 (defun org-add-log-note (&optional purpose)
13393 "Pop up a window for taking a note, and add this note later at point."
13394 (remove-hook 'post-command-hook 'org-add-log-note)
13395 (setq org-log-note-window-configuration (current-window-configuration))
13396 (delete-other-windows)
13397 (move-marker org-log-note-return-to (point))
13398 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13399 (goto-char org-log-note-marker)
13400 (org-switch-to-buffer-other-window "*Org Note*")
13401 (erase-buffer)
13402 (if (memq org-log-note-how '(time state))
13403 (let (current-prefix-arg) (org-store-log-note))
13404 (let ((org-inhibit-startup t)) (org-mode))
13405 (insert (format "# Insert note for %s.
13406 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13407 (cond
13408 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13409 ((eq org-log-note-purpose 'done) "closed todo item")
13410 ((eq org-log-note-purpose 'state)
13411 (format "state change from \"%s\" to \"%s\""
13412 (or org-log-note-previous-state "")
13413 (or org-log-note-state "")))
13414 ((eq org-log-note-purpose 'reschedule)
13415 "rescheduling")
13416 ((eq org-log-note-purpose 'delschedule)
13417 "no longer scheduled")
13418 ((eq org-log-note-purpose 'redeadline)
13419 "changing deadline")
13420 ((eq org-log-note-purpose 'deldeadline)
13421 "removing deadline")
13422 ((eq org-log-note-purpose 'refile)
13423 "refiling")
13424 ((eq org-log-note-purpose 'note)
13425 "this entry")
13426 (t (error "This should not happen")))))
13427 (if org-log-note-extra (insert org-log-note-extra))
13428 (org-set-local 'org-finish-function 'org-store-log-note)
13429 (run-hooks 'org-log-buffer-setup-hook)))
13431 (defvar org-note-abort nil) ; dynamically scoped
13432 (defun org-store-log-note ()
13433 "Finish taking a log note, and insert it to where it belongs."
13434 (let ((txt (buffer-string)))
13435 (kill-buffer (current-buffer))
13436 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13437 lines ind bul)
13438 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13439 (setq txt (replace-match "" t t txt)))
13440 (if (string-match "\\s-+\\'" txt)
13441 (setq txt (replace-match "" t t txt)))
13442 (setq lines (org-split-string txt "\n"))
13443 (when (and note (string-match "\\S-" note))
13444 (setq note
13445 (org-replace-escapes
13446 note
13447 (list (cons "%u" (user-login-name))
13448 (cons "%U" user-full-name)
13449 (cons "%t" (format-time-string
13450 (org-time-stamp-format 'long 'inactive)
13451 org-log-note-effective-time))
13452 (cons "%T" (format-time-string
13453 (org-time-stamp-format 'long nil)
13454 org-log-note-effective-time))
13455 (cons "%d" (format-time-string
13456 (org-time-stamp-format nil 'inactive)
13457 org-log-note-effective-time))
13458 (cons "%D" (format-time-string
13459 (org-time-stamp-format nil nil)
13460 org-log-note-effective-time))
13461 (cons "%s" (if org-log-note-state
13462 (concat "\"" org-log-note-state "\"")
13463 ""))
13464 (cons "%S" (if org-log-note-previous-state
13465 (concat "\"" org-log-note-previous-state "\"")
13466 "\"\"")))))
13467 (if lines (setq note (concat note " \\\\")))
13468 (push note lines))
13469 (when (or current-prefix-arg org-note-abort)
13470 (when org-log-into-drawer
13471 (org-remove-empty-drawer-at org-log-note-marker))
13472 (setq lines nil))
13473 (when lines
13474 (with-current-buffer (marker-buffer org-log-note-marker)
13475 (save-excursion
13476 (goto-char org-log-note-marker)
13477 (move-marker org-log-note-marker nil)
13478 (end-of-line 1)
13479 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13480 (setq ind (save-excursion
13481 (if (ignore-errors (goto-char (org-in-item-p)))
13482 (let ((struct (org-list-struct)))
13483 (org-list-get-ind
13484 (org-list-get-top-point struct) struct))
13485 (skip-chars-backward " \r\t\n")
13486 (cond
13487 ((and (org-at-heading-p)
13488 org-adapt-indentation)
13489 (1+ (org-current-level)))
13490 ((org-at-heading-p) 0)
13491 (t (org-get-indentation))))))
13492 (setq bul (org-list-bullet-string "-"))
13493 (org-indent-line-to ind)
13494 (insert bul (pop lines))
13495 (let ((ind-body (+ (length bul) ind)))
13496 (while lines
13497 (insert "\n")
13498 (org-indent-line-to ind-body)
13499 (insert (pop lines))))
13500 (message "Note stored")
13501 (org-back-to-heading t)
13502 (org-cycle-hide-drawers 'children))
13503 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13504 ;; from within `org-add-log-note' because `buffer-undo-list'
13505 ;; is then modified outside of `org-with-remote-undo'.
13506 (when (eq this-command 'org-agenda-todo)
13507 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13508 ;; Don't add undo information when called from `org-agenda-todo'
13509 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13510 (set-window-configuration org-log-note-window-configuration)
13511 (with-current-buffer (marker-buffer org-log-note-return-to)
13512 (goto-char org-log-note-return-to))
13513 (move-marker org-log-note-return-to nil)
13514 (and org-log-post-message (message "%s" org-log-post-message))))
13516 (defun org-remove-empty-drawer-at (pos)
13517 "Remove an empty drawer at position POS.
13518 POS may also be a marker."
13519 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13520 (org-with-wide-buffer
13521 (goto-char pos)
13522 (let ((drawer (org-element-at-point)))
13523 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13524 (not (org-element-property :contents-begin drawer)))
13525 (delete-region (org-element-property :begin drawer)
13526 (progn (goto-char (org-element-property :end drawer))
13527 (skip-chars-backward " \r\t\n")
13528 (forward-line)
13529 (point))))))))
13531 (defvar org-ts-type nil)
13532 (defun org-sparse-tree (&optional arg type)
13533 "Create a sparse tree, prompt for the details.
13534 This command can create sparse trees. You first need to select the type
13535 of match used to create the tree:
13537 t Show all TODO entries.
13538 T Show entries with a specific TODO keyword.
13539 m Show entries selected by a tags/property match.
13540 p Enter a property name and its value (both with completion on existing
13541 names/values) and show entries with that property.
13542 r Show entries matching a regular expression (`/' can be used as well).
13543 b Show deadlines and scheduled items before a date.
13544 a Show deadlines and scheduled items after a date.
13545 d Show deadlines due within `org-deadline-warning-days'.
13546 D Show deadlines and scheduled items between a date range."
13547 (interactive "P")
13548 (let (ans kwd value ts-type)
13549 (setq type (or type org-sparse-tree-default-date-type))
13550 (setq org-ts-type type)
13551 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range\n [c]ycle through date types: %s"
13552 (cond ((eq type 'all) "all timestamps")
13553 ((eq type 'scheduled) "only scheduled")
13554 ((eq type 'deadline) "only deadline")
13555 ((eq type 'active) "only active timestamps")
13556 ((eq type 'inactive) "only inactive timestamps")
13557 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13558 ((eq type 'closed) "with a closed time-stamp")
13559 (t "scheduled/deadline")))
13560 (setq ans (read-char-exclusive))
13561 (cond
13562 ((equal ans ?c)
13563 (org-sparse-tree
13564 arg (cadr (member type '(scheduled-or-deadline
13565 all scheduled deadline active inactive closed)))))
13566 ((equal ans ?d)
13567 (call-interactively 'org-check-deadlines))
13568 ((equal ans ?b)
13569 (call-interactively 'org-check-before-date))
13570 ((equal ans ?a)
13571 (call-interactively 'org-check-after-date))
13572 ((equal ans ?D)
13573 (call-interactively 'org-check-dates-range))
13574 ((equal ans ?t)
13575 (call-interactively 'org-show-todo-tree))
13576 ((equal ans ?T)
13577 (org-show-todo-tree '(4)))
13578 ((member ans '(?T ?m))
13579 (call-interactively 'org-match-sparse-tree))
13580 ((member ans '(?p ?P))
13581 (setq kwd (org-icompleting-read "Property: "
13582 (mapcar 'list (org-buffer-property-keys))))
13583 (setq value (org-icompleting-read "Value: "
13584 (mapcar 'list (org-property-values kwd))))
13585 (unless (string-match "\\`{.*}\\'" value)
13586 (setq value (concat "\"" value "\"")))
13587 (org-match-sparse-tree arg (concat kwd "=" value)))
13588 ((member ans '(?r ?R ?/))
13589 (call-interactively 'org-occur))
13590 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13592 (defvar org-occur-highlights nil
13593 "List of overlays used for occur matches.")
13594 (make-variable-buffer-local 'org-occur-highlights)
13595 (defvar org-occur-parameters nil
13596 "Parameters of the active org-occur calls.
13597 This is a list, each call to org-occur pushes as cons cell,
13598 containing the regular expression and the callback, onto the list.
13599 The list can contain several entries if `org-occur' has been called
13600 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13601 will only contain one set of parameters. When the highlights are
13602 removed (for example with `C-c C-c', or with the next edit (depending
13603 on `org-remove-highlights-with-change'), this variable is emptied
13604 as well.")
13605 (make-variable-buffer-local 'org-occur-parameters)
13607 (defun org-occur (regexp &optional keep-previous callback)
13608 "Make a compact tree which shows all matches of REGEXP.
13609 The tree will show the lines where the regexp matches, and all higher
13610 headlines above the match. It will also show the heading after the match,
13611 to make sure editing the matching entry is easy.
13612 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13613 call to `org-occur' will be kept, to allow stacking of calls to this
13614 command.
13615 If CALLBACK is non-nil, it is a function which is called to confirm
13616 that the match should indeed be shown."
13617 (interactive "sRegexp: \nP")
13618 (when (equal regexp "")
13619 (user-error "Regexp cannot be empty"))
13620 (unless keep-previous
13621 (org-remove-occur-highlights nil nil t))
13622 (push (cons regexp callback) org-occur-parameters)
13623 (let ((cnt 0))
13624 (save-excursion
13625 (goto-char (point-min))
13626 (if (or (not keep-previous) ; do not want to keep
13627 (not org-occur-highlights)) ; no previous matches
13628 ;; hide everything
13629 (org-overview))
13630 (while (re-search-forward regexp nil t)
13631 (when (or (not callback)
13632 (save-match-data (funcall callback)))
13633 (setq cnt (1+ cnt))
13634 (when org-highlight-sparse-tree-matches
13635 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13636 (org-show-context 'occur-tree))))
13637 (when org-remove-highlights-with-change
13638 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13639 nil 'local))
13640 (unless org-sparse-tree-open-archived-trees
13641 (org-hide-archived-subtrees (point-min) (point-max)))
13642 (run-hooks 'org-occur-hook)
13643 (if (org-called-interactively-p 'interactive)
13644 (message "%d match(es) for regexp %s" cnt regexp))
13645 cnt))
13647 (defun org-occur-next-match (&optional n reset)
13648 "Function for `next-error-function' to find sparse tree matches.
13649 N is the number of matches to move, when negative move backwards.
13650 RESET is entirely ignored - this function always goes back to the
13651 starting point when no match is found."
13652 (let* ((limit (if (< n 0) (point-min) (point-max)))
13653 (search-func (if (< n 0)
13654 'previous-single-char-property-change
13655 'next-single-char-property-change))
13656 (n (abs n))
13657 (pos (point))
13659 (catch 'exit
13660 (while (setq p1 (funcall search-func (point) 'org-type))
13661 (when (equal p1 limit)
13662 (goto-char pos)
13663 (error "No more matches"))
13664 (when (equal (get-char-property p1 'org-type) 'org-occur)
13665 (setq n (1- n))
13666 (when (= n 0)
13667 (goto-char p1)
13668 (throw 'exit (point))))
13669 (goto-char p1))
13670 (goto-char p1)
13671 (error "No more matches"))))
13673 (defun org-show-context (&optional key)
13674 "Make sure point and context are visible.
13675 How much context is shown depends upon the variables
13676 `org-show-hierarchy-above', `org-show-following-heading',
13677 `org-show-entry-below' and `org-show-siblings'."
13678 (let ((heading-p (org-at-heading-p t))
13679 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13680 (following-p (org-get-alist-option org-show-following-heading key))
13681 (entry-p (org-get-alist-option org-show-entry-below key))
13682 (siblings-p (org-get-alist-option org-show-siblings key)))
13683 ;; Show heading or entry text
13684 (if (and heading-p (not entry-p))
13685 (org-flag-heading nil) ; only show the heading
13686 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13687 (org-show-hidden-entry))) ; show entire entry
13688 (when following-p
13689 ;; Show next sibling, or heading below text
13690 (save-excursion
13691 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13692 (org-flag-heading nil))))
13693 (when siblings-p (org-show-siblings))
13694 (when hierarchy-p
13695 ;; show all higher headings, possibly with siblings
13696 (save-excursion
13697 (while (and (condition-case nil
13698 (progn (org-up-heading-all 1) t)
13699 (error nil))
13700 (not (bobp)))
13701 (org-flag-heading nil)
13702 (when siblings-p (org-show-siblings)))))
13703 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13705 (defvar org-reveal-start-hook nil
13706 "Hook run before revealing a location.")
13708 (defun org-reveal (&optional siblings)
13709 "Show current entry, hierarchy above it, and the following headline.
13710 This can be used to show a consistent set of context around locations
13711 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13712 not t for the search context.
13714 With optional argument SIBLINGS, on each level of the hierarchy all
13715 siblings are shown. This repairs the tree structure to what it would
13716 look like when opened with hierarchical calls to `org-cycle'.
13717 With double optional argument \\[universal-argument] \\[universal-argument], \
13718 go to the parent and show the
13719 entire tree."
13720 (interactive "P")
13721 (run-hooks 'org-reveal-start-hook)
13722 (let ((org-show-hierarchy-above t)
13723 (org-show-following-heading t)
13724 (org-show-siblings (if siblings t org-show-siblings)))
13725 (org-show-context nil))
13726 (when (equal siblings '(16))
13727 (save-excursion
13728 (when (org-up-heading-safe)
13729 (org-show-subtree)
13730 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13732 (defun org-highlight-new-match (beg end)
13733 "Highlight from BEG to END and mark the highlight is an occur headline."
13734 (let ((ov (make-overlay beg end)))
13735 (overlay-put ov 'face 'secondary-selection)
13736 (overlay-put ov 'org-type 'org-occur)
13737 (push ov org-occur-highlights)))
13739 (defun org-remove-occur-highlights (&optional beg end noremove)
13740 "Remove the occur highlights from the buffer.
13741 BEG and END are ignored. If NOREMOVE is nil, remove this function
13742 from the `before-change-functions' in the current buffer."
13743 (interactive)
13744 (unless org-inhibit-highlight-removal
13745 (mapc 'delete-overlay org-occur-highlights)
13746 (setq org-occur-highlights nil)
13747 (setq org-occur-parameters nil)
13748 (unless noremove
13749 (remove-hook 'before-change-functions
13750 'org-remove-occur-highlights 'local))))
13752 ;;;; Priorities
13754 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13755 "Regular expression matching the priority indicator.")
13757 (defvar org-remove-priority-next-time nil)
13759 (defun org-priority-up ()
13760 "Increase the priority of the current item."
13761 (interactive)
13762 (org-priority 'up))
13764 (defun org-priority-down ()
13765 "Decrease the priority of the current item."
13766 (interactive)
13767 (org-priority 'down))
13769 (defun org-priority (&optional action show)
13770 "Change the priority of an item.
13771 ACTION can be `set', `up', `down', or a character."
13772 (interactive "P")
13773 (if (equal action '(4))
13774 (org-show-priority)
13775 (unless org-enable-priority-commands
13776 (user-error "Priority commands are disabled"))
13777 (setq action (or action 'set))
13778 (let (current new news have remove)
13779 (save-excursion
13780 (org-back-to-heading t)
13781 (if (looking-at org-priority-regexp)
13782 (setq current (string-to-char (match-string 2))
13783 have t))
13784 (cond
13785 ((eq action 'remove)
13786 (setq remove t new ?\ ))
13787 ((or (eq action 'set)
13788 (if (featurep 'xemacs) (characterp action) (integerp action)))
13789 (if (not (eq action 'set))
13790 (setq new action)
13791 (message "Priority %c-%c, SPC to remove: "
13792 org-highest-priority org-lowest-priority)
13793 (save-match-data
13794 (setq new (read-char-exclusive))))
13795 (if (and (= (upcase org-highest-priority) org-highest-priority)
13796 (= (upcase org-lowest-priority) org-lowest-priority))
13797 (setq new (upcase new)))
13798 (cond ((equal new ?\ ) (setq remove t))
13799 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13800 (user-error "Priority must be between `%c' and `%c'"
13801 org-highest-priority org-lowest-priority))))
13802 ((eq action 'up)
13803 (setq new (if have
13804 (1- current) ; normal cycling
13805 ;; last priority was empty
13806 (if (eq last-command this-command)
13807 org-lowest-priority ; wrap around empty to lowest
13808 ;; default
13809 (if org-priority-start-cycle-with-default
13810 org-default-priority
13811 (1- org-default-priority))))))
13812 ((eq action 'down)
13813 (setq new (if have
13814 (1+ current) ; normal cycling
13815 ;; last priority was empty
13816 (if (eq last-command this-command)
13817 org-highest-priority ; wrap around empty to highest
13818 ;; default
13819 (if org-priority-start-cycle-with-default
13820 org-default-priority
13821 (1+ org-default-priority))))))
13822 (t (user-error "Invalid action")))
13823 (if (or (< (upcase new) org-highest-priority)
13824 (> (upcase new) org-lowest-priority))
13825 (if (and (memq action '(up down))
13826 (not have) (not (eq last-command this-command)))
13827 ;; `new' is from default priority
13828 (error
13829 "The default can not be set, see `org-default-priority' why")
13830 ;; normal cycling: `new' is beyond highest/lowest priority
13831 ;; and is wrapped around to the empty priority
13832 (setq remove t)))
13833 (setq news (format "%c" new))
13834 (if have
13835 (if remove
13836 (replace-match "" t t nil 1)
13837 (replace-match news t t nil 2))
13838 (if remove
13839 (user-error "No priority cookie found in line")
13840 (let ((case-fold-search nil))
13841 (looking-at org-todo-line-regexp))
13842 (if (match-end 2)
13843 (progn
13844 (goto-char (match-end 2))
13845 (insert " [#" news "]"))
13846 (goto-char (match-beginning 3))
13847 (insert "[#" news "] "))))
13848 (org-preserve-lc (org-set-tags nil 'align)))
13849 (if remove
13850 (message "Priority removed")
13851 (message "Priority of current item set to %s" news)))))
13853 (defun org-show-priority ()
13854 "Show the priority of the current item.
13855 This priority is composed of the main priority given with the [#A] cookies,
13856 and by additional input from the age of a schedules or deadline entry."
13857 (interactive)
13858 (let ((pri (if (eq major-mode 'org-agenda-mode)
13859 (org-get-at-bol 'priority)
13860 (save-excursion
13861 (save-match-data
13862 (beginning-of-line)
13863 (and (looking-at org-heading-regexp)
13864 (org-get-priority (match-string 0))))))))
13865 (message "Priority is %d" (if pri pri -1000))))
13867 (defun org-get-priority (s)
13868 "Find priority cookie and return priority."
13869 (save-match-data
13870 (if (functionp org-get-priority-function)
13871 (funcall org-get-priority-function)
13872 (if (not (string-match org-priority-regexp s))
13873 (* 1000 (- org-lowest-priority org-default-priority))
13874 (* 1000 (- org-lowest-priority
13875 (string-to-char (match-string 2 s))))))))
13877 ;;;; Tags
13879 (defvar org-agenda-archives-mode)
13880 (defvar org-map-continue-from nil
13881 "Position from where mapping should continue.
13882 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13884 (defvar org-scanner-tags nil
13885 "The current tag list while the tags scanner is running.")
13886 (defvar org-trust-scanner-tags nil
13887 "Should `org-get-tags-at' use the tags for the scanner.
13888 This is for internal dynamical scoping only.
13889 When this is non-nil, the function `org-get-tags-at' will return the value
13890 of `org-scanner-tags' instead of building the list by itself. This
13891 can lead to large speed-ups when the tags scanner is used in a file with
13892 many entries, and when the list of tags is retrieved, for example to
13893 obtain a list of properties. Building the tags list for each entry in such
13894 a file becomes an N^2 operation - but with this variable set, it scales
13895 as N.")
13897 (defun org-scan-tags (action matcher todo-only &optional start-level)
13898 "Sca headline tags with inheritance and produce output ACTION.
13900 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13901 or `agenda' to produce an entry list for an agenda view. It can also be
13902 a Lisp form or a function that should be called at each matched headline, in
13903 this case the return value is a list of all return values from these calls.
13905 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13906 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13907 only lines with a not-done TODO keyword are included in the output.
13908 This should be the same variable that was scoped into
13909 and set by `org-make-tags-matcher' when it constructed MATCHER.
13911 START-LEVEL can be a string with asterisks, reducing the scope to
13912 headlines matching this string."
13913 (require 'org-agenda)
13914 (let* ((re (concat "^"
13915 (if start-level
13916 ;; Get the correct level to match
13917 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13918 org-outline-regexp)
13919 " *\\(\\<\\("
13920 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13921 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13922 (props (list 'face 'default
13923 'done-face 'org-agenda-done
13924 'undone-face 'default
13925 'mouse-face 'highlight
13926 'org-not-done-regexp org-not-done-regexp
13927 'org-todo-regexp org-todo-regexp
13928 'org-complex-heading-regexp org-complex-heading-regexp
13929 'help-echo
13930 (format "mouse-2 or RET jump to org file %s"
13931 (abbreviate-file-name
13932 (or (buffer-file-name (buffer-base-buffer))
13933 (buffer-name (buffer-base-buffer)))))))
13934 (org-map-continue-from nil)
13935 lspos tags tags-list
13936 (tags-alist (list (cons 0 org-file-tags)))
13937 (llast 0) rtn rtn1 level category i txt
13938 todo marker entry priority)
13939 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13940 (setq action (list 'lambda nil action)))
13941 (save-excursion
13942 (goto-char (point-min))
13943 (when (eq action 'sparse-tree)
13944 (org-overview)
13945 (org-remove-occur-highlights))
13946 (while (let (case-fold-search)
13947 (re-search-forward re nil t))
13948 (setq org-map-continue-from nil)
13949 (catch :skip
13950 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13951 tags (if (match-end 4) (org-match-string-no-properties 4)))
13952 (goto-char (setq lspos (match-beginning 0)))
13953 (setq level (org-reduced-level (org-outline-level))
13954 category (org-get-category))
13955 (setq i llast llast level)
13956 ;; remove tag lists from same and sublevels
13957 (while (>= i level)
13958 (when (setq entry (assoc i tags-alist))
13959 (setq tags-alist (delete entry tags-alist)))
13960 (setq i (1- i)))
13961 ;; add the next tags
13962 (when tags
13963 (setq tags (org-split-string tags ":")
13964 tags-alist
13965 (cons (cons level tags) tags-alist)))
13966 ;; compile tags for current headline
13967 (setq tags-list
13968 (if org-use-tag-inheritance
13969 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13970 tags)
13971 org-scanner-tags tags-list)
13972 (when org-use-tag-inheritance
13973 (setcdr (car tags-alist)
13974 (mapcar (lambda (x)
13975 (setq x (copy-sequence x))
13976 (org-add-prop-inherited x))
13977 (cdar tags-alist))))
13978 (when (and tags org-use-tag-inheritance
13979 (or (not (eq t org-use-tag-inheritance))
13980 org-tags-exclude-from-inheritance))
13981 ;; selective inheritance, remove uninherited ones
13982 (setcdr (car tags-alist)
13983 (org-remove-uninherited-tags (cdar tags-alist))))
13984 (when (and
13986 ;; eval matcher only when the todo condition is OK
13987 (and (or (not todo-only) (member todo org-not-done-keywords))
13988 (let ((case-fold-search t) (org-trust-scanner-tags t))
13989 (eval matcher)))
13991 ;; Call the skipper, but return t if it does not skip,
13992 ;; so that the `and' form continues evaluating
13993 (progn
13994 (unless (eq action 'sparse-tree) (org-agenda-skip))
13997 ;; Check if timestamps are deselecting this entry
13998 (or (not todo-only)
13999 (and (member todo org-not-done-keywords)
14000 (or (not org-agenda-tags-todo-honor-ignore-options)
14001 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14003 ;; select this headline
14004 (cond
14005 ((eq action 'sparse-tree)
14006 (and org-highlight-sparse-tree-matches
14007 (org-get-heading) (match-end 0)
14008 (org-highlight-new-match
14009 (match-beginning 1) (match-end 1)))
14010 (org-show-context 'tags-tree))
14011 ((eq action 'agenda)
14012 (setq txt (org-agenda-format-item
14014 (concat
14015 (if (eq org-tags-match-list-sublevels 'indented)
14016 (make-string (1- level) ?.) "")
14017 (org-get-heading))
14018 level category
14019 tags-list)
14020 priority (org-get-priority txt))
14021 (goto-char lspos)
14022 (setq marker (org-agenda-new-marker))
14023 (org-add-props txt props
14024 'org-marker marker 'org-hd-marker marker 'org-category category
14025 'todo-state todo
14026 'priority priority 'type "tagsmatch")
14027 (push txt rtn))
14028 ((functionp action)
14029 (setq org-map-continue-from nil)
14030 (save-excursion
14031 (setq rtn1 (funcall action))
14032 (push rtn1 rtn)))
14033 (t (user-error "Invalid action")))
14035 ;; if we are to skip sublevels, jump to end of subtree
14036 (unless org-tags-match-list-sublevels
14037 (org-end-of-subtree t)
14038 (backward-char 1))))
14039 ;; Get the correct position from where to continue
14040 (if org-map-continue-from
14041 (goto-char org-map-continue-from)
14042 (and (= (point) lspos) (end-of-line 1)))))
14043 (when (and (eq action 'sparse-tree)
14044 (not org-sparse-tree-open-archived-trees))
14045 (org-hide-archived-subtrees (point-min) (point-max)))
14046 (nreverse rtn)))
14048 (defun org-remove-uninherited-tags (tags)
14049 "Remove all tags that are not inherited from the list TAGS."
14050 (cond
14051 ((eq org-use-tag-inheritance t)
14052 (if org-tags-exclude-from-inheritance
14053 (org-delete-all org-tags-exclude-from-inheritance tags)
14054 tags))
14055 ((not org-use-tag-inheritance) nil)
14056 ((stringp org-use-tag-inheritance)
14057 (delq nil (mapcar
14058 (lambda (x)
14059 (if (and (string-match org-use-tag-inheritance x)
14060 (not (member x org-tags-exclude-from-inheritance)))
14061 x nil))
14062 tags)))
14063 ((listp org-use-tag-inheritance)
14064 (delq nil (mapcar
14065 (lambda (x)
14066 (if (member x org-use-tag-inheritance) x nil))
14067 tags)))))
14069 (defun org-match-sparse-tree (&optional todo-only match)
14070 "Create a sparse tree according to tags string MATCH.
14071 MATCH can contain positive and negative selection of tags, like
14072 \"+WORK+URGENT-WITHBOSS\".
14073 If optional argument TODO-ONLY is non-nil, only select lines that are
14074 also TODO lines."
14075 (interactive "P")
14076 (org-agenda-prepare-buffers (list (current-buffer)))
14077 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14079 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14081 (defvar org-cached-props nil)
14082 (defun org-cached-entry-get (pom property)
14083 (if (or (eq t org-use-property-inheritance)
14084 (and (stringp org-use-property-inheritance)
14085 (string-match org-use-property-inheritance property))
14086 (and (listp org-use-property-inheritance)
14087 (member property org-use-property-inheritance)))
14088 ;; Caching is not possible, check it directly
14089 (org-entry-get pom property 'inherit)
14090 ;; Get all properties, so that we can do complicated checks easily
14091 (cdr (assoc property (or org-cached-props
14092 (setq org-cached-props
14093 (org-entry-properties pom)))))))
14095 (defun org-global-tags-completion-table (&optional files)
14096 "Return the list of all tags in all agenda buffer/files.
14097 Optional FILES argument is a list of files which can be used
14098 instead of the agenda files."
14099 (save-excursion
14100 (org-uniquify
14101 (delq nil
14102 (apply 'append
14103 (mapcar
14104 (lambda (file)
14105 (set-buffer (find-file-noselect file))
14106 (append (org-get-buffer-tags)
14107 (mapcar (lambda (x) (if (stringp (car-safe x))
14108 (list (car-safe x)) nil))
14109 org-tag-alist)))
14110 (if (and files (car files))
14111 files
14112 (org-agenda-files))))))))
14114 (defun org-make-tags-matcher (match)
14115 "Create the TAGS/TODO matcher form for the selection string MATCH.
14117 The variable `todo-only' is scoped dynamically into this function.
14118 It will be set to t if the matcher restricts matching to TODO entries,
14119 otherwise will not be touched.
14121 Returns a cons of the selection string MATCH and the constructed
14122 lisp form implementing the matcher. The matcher is to be evaluated
14123 at an Org entry, with point on the headline, and returns t if the
14124 entry matches the selection string MATCH. The returned lisp form
14125 references two variables with information about the entry, which
14126 must be bound around the form's evaluation: todo, the TODO keyword
14127 at the entry (or nil of none); and tags-list, the list of all tags
14128 at the entry including inherited ones. Additionally, the category
14129 of the entry (if any) must be specified as the text property
14130 'org-category on the headline.
14132 See also `org-scan-tags'.
14134 (declare (special todo-only))
14135 (unless (boundp 'todo-only)
14136 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14137 (unless match
14138 ;; Get a new match request, with completion against the global
14139 ;; tags table and the local tags in current buffer
14140 (let ((org-last-tags-completion-table
14141 (org-uniquify
14142 (delq nil (append (org-get-buffer-tags)
14143 (org-global-tags-completion-table))))))
14144 (setq match (org-completing-read-no-i
14145 "Match: " 'org-tags-completion-function nil nil nil
14146 'org-tags-history))))
14148 ;; Parse the string and create a lisp form
14149 (let ((match0 match)
14150 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14151 minus tag mm
14152 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14153 orterms term orlist re-p str-p level-p level-op time-p
14154 prop-p pn pv po gv rest (start 0) (ss 0))
14155 ;; Expand group tags
14156 (setq match (org-tags-expand match))
14158 ;; Check if there is a TODO part of this match, which would be the
14159 ;; part after a "/". TO make sure that this slash is not part of
14160 ;; a property value to be matched against, we also check that there
14161 ;; is no " after that slash.
14162 ;; First, find the last slash
14163 (while (string-match "/+" match ss)
14164 (setq start (match-beginning 0) ss (match-end 0)))
14165 (if (and (string-match "/+" match start)
14166 (not (save-match-data (string-match "\"" match start))))
14167 ;; match contains also a todo-matching request
14168 (progn
14169 (setq tagsmatch (substring match 0 (match-beginning 0))
14170 todomatch (substring match (match-end 0)))
14171 (if (string-match "^!" todomatch)
14172 (setq todo-only t todomatch (substring todomatch 1)))
14173 (if (string-match "^\\s-*$" todomatch)
14174 (setq todomatch nil)))
14175 ;; only matching tags
14176 (setq tagsmatch match todomatch nil))
14178 ;; Make the tags matcher
14179 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14180 (setq tagsmatcher t)
14181 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14182 (while (setq term (pop orterms))
14183 (while (and (equal (substring term -1) "\\") orterms)
14184 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14185 (while (string-match re term)
14186 (setq rest (substring term (match-end 0))
14187 minus (and (match-end 1)
14188 (equal (match-string 1 term) "-"))
14189 tag (save-match-data (replace-regexp-in-string
14190 "\\\\-" "-"
14191 (match-string 2 term)))
14192 re-p (equal (string-to-char tag) ?{)
14193 level-p (match-end 4)
14194 prop-p (match-end 5)
14195 mm (cond
14196 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14197 (level-p
14198 (setq level-op (org-op-to-function (match-string 3 term)))
14199 `(,level-op level ,(string-to-number
14200 (match-string 4 term))))
14201 (prop-p
14202 (setq pn (match-string 5 term)
14203 po (match-string 6 term)
14204 pv (match-string 7 term)
14205 re-p (equal (string-to-char pv) ?{)
14206 str-p (equal (string-to-char pv) ?\")
14207 time-p (save-match-data
14208 (string-match "^\"[[<].*[]>]\"$" pv))
14209 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14210 (if time-p (setq pv (org-matcher-time pv)))
14211 (setq po (org-op-to-function po (if time-p 'time str-p)))
14212 (cond
14213 ((equal pn "CATEGORY")
14214 (setq gv '(get-text-property (point) 'org-category)))
14215 ((equal pn "TODO")
14216 (setq gv 'todo))
14218 (setq gv `(org-cached-entry-get nil ,pn))))
14219 (if re-p
14220 (if (eq po 'org<>)
14221 `(not (string-match ,pv (or ,gv "")))
14222 `(string-match ,pv (or ,gv "")))
14223 (if str-p
14224 `(,po (or ,gv "") ,pv)
14225 `(,po (string-to-number (or ,gv ""))
14226 ,(string-to-number pv) ))))
14227 (t `(member ,tag tags-list)))
14228 mm (if minus (list 'not mm) mm)
14229 term rest)
14230 (push mm tagsmatcher))
14231 (push (if (> (length tagsmatcher) 1)
14232 (cons 'and tagsmatcher)
14233 (car tagsmatcher))
14234 orlist)
14235 (setq tagsmatcher nil))
14236 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14237 (setq tagsmatcher
14238 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14239 ;; Make the todo matcher
14240 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14241 (setq todomatcher t)
14242 (setq orterms (org-split-string todomatch "|") orlist nil)
14243 (while (setq term (pop orterms))
14244 (while (string-match re term)
14245 (setq minus (and (match-end 1)
14246 (equal (match-string 1 term) "-"))
14247 kwd (match-string 2 term)
14248 re-p (equal (string-to-char kwd) ?{)
14249 term (substring term (match-end 0))
14250 mm (if re-p
14251 `(string-match ,(substring kwd 1 -1) todo)
14252 (list 'equal 'todo kwd))
14253 mm (if minus (list 'not mm) mm))
14254 (push mm todomatcher))
14255 (push (if (> (length todomatcher) 1)
14256 (cons 'and todomatcher)
14257 (car todomatcher))
14258 orlist)
14259 (setq todomatcher nil))
14260 (setq todomatcher (if (> (length orlist) 1)
14261 (cons 'or orlist) (car orlist))))
14263 ;; Return the string and lisp forms of the matcher
14264 (setq matcher (if todomatcher
14265 (list 'and tagsmatcher todomatcher)
14266 tagsmatcher))
14267 (when todo-only
14268 (setq matcher (list 'and '(member todo org-not-done-keywords)
14269 matcher)))
14270 (cons match0 matcher)))
14272 (defun org-tags-expand (match &optional single-as-list downcased)
14273 "Expand group tags in MATCH.
14275 This replaces every group tag in MATCH with a regexp tag search.
14276 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14277 will be replaced like this:
14279 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14280 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14281 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14283 Replacing by a regexp preserves the structure of the match.
14284 E.g., this expansion
14286 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14288 will match anything tagged with \"Lab\" and \"Home\", or tagged
14289 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14291 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14292 assumed to be a single group tag, and the function will return
14293 the list of tags in this group.
14295 When DOWNCASE is non-nil, expand downcased TAGS."
14296 (if org-group-tags
14297 (let* ((case-fold-search t)
14298 (stable org-mode-syntax-table)
14299 (tal (or org-tag-groups-alist-for-agenda
14300 org-tag-groups-alist))
14301 (tal (if downcased
14302 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14303 (tml (mapcar 'car tal))
14304 (rtnmatch match) rpl)
14305 ;; @ and _ are allowed as word-components in tags
14306 (modify-syntax-entry ?@ "w" stable)
14307 (modify-syntax-entry ?_ "w" stable)
14308 (while (and tml
14309 (with-syntax-table stable
14310 (string-match
14311 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14312 (regexp-opt tml) "\\>\\)") rtnmatch)))
14313 (let* ((dir (match-string 1 rtnmatch))
14314 (tag (match-string 2 rtnmatch))
14315 (tag (if downcased (downcase tag) tag)))
14316 (setq tml (delete tag tml))
14317 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14318 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14319 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14320 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14321 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14322 (if single-as-list
14323 (or (reverse rpl) (list rtnmatch))
14324 rtnmatch))
14325 (if single-as-list (list (if downcased (downcase match) match))
14326 match)))
14328 (defun org-op-to-function (op &optional stringp)
14329 "Turn an operator into the appropriate function."
14330 (setq op
14331 (cond
14332 ((equal op "<" ) '(< string< org-time<))
14333 ((equal op ">" ) '(> org-string> org-time>))
14334 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14335 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14336 ((member op '("=" "==")) '(= string= org-time=))
14337 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14338 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14340 (defun org<> (a b) (not (= a b)))
14341 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14342 (defun org-string>= (a b) (not (string< a b)))
14343 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14344 (defun org-string<> (a b) (not (string= a b)))
14345 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14346 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14347 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14348 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14349 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14350 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14351 (defun org-2ft (s)
14352 "Convert S to a floating point time.
14353 If S is already a number, just return it. If it is a string, parse
14354 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14355 (cond
14356 ((numberp s) s)
14357 ((stringp s)
14358 (condition-case nil
14359 (float-time (apply 'encode-time (org-parse-time-string s)))
14360 (error 0.)))
14361 (t 0.)))
14363 (defun org-time-today ()
14364 "Time in seconds today at 0:00.
14365 Returns the float number of seconds since the beginning of the
14366 epoch to the beginning of today (00:00)."
14367 (float-time (apply 'encode-time
14368 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14370 (defun org-matcher-time (s)
14371 "Interpret a time comparison value."
14372 (save-match-data
14373 (cond
14374 ((string= s "<now>") (float-time))
14375 ((string= s "<today>") (org-time-today))
14376 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14377 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14378 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14379 (+ (org-time-today)
14380 (* (string-to-number (match-string 1 s))
14381 (cdr (assoc (match-string 2 s)
14382 '(("d" . 86400.0) ("w" . 604800.0)
14383 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14384 (t (org-2ft s)))))
14386 (defun org-match-any-p (re list)
14387 "Does re match any element of list?"
14388 (setq list (mapcar (lambda (x) (string-match re x)) list))
14389 (delq nil list))
14391 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14392 (defvar org-tags-overlay (make-overlay 1 1))
14393 (org-detach-overlay org-tags-overlay)
14395 (defun org-get-local-tags-at (&optional pos)
14396 "Get a list of tags defined in the current headline."
14397 (org-get-tags-at pos 'local))
14399 (defun org-get-local-tags ()
14400 "Get a list of tags defined in the current headline."
14401 (org-get-tags-at nil 'local))
14403 (defun org-get-tags-at (&optional pos local)
14404 "Get a list of all headline tags applicable at POS.
14405 POS defaults to point. If tags are inherited, the list contains
14406 the targets in the same sequence as the headlines appear, i.e.
14407 the tags of the current headline come last.
14408 When LOCAL is non-nil, only return tags from the current headline,
14409 ignore inherited ones."
14410 (interactive)
14411 (if (and org-trust-scanner-tags
14412 (or (not pos) (equal pos (point)))
14413 (not local))
14414 org-scanner-tags
14415 (let (tags ltags lastpos parent)
14416 (save-excursion
14417 (save-restriction
14418 (widen)
14419 (goto-char (or pos (point)))
14420 (save-match-data
14421 (catch 'done
14422 (condition-case nil
14423 (progn
14424 (org-back-to-heading t)
14425 (while (not (equal lastpos (point)))
14426 (setq lastpos (point))
14427 (when (looking-at
14428 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14429 (setq ltags (org-split-string
14430 (org-match-string-no-properties 1) ":"))
14431 (when parent
14432 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14433 (setq tags (append
14434 (if parent
14435 (org-remove-uninherited-tags ltags)
14436 ltags)
14437 tags)))
14438 (or org-use-tag-inheritance (throw 'done t))
14439 (if local (throw 'done t))
14440 (or (org-up-heading-safe) (error nil))
14441 (setq parent t)))
14442 (error nil)))))
14443 (if local
14444 tags
14445 (reverse (delete-dups
14446 (reverse (append
14447 (org-remove-uninherited-tags
14448 org-file-tags) tags)))))))))
14450 (defun org-add-prop-inherited (s)
14451 (add-text-properties 0 (length s) '(inherited t) s)
14454 (defun org-toggle-tag (tag &optional onoff)
14455 "Toggle the tag TAG for the current line.
14456 If ONOFF is `on' or `off', don't toggle but set to this state."
14457 (let (res current)
14458 (save-excursion
14459 (org-back-to-heading t)
14460 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14461 (point-at-eol) t)
14462 (progn
14463 (setq current (match-string 1))
14464 (replace-match ""))
14465 (setq current ""))
14466 (setq current (nreverse (org-split-string current ":")))
14467 (cond
14468 ((eq onoff 'on)
14469 (setq res t)
14470 (or (member tag current) (push tag current)))
14471 ((eq onoff 'off)
14472 (or (not (member tag current)) (setq current (delete tag current))))
14473 (t (if (member tag current)
14474 (setq current (delete tag current))
14475 (setq res t)
14476 (push tag current))))
14477 (end-of-line 1)
14478 (if current
14479 (progn
14480 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14481 (org-set-tags nil t))
14482 (delete-horizontal-space))
14483 (run-hooks 'org-after-tags-change-hook))
14484 res))
14486 (defun org-align-tags-here (to-col)
14487 ;; Assumes that this is a headline
14488 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14489 (beginning-of-line 1)
14490 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14491 (< pos (match-beginning 2)))
14492 (progn
14493 (setq tags-l (- (match-end 2) (match-beginning 2)))
14494 (goto-char (match-beginning 1))
14495 (insert " ")
14496 (delete-region (point) (1+ (match-beginning 2)))
14497 (setq ncol (max (current-column)
14498 (1+ col)
14499 (if (> to-col 0)
14500 to-col
14501 (- (abs to-col) tags-l))))
14502 (setq p (point))
14503 (insert (make-string (- ncol (current-column)) ?\ ))
14504 (setq ncol (current-column))
14505 (when indent-tabs-mode (tabify p (point-at-eol)))
14506 (org-move-to-column (min ncol col) t nil t))
14507 (goto-char pos))))
14509 (defun org-set-tags-command (&optional arg just-align)
14510 "Call the set-tags command for the current entry."
14511 (interactive "P")
14512 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14513 (org-set-tags arg just-align)
14514 (save-excursion
14515 (unless (and (org-region-active-p)
14516 org-loop-over-headlines-in-active-region)
14517 (org-back-to-heading t))
14518 (org-set-tags arg just-align))))
14520 (defun org-set-tags-to (data)
14521 "Set the tags of the current entry to DATA, replacing the current tags.
14522 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14523 If DATA is nil or the empty string, any tags will be removed."
14524 (interactive "sTags: ")
14525 (setq data
14526 (cond
14527 ((eq data nil) "")
14528 ((equal data "") "")
14529 ((stringp data)
14530 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14531 ":"))
14532 ((listp data)
14533 (concat ":" (mapconcat 'identity data ":") ":"))))
14534 (when data
14535 (save-excursion
14536 (org-back-to-heading t)
14537 (when (looking-at org-complex-heading-regexp)
14538 (if (match-end 5)
14539 (progn
14540 (goto-char (match-beginning 5))
14541 (insert data)
14542 (delete-region (point) (point-at-eol))
14543 (org-set-tags nil 'align))
14544 (goto-char (point-at-eol))
14545 (insert " " data)
14546 (org-set-tags nil 'align)))
14547 (beginning-of-line 1)
14548 (if (looking-at ".*?\\([ \t]+\\)$")
14549 (delete-region (match-beginning 1) (match-end 1))))))
14551 (defun org-align-all-tags ()
14552 "Align the tags i all headings."
14553 (interactive)
14554 (save-excursion
14555 (or (ignore-errors (org-back-to-heading t))
14556 (outline-next-heading))
14557 (if (org-at-heading-p)
14558 (org-set-tags t)
14559 (message "No headings"))))
14561 (defvar org-indent-indentation-per-level)
14562 (defun org-set-tags (&optional arg just-align)
14563 "Set the tags for the current headline.
14564 With prefix ARG, realign all tags in headings in the current buffer.
14565 When JUST-ALIGN is non-nil, only align tags.
14566 When JUST-ALIGN is 'ignore-column, align tags without trying to set
14567 the column by ignoring invisible text."
14568 (interactive "P")
14569 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14570 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14571 'region-start-level 'region))
14572 org-loop-over-headlines-in-active-region)
14573 (org-map-entries
14574 ;; We don't use ARG and JUST-ALIGN here because these args
14575 ;; are not useful when looping over headlines.
14576 `(org-set-tags)
14577 org-loop-over-headlines-in-active-region
14578 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14579 (let* ((re org-outline-regexp-bol)
14580 (current (unless arg (org-get-tags-string)))
14581 (col (current-column))
14582 (org-setting-tags t)
14583 table current-tags inherited-tags ; computed below when needed
14584 tags p0 c0 c1 rpl di tc level)
14585 (if arg
14586 (save-excursion
14587 (goto-char (point-min))
14588 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14589 (while (re-search-forward re nil t)
14590 (org-set-tags nil t)
14591 (end-of-line 1)))
14592 (message "All tags realigned to column %d" org-tags-column))
14593 (if just-align
14594 (setq tags current)
14595 ;; Get a new set of tags from the user
14596 (save-excursion
14597 (setq table (append org-tag-persistent-alist
14598 (or org-tag-alist (org-get-buffer-tags))
14599 (and
14600 org-complete-tags-always-offer-all-agenda-tags
14601 (org-global-tags-completion-table
14602 (org-agenda-files))))
14603 org-last-tags-completion-table table
14604 current-tags (org-split-string current ":")
14605 inherited-tags (nreverse
14606 (nthcdr (length current-tags)
14607 (nreverse (org-get-tags-at))))
14608 tags
14609 (if (or (eq t org-use-fast-tag-selection)
14610 (and org-use-fast-tag-selection
14611 (delq nil (mapcar 'cdr table))))
14612 (org-fast-tag-selection
14613 current-tags inherited-tags table
14614 (if org-fast-tag-selection-include-todo
14615 org-todo-key-alist))
14616 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14617 (org-trim
14618 (org-icompleting-read "Tags: "
14619 'org-tags-completion-function
14620 nil nil current 'org-tags-history))))))
14621 (while (string-match "[-+&]+" tags)
14622 ;; No boolean logic, just a list
14623 (setq tags (replace-match ":" t t tags))))
14625 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14627 (if org-tags-sort-function
14628 (setq tags (mapconcat 'identity
14629 (sort (org-split-string
14630 tags (org-re "[^[:alnum:]_@#%]+"))
14631 org-tags-sort-function) ":")))
14633 (if (string-match "\\`[\t ]*\\'" tags)
14634 (setq tags "")
14635 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14636 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14638 ;; Insert new tags at the correct column
14639 (beginning-of-line 1)
14640 (setq level (or (and (looking-at org-outline-regexp)
14641 (- (match-end 0) (point) 1))
14643 (cond
14644 ((and (equal current "") (equal tags "")))
14645 ((re-search-forward
14646 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14647 (point-at-eol) t)
14648 (if (equal tags "")
14649 (setq rpl "")
14650 (goto-char (match-beginning 0))
14651 (setq c0 (current-column)
14652 ;; compute offset for the case of org-indent-mode active
14653 di (if (org-bound-and-true-p org-indent-mode)
14654 (* (1- org-indent-indentation-per-level) (1- level))
14656 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14657 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14658 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14659 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14660 (replace-match rpl t t)
14661 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14662 tags)
14663 (t (error "Tags alignment failed")))
14664 (org-move-to-column col nil nil (not (eq just-align 'ignore-column)))
14665 (unless just-align
14666 (run-hooks 'org-after-tags-change-hook))))))
14668 (defun org-change-tag-in-region (beg end tag off)
14669 "Add or remove TAG for each entry in the region.
14670 This works in the agenda, and also in an org-mode buffer."
14671 (interactive
14672 (list (region-beginning) (region-end)
14673 (let ((org-last-tags-completion-table
14674 (if (derived-mode-p 'org-mode)
14675 (org-uniquify
14676 (delq nil (append (org-get-buffer-tags)
14677 (org-global-tags-completion-table))))
14678 (org-global-tags-completion-table))))
14679 (org-icompleting-read
14680 "Tag: " 'org-tags-completion-function nil nil nil
14681 'org-tags-history))
14682 (progn
14683 (message "[s]et or [r]emove? ")
14684 (equal (read-char-exclusive) ?r))))
14685 (if (fboundp 'deactivate-mark) (deactivate-mark))
14686 (let ((agendap (equal major-mode 'org-agenda-mode))
14687 l1 l2 m buf pos newhead (cnt 0))
14688 (goto-char end)
14689 (setq l2 (1- (org-current-line)))
14690 (goto-char beg)
14691 (setq l1 (org-current-line))
14692 (loop for l from l1 to l2 do
14693 (org-goto-line l)
14694 (setq m (get-text-property (point) 'org-hd-marker))
14695 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14696 (and agendap m))
14697 (setq buf (if agendap (marker-buffer m) (current-buffer))
14698 pos (if agendap m (point)))
14699 (with-current-buffer buf
14700 (save-excursion
14701 (save-restriction
14702 (goto-char pos)
14703 (setq cnt (1+ cnt))
14704 (org-toggle-tag tag (if off 'off 'on))
14705 (setq newhead (org-get-heading)))))
14706 (and agendap (org-agenda-change-all-lines newhead m))))
14707 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14709 (defun org-tags-completion-function (string predicate &optional flag)
14710 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14711 (confirm (lambda (x) (stringp (car x)))))
14712 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14713 (setq s1 (match-string 1 string)
14714 s2 (match-string 2 string))
14715 (setq s1 "" s2 string))
14716 (cond
14717 ((eq flag nil)
14718 ;; try completion
14719 (setq rtn (try-completion s2 ctable confirm))
14720 (if (stringp rtn)
14721 (setq rtn
14722 (concat s1 s2 (substring rtn (length s2))
14723 (if (and org-add-colon-after-tag-completion
14724 (assoc rtn ctable))
14725 ":" ""))))
14726 rtn)
14727 ((eq flag t)
14728 ;; all-completions
14729 (all-completions s2 ctable confirm))
14730 ((eq flag 'lambda)
14731 ;; exact match?
14732 (assoc s2 ctable)))))
14734 (defun org-fast-tag-insert (kwd tags face &optional end)
14735 "Insert KDW, and the TAGS, the latter with face FACE.
14736 Also insert END."
14737 (insert (format "%-12s" (concat kwd ":"))
14738 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14739 (or end "")))
14741 (defun org-fast-tag-show-exit (flag)
14742 (save-excursion
14743 (org-goto-line 3)
14744 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14745 (replace-match ""))
14746 (when flag
14747 (end-of-line 1)
14748 (org-move-to-column (- (window-width) 19) t)
14749 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14751 (defun org-set-current-tags-overlay (current prefix)
14752 "Add an overlay to CURRENT tag with PREFIX."
14753 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14754 (if (featurep 'xemacs)
14755 (org-overlay-display org-tags-overlay (concat prefix s)
14756 'secondary-selection)
14757 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14758 (org-overlay-display org-tags-overlay (concat prefix s)))))
14760 (defvar org-last-tag-selection-key nil)
14761 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14762 "Fast tag selection with single keys.
14763 CURRENT is the current list of tags in the headline, INHERITED is the
14764 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14765 possibly with grouping information. TODO-TABLE is a similar table with
14766 TODO keywords, should these have keys assigned to them.
14767 If the keys are nil, a-z are automatically assigned.
14768 Returns the new tags string, or nil to not change the current settings."
14769 (let* ((fulltable (append table todo-table))
14770 (maxlen (apply 'max (mapcar
14771 (lambda (x)
14772 (if (stringp (car x)) (string-width (car x)) 0))
14773 fulltable)))
14774 (buf (current-buffer))
14775 (expert (eq org-fast-tag-selection-single-key 'expert))
14776 (buffer-tags nil)
14777 (fwidth (+ maxlen 3 1 3))
14778 (ncol (/ (- (window-width) 4) fwidth))
14779 (i-face 'org-done)
14780 (c-face 'org-todo)
14781 tg cnt e c char c1 c2 ntable tbl rtn
14782 ov-start ov-end ov-prefix
14783 (exit-after-next org-fast-tag-selection-single-key)
14784 (done-keywords org-done-keywords)
14785 groups ingroup)
14786 (save-excursion
14787 (beginning-of-line 1)
14788 (if (looking-at
14789 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14790 (setq ov-start (match-beginning 1)
14791 ov-end (match-end 1)
14792 ov-prefix "")
14793 (setq ov-start (1- (point-at-eol))
14794 ov-end (1+ ov-start))
14795 (skip-chars-forward "^\n\r")
14796 (setq ov-prefix
14797 (concat
14798 (buffer-substring (1- (point)) (point))
14799 (if (> (current-column) org-tags-column)
14801 (make-string (- org-tags-column (current-column)) ?\ ))))))
14802 (move-overlay org-tags-overlay ov-start ov-end)
14803 (save-window-excursion
14804 (if expert
14805 (set-buffer (get-buffer-create " *Org tags*"))
14806 (delete-other-windows)
14807 (split-window-vertically)
14808 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14809 (erase-buffer)
14810 (org-set-local 'org-done-keywords done-keywords)
14811 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14812 (org-fast-tag-insert "Current" current c-face "\n\n")
14813 (org-fast-tag-show-exit exit-after-next)
14814 (org-set-current-tags-overlay current ov-prefix)
14815 (setq tbl fulltable char ?a cnt 0)
14816 (while (setq e (pop tbl))
14817 (cond
14818 ((equal (car e) :startgroup)
14819 (push '() groups) (setq ingroup t)
14820 (when (not (= cnt 0))
14821 (setq cnt 0)
14822 (insert "\n"))
14823 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14824 ((equal (car e) :endgroup)
14825 (setq ingroup nil cnt 0)
14826 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14827 ((equal e '(:newline))
14828 (when (not (= cnt 0))
14829 (setq cnt 0)
14830 (insert "\n")
14831 (setq e (car tbl))
14832 (while (equal (car tbl) '(:newline))
14833 (insert "\n")
14834 (setq tbl (cdr tbl)))))
14835 ((equal e '(:grouptags)) nil)
14837 (setq tg (copy-sequence (car e)) c2 nil)
14838 (if (cdr e)
14839 (setq c (cdr e))
14840 ;; automatically assign a character.
14841 (setq c1 (string-to-char
14842 (downcase (substring
14843 tg (if (= (string-to-char tg) ?@) 1 0)))))
14844 (if (or (rassoc c1 ntable) (rassoc c1 table))
14845 (while (or (rassoc char ntable) (rassoc char table))
14846 (setq char (1+ char)))
14847 (setq c2 c1))
14848 (setq c (or c2 char)))
14849 (if ingroup (push tg (car groups)))
14850 (setq tg (org-add-props tg nil 'face
14851 (cond
14852 ((not (assoc tg table))
14853 (org-get-todo-face tg))
14854 ((member tg current) c-face)
14855 ((member tg inherited) i-face))))
14856 (if (equal (caar tbl) :grouptags)
14857 (org-add-props tg nil 'face 'org-tag-group))
14858 (if (and (= cnt 0) (not ingroup)) (insert " "))
14859 (insert "[" c "] " tg (make-string
14860 (- fwidth 4 (length tg)) ?\ ))
14861 (push (cons tg c) ntable)
14862 (when (= (setq cnt (1+ cnt)) ncol)
14863 (insert "\n")
14864 (if ingroup (insert " "))
14865 (setq cnt 0)))))
14866 (setq ntable (nreverse ntable))
14867 (insert "\n")
14868 (goto-char (point-min))
14869 (if (not expert) (org-fit-window-to-buffer))
14870 (setq rtn
14871 (catch 'exit
14872 (while t
14873 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14874 (if (not groups) "no " "")
14875 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14876 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14877 (setq org-last-tag-selection-key c)
14878 (cond
14879 ((= c ?\r) (throw 'exit t))
14880 ((= c ?!)
14881 (setq groups (not groups))
14882 (goto-char (point-min))
14883 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14884 ((= c ?\C-c)
14885 (if (not expert)
14886 (org-fast-tag-show-exit
14887 (setq exit-after-next (not exit-after-next)))
14888 (setq expert nil)
14889 (delete-other-windows)
14890 (set-window-buffer (split-window-vertically) " *Org tags*")
14891 (org-switch-to-buffer-other-window " *Org tags*")
14892 (org-fit-window-to-buffer)))
14893 ((or (= c ?\C-g)
14894 (and (= c ?q) (not (rassoc c ntable))))
14895 (org-detach-overlay org-tags-overlay)
14896 (setq quit-flag t))
14897 ((= c ?\ )
14898 (setq current nil)
14899 (if exit-after-next (setq exit-after-next 'now)))
14900 ((= c ?\t)
14901 (condition-case nil
14902 (setq tg (org-icompleting-read
14903 "Tag: "
14904 (or buffer-tags
14905 (with-current-buffer buf
14906 (org-get-buffer-tags)))))
14907 (quit (setq tg "")))
14908 (when (string-match "\\S-" tg)
14909 (add-to-list 'buffer-tags (list tg))
14910 (if (member tg current)
14911 (setq current (delete tg current))
14912 (push tg current)))
14913 (if exit-after-next (setq exit-after-next 'now)))
14914 ((setq e (rassoc c todo-table) tg (car e))
14915 (with-current-buffer buf
14916 (save-excursion (org-todo tg)))
14917 (if exit-after-next (setq exit-after-next 'now)))
14918 ((setq e (rassoc c ntable) tg (car e))
14919 (if (member tg current)
14920 (setq current (delete tg current))
14921 (loop for g in groups do
14922 (if (member tg g)
14923 (mapc (lambda (x)
14924 (setq current (delete x current)))
14925 g)))
14926 (push tg current))
14927 (if exit-after-next (setq exit-after-next 'now))))
14929 ;; Create a sorted list
14930 (setq current
14931 (sort current
14932 (lambda (a b)
14933 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14934 (if (eq exit-after-next 'now) (throw 'exit t))
14935 (goto-char (point-min))
14936 (beginning-of-line 2)
14937 (delete-region (point) (point-at-eol))
14938 (org-fast-tag-insert "Current" current c-face)
14939 (org-set-current-tags-overlay current ov-prefix)
14940 (while (re-search-forward
14941 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14942 (setq tg (match-string 1))
14943 (add-text-properties
14944 (match-beginning 1) (match-end 1)
14945 (list 'face
14946 (cond
14947 ((member tg current) c-face)
14948 ((member tg inherited) i-face)
14949 (t (get-text-property (match-beginning 1) 'face))))))
14950 (goto-char (point-min)))))
14951 (org-detach-overlay org-tags-overlay)
14952 (if rtn
14953 (mapconcat 'identity current ":")
14954 nil))))
14956 (defun org-get-tags-string ()
14957 "Get the TAGS string in the current headline."
14958 (unless (org-at-heading-p t)
14959 (user-error "Not on a heading"))
14960 (save-excursion
14961 (beginning-of-line 1)
14962 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14963 (org-match-string-no-properties 1)
14964 "")))
14966 (defun org-get-tags ()
14967 "Get the list of tags specified in the current headline."
14968 (org-split-string (org-get-tags-string) ":"))
14970 (defun org-get-buffer-tags ()
14971 "Get a table of all tags used in the buffer, for completion."
14972 (let (tags)
14973 (save-excursion
14974 (goto-char (point-min))
14975 (while (re-search-forward
14976 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14977 (when (equal (char-after (point-at-bol 0)) ?*)
14978 (mapc (lambda (x) (add-to-list 'tags x))
14979 (org-split-string (org-match-string-no-properties 1) ":")))))
14980 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14981 (mapcar 'list tags)))
14983 ;;;; The mapping API
14985 (defun org-map-entries (func &optional match scope &rest skip)
14986 "Call FUNC at each headline selected by MATCH in SCOPE.
14988 FUNC is a function or a lisp form. The function will be called without
14989 arguments, with the cursor positioned at the beginning of the headline.
14990 The return values of all calls to the function will be collected and
14991 returned as a list.
14993 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14994 does not need to preserve point. After evaluation, the cursor will be
14995 moved to the end of the line (presumably of the headline of the
14996 processed entry) and search continues from there. Under some
14997 circumstances, this may not produce the wanted results. For example,
14998 if you have removed (e.g. archived) the current (sub)tree it could
14999 mean that the next entry will be skipped entirely. In such cases, you
15000 can specify the position from where search should continue by making
15001 FUNC set the variable `org-map-continue-from' to the desired buffer
15002 position.
15004 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15005 Only headlines that are matched by this query will be considered during
15006 the iteration. When MATCH is nil or t, all headlines will be
15007 visited by the iteration.
15009 SCOPE determines the scope of this command. It can be any of:
15011 nil The current buffer, respecting the restriction if any
15012 tree The subtree started with the entry at point
15013 region The entries within the active region, if any
15014 region-start-level
15015 The entries within the active region, but only those at
15016 the same level than the first one.
15017 file The current buffer, without restriction
15018 file-with-archives
15019 The current buffer, and any archives associated with it
15020 agenda All agenda files
15021 agenda-with-archives
15022 All agenda files with any archive files associated with them
15023 \(file1 file2 ...)
15024 If this is a list, all files in the list will be scanned
15026 The remaining args are treated as settings for the skipping facilities of
15027 the scanner. The following items can be given here:
15029 archive skip trees with the archive tag
15030 comment skip trees with the COMMENT keyword
15031 function or Emacs Lisp form:
15032 will be used as value for `org-agenda-skip-function', so
15033 whenever the function returns a position, FUNC will not be
15034 called for that entry and search will continue from the
15035 position returned
15037 If your function needs to retrieve the tags including inherited tags
15038 at the *current* entry, you can use the value of the variable
15039 `org-scanner-tags' which will be much faster than getting the value
15040 with `org-get-tags-at'. If your function gets properties with
15041 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15042 to t around the call to `org-entry-properties' to get the same speedup.
15043 Note that if your function moves around to retrieve tags and properties at
15044 a *different* entry, you cannot use these techniques."
15045 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15046 (not (org-region-active-p)))
15047 (let* ((org-agenda-archives-mode nil) ; just to make sure
15048 (org-agenda-skip-archived-trees (memq 'archive skip))
15049 (org-agenda-skip-comment-trees (memq 'comment skip))
15050 (org-agenda-skip-function
15051 (car (org-delete-all '(comment archive) skip)))
15052 (org-tags-match-list-sublevels t)
15053 (start-level (eq scope 'region-start-level))
15054 matcher file res
15055 org-todo-keywords-for-agenda
15056 org-done-keywords-for-agenda
15057 org-todo-keyword-alist-for-agenda
15058 org-tag-alist-for-agenda
15059 todo-only)
15061 (cond
15062 ((eq match t) (setq matcher t))
15063 ((eq match nil) (setq matcher t))
15064 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15066 (save-window-excursion
15067 (save-restriction
15068 (cond ((eq scope 'tree)
15069 (org-back-to-heading t)
15070 (org-narrow-to-subtree)
15071 (setq scope nil))
15072 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15073 (org-region-active-p))
15074 ;; If needed, set start-level to a string like "2"
15075 (when start-level
15076 (save-excursion
15077 (goto-char (region-beginning))
15078 (unless (org-at-heading-p) (outline-next-heading))
15079 (setq start-level (org-current-level))))
15080 (narrow-to-region (region-beginning)
15081 (save-excursion
15082 (goto-char (region-end))
15083 (unless (and (bolp) (org-at-heading-p))
15084 (outline-next-heading))
15085 (point)))
15086 (setq scope nil)))
15088 (if (not scope)
15089 (progn
15090 (org-agenda-prepare-buffers
15091 (list (buffer-file-name (current-buffer))))
15092 (setq res (org-scan-tags func matcher todo-only start-level)))
15093 ;; Get the right scope
15094 (cond
15095 ((and scope (listp scope) (symbolp (car scope)))
15096 (setq scope (eval scope)))
15097 ((eq scope 'agenda)
15098 (setq scope (org-agenda-files t)))
15099 ((eq scope 'agenda-with-archives)
15100 (setq scope (org-agenda-files t))
15101 (setq scope (org-add-archive-files scope)))
15102 ((eq scope 'file)
15103 (setq scope (list (buffer-file-name))))
15104 ((eq scope 'file-with-archives)
15105 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15106 (org-agenda-prepare-buffers scope)
15107 (while (setq file (pop scope))
15108 (with-current-buffer (org-find-base-buffer-visiting file)
15109 (save-excursion
15110 (save-restriction
15111 (widen)
15112 (goto-char (point-min))
15113 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15114 res)))
15116 ;;;; Properties
15118 ;;; Setting and retrieving properties
15120 (defconst org-special-properties
15121 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15122 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15123 "The special properties valid in Org-mode.
15125 These are properties that are not defined in the property drawer,
15126 but in some other way.")
15128 (defconst org-default-properties
15129 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15130 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15131 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15132 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15133 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15134 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15135 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15136 "Some properties that are used by Org-mode for various purposes.
15137 Being in this list makes sure that they are offered for completion.")
15139 (defun org-property-action ()
15140 "Do an action on properties."
15141 (interactive)
15142 (let (c)
15143 (org-at-property-p)
15144 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15145 (setq c (read-char-exclusive))
15146 (cond
15147 ((equal c ?s)
15148 (call-interactively 'org-set-property))
15149 ((equal c ?d)
15150 (call-interactively 'org-delete-property))
15151 ((equal c ?D)
15152 (call-interactively 'org-delete-property-globally))
15153 ((equal c ?c)
15154 (call-interactively 'org-compute-property-at-point))
15155 (t (user-error "No such property action %c" c)))))
15157 (defun org-inc-effort ()
15158 "Increment the value of the effort property in the current entry."
15159 (interactive)
15160 (org-set-effort nil t))
15162 (defvar org-clock-effort) ;; Defined in org-clock.el
15163 (defvar org-clock-current-task) ;; Defined in org-clock.el
15164 (defun org-set-effort (&optional value increment)
15165 "Set the effort property of the current entry.
15166 With numerical prefix arg, use the nth allowed value, 0 stands for the
15167 10th allowed value.
15169 When INCREMENT is non-nil, set the property to the next allowed value."
15170 (interactive "P")
15171 (if (equal value 0) (setq value 10))
15172 (let* ((completion-ignore-case t)
15173 (prop org-effort-property)
15174 (cur (org-entry-get nil prop))
15175 (allowed (org-property-get-allowed-values nil prop 'table))
15176 (existing (mapcar 'list (org-property-values prop)))
15177 (heading (nth 4 (org-heading-components)))
15179 (val (cond
15180 ((stringp value) value)
15181 ((and allowed (integerp value))
15182 (or (car (nth (1- value) allowed))
15183 (car (org-last allowed))))
15184 ((and allowed increment)
15185 (or (caadr (member (list cur) allowed))
15186 (user-error "Allowed effort values are not set")))
15187 (allowed
15188 (message "Select 1-9,0, [RET%s]: %s"
15189 (if cur (concat "=" cur) "")
15190 (mapconcat 'car allowed " "))
15191 (setq rpl (read-char-exclusive))
15192 (if (equal rpl ?\r)
15194 (setq rpl (- rpl ?0))
15195 (if (equal rpl 0) (setq rpl 10))
15196 (if (and (> rpl 0) (<= rpl (length allowed)))
15197 (car (nth (1- rpl) allowed))
15198 (org-completing-read "Effort: " allowed nil))))
15200 (let (org-completion-use-ido org-completion-use-iswitchb)
15201 (org-completing-read
15202 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15203 (concat "[" cur "]") "")
15204 ": ")
15205 existing nil nil "" nil cur))))))
15206 (unless (equal (org-entry-get nil prop) val)
15207 (org-entry-put nil prop val))
15208 (save-excursion
15209 (org-back-to-heading t)
15210 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15211 (when (string= heading org-clock-current-task)
15212 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15213 (org-clock-update-mode-line))
15214 (message "%s is now %s" prop val)))
15216 (defun org-at-property-p ()
15217 "Is cursor inside a property drawer?"
15218 (save-excursion
15219 (when (equal 'node-property (car (org-element-at-point)))
15220 (beginning-of-line 1)
15221 (looking-at org-property-re))))
15223 (defun org-get-property-block (&optional beg end force)
15224 "Return the (beg . end) range of the body of the property drawer.
15225 BEG and END are the beginning and end of the current subtree, or of
15226 the part before the first headline. If they are not given, they will
15227 be found. If the drawer does not exist and FORCE is non-nil, create
15228 the drawer."
15229 (catch 'exit
15230 (save-excursion
15231 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15232 (progn (org-back-to-heading t) (point))))
15233 (end (or end (and (not (outline-next-heading)) (point-max))
15234 (point))))
15235 (goto-char beg)
15236 (if (re-search-forward org-property-start-re end t)
15237 (setq beg (1+ (match-end 0)))
15238 (if force
15239 (save-excursion
15240 (org-insert-property-drawer)
15241 (setq end (progn (outline-next-heading) (point))))
15242 (throw 'exit nil))
15243 (goto-char beg)
15244 (if (re-search-forward org-property-start-re end t)
15245 (setq beg (1+ (match-end 0)))))
15246 (if (re-search-forward org-property-end-re end t)
15247 (setq end (match-beginning 0))
15248 (or force (throw 'exit nil))
15249 (goto-char beg)
15250 (setq end beg)
15251 (org-indent-line)
15252 (insert ":END:\n"))
15253 (cons beg end)))))
15255 (defun org-entry-properties (&optional pom which specific)
15256 "Get all properties of the entry at point-or-marker POM.
15257 This includes the TODO keyword, the tags, time strings for deadline,
15258 scheduled, and clocking, and any additional properties defined in the
15259 entry. The return value is an alist, keys may occur multiple times
15260 if the property key was used several times.
15261 POM may also be nil, in which case the current entry is used.
15262 If WHICH is nil or `all', get all properties. If WHICH is
15263 `special' or `standard', only get that subclass. If WHICH
15264 is a string only get exactly this property. SPECIFIC can be a string, the
15265 specific property we are interested in. Specifying it can speed
15266 things up because then unnecessary parsing is avoided."
15267 (setq which (or which 'all))
15268 (org-with-wide-buffer
15269 (org-with-point-at pom
15270 (let ((clockstr (substring org-clock-string 0 -1))
15271 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15272 (case-fold-search nil)
15273 beg end range props sum-props key key1 value string clocksum clocksumt)
15274 (when (and (derived-mode-p 'org-mode)
15275 (ignore-errors (org-back-to-heading t)))
15276 (setq beg (point))
15277 (setq sum-props (get-text-property (point) 'org-summaries))
15278 (setq clocksum (get-text-property (point) :org-clock-minutes)
15279 clocksumt (get-text-property (point) :org-clock-minutes-today))
15280 (outline-next-heading)
15281 (setq end (point))
15282 (when (memq which '(all special))
15283 ;; Get the special properties, like TODO and tags
15284 (goto-char beg)
15285 (when (and (or (not specific) (string= specific "TODO"))
15286 (looking-at org-todo-line-regexp) (match-end 2))
15287 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15288 (when (and (or (not specific) (string= specific "PRIORITY"))
15289 (looking-at org-priority-regexp))
15290 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15291 (when (or (not specific) (string= specific "FILE"))
15292 (push (cons "FILE" buffer-file-name) props))
15293 (when (and (or (not specific) (string= specific "TAGS"))
15294 (setq value (org-get-tags-string))
15295 (string-match "\\S-" value))
15296 (push (cons "TAGS" value) props))
15297 (when (and (or (not specific) (string= specific "ALLTAGS"))
15298 (setq value (org-get-tags-at)))
15299 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15300 ":"))
15301 props))
15302 (when (or (not specific) (string= specific "BLOCKED"))
15303 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15304 (when (or (not specific)
15305 (member specific
15306 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15307 "TIMESTAMP" "TIMESTAMP_IA")))
15308 (catch 'match
15309 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15310 (setq key (if (match-end 1)
15311 (substring (org-match-string-no-properties 1)
15312 0 -1))
15313 string (if (equal key clockstr)
15314 (org-trim
15315 (buffer-substring-no-properties
15316 (match-beginning 3) (goto-char
15317 (point-at-eol))))
15318 (substring (org-match-string-no-properties 3)
15319 1 -1)))
15320 ;; Get the correct property name from the key. This is
15321 ;; necessary if the user has configured time keywords.
15322 (setq key1 (concat key ":"))
15323 (cond
15324 ((not key)
15325 (setq key
15326 (if (= (char-after (match-beginning 3)) ?\[)
15327 "TIMESTAMP_IA" "TIMESTAMP")))
15328 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15329 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15330 ((equal key1 org-closed-string) (setq key "CLOSED"))
15331 ((equal key1 org-clock-string) (setq key "CLOCK")))
15332 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15333 (progn
15334 (push (cons key string) props)
15335 ;; no need to search further if match is found
15336 (throw 'match t))
15337 (when (or (equal key "CLOCK") (not (assoc key props)))
15338 (push (cons key string) props)))))))
15340 (when (memq which '(all standard))
15341 ;; Get the standard properties, like :PROP: ...
15342 (setq range (org-get-property-block beg end))
15343 (when range
15344 (goto-char (car range))
15345 (while (re-search-forward org-property-re
15346 (cdr range) t)
15347 (setq key (org-match-string-no-properties 2)
15348 value (org-trim (or (org-match-string-no-properties 3) "")))
15349 (unless (member key excluded)
15350 (push (cons key (or value "")) props)))))
15351 (if clocksum
15352 (push (cons "CLOCKSUM"
15353 (org-columns-number-to-string (/ (float clocksum) 60.)
15354 'add_times))
15355 props))
15356 (if clocksumt
15357 (push (cons "CLOCKSUM_T"
15358 (org-columns-number-to-string (/ (float clocksumt) 60.)
15359 'add_times))
15360 props))
15361 (unless (assoc "CATEGORY" props)
15362 (push (cons "CATEGORY" (org-get-category)) props))
15363 (append sum-props (nreverse props)))))))
15365 (defun org-entry-get (pom property &optional inherit literal-nil)
15366 "Get value of PROPERTY for entry or content at point-or-marker POM.
15367 If INHERIT is non-nil and the entry does not have the property,
15368 then also check higher levels of the hierarchy.
15369 If INHERIT is the symbol `selective', use inheritance only if the setting
15370 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15371 If the property is present but empty, the return value is the empty string.
15372 If the property is not present at all, nil is returned.
15374 Return the value as a string.
15376 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15377 do not interpret it as the list atom nil. This is used for inheritance
15378 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15379 (org-with-point-at pom
15380 (if (and inherit (if (eq inherit 'selective)
15381 (org-property-inherit-p property)
15383 (org-entry-get-with-inheritance property literal-nil)
15384 (if (member property org-special-properties)
15385 ;; We need a special property. Use `org-entry-properties'
15386 ;; to retrieve it, but specify the wanted property
15387 (cdr (assoc property (org-entry-properties nil 'special property)))
15388 (org-with-wide-buffer
15389 (let ((range (org-get-property-block)))
15390 (when (and range (not (eq (car range) (cdr range))))
15391 (let* ((props
15392 (list (or (assoc property org-file-properties)
15393 (assoc property org-global-properties)
15394 (assoc property org-global-properties-fixed))))
15395 (ap (lambda (key)
15396 (when (re-search-forward
15397 (org-re-property key) (cdr range) t)
15398 (setq props
15399 (org-update-property-plist
15401 (if (match-end 3)
15402 (org-match-string-no-properties 3) "")
15403 props)))))
15404 val)
15405 (goto-char (car range))
15406 (funcall ap property)
15407 (goto-char (car range))
15408 (while (funcall ap (concat property "+")))
15409 (setq val (cdr (assoc property props)))
15410 (when val (if literal-nil val (org-not-nil val)))))))))))
15412 (defun org-property-or-variable-value (var &optional inherit)
15413 "Check if there is a property fixing the value of VAR.
15414 If yes, return this value. If not, return the current value of the variable."
15415 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15416 (if (and prop (stringp prop) (string-match "\\S-" prop))
15417 (read prop)
15418 (symbol-value var))))
15420 (defun org-entry-delete (pom property)
15421 "Delete the property PROPERTY from entry at point-or-marker POM."
15422 (unless (member property org-special-properties)
15423 (org-with-point-at pom
15424 (let ((range (org-get-property-block)))
15425 (if (and range
15426 (goto-char (car range))
15427 (re-search-forward
15428 (org-re-property property)
15429 (cdr range) t))
15430 (progn
15431 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15432 (org-remove-empty-drawer-at (car range))
15434 nil)))))
15436 ;; Multi-values properties are properties that contain multiple values
15437 ;; These values are assumed to be single words, separated by whitespace.
15438 (defun org-entry-add-to-multivalued-property (pom property value)
15439 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15440 (let* ((old (org-entry-get pom property))
15441 (values (and old (org-split-string old "[ \t]"))))
15442 (setq value (org-entry-protect-space value))
15443 (unless (member value values)
15444 (setq values (append values (list value)))
15445 (org-entry-put pom property
15446 (mapconcat 'identity values " ")))))
15448 (defun org-entry-remove-from-multivalued-property (pom property value)
15449 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15450 (let* ((old (org-entry-get pom property))
15451 (values (and old (org-split-string old "[ \t]"))))
15452 (setq value (org-entry-protect-space value))
15453 (when (member value values)
15454 (setq values (delete value values))
15455 (org-entry-put pom property
15456 (mapconcat 'identity values " ")))))
15458 (defun org-entry-member-in-multivalued-property (pom property value)
15459 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15460 (let* ((old (org-entry-get pom property))
15461 (values (and old (org-split-string old "[ \t]"))))
15462 (setq value (org-entry-protect-space value))
15463 (member value values)))
15465 (defun org-entry-get-multivalued-property (pom property)
15466 "Return a list of values in a multivalued property."
15467 (let* ((value (org-entry-get pom property))
15468 (values (and value (org-split-string value "[ \t]"))))
15469 (mapcar 'org-entry-restore-space values)))
15471 (defun org-entry-put-multivalued-property (pom property &rest values)
15472 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15473 VALUES should be a list of strings. Spaces will be protected."
15474 (org-entry-put pom property
15475 (mapconcat 'org-entry-protect-space values " "))
15476 (let* ((value (org-entry-get pom property))
15477 (values (and value (org-split-string value "[ \t]"))))
15478 (mapcar 'org-entry-restore-space values)))
15480 (defun org-entry-protect-space (s)
15481 "Protect spaces and newline in string S."
15482 (while (string-match " " s)
15483 (setq s (replace-match "%20" t t s)))
15484 (while (string-match "\n" s)
15485 (setq s (replace-match "%0A" t t s)))
15488 (defun org-entry-restore-space (s)
15489 "Restore spaces and newline in string S."
15490 (while (string-match "%20" s)
15491 (setq s (replace-match " " t t s)))
15492 (while (string-match "%0A" s)
15493 (setq s (replace-match "\n" t t s)))
15496 (defvar org-entry-property-inherited-from (make-marker)
15497 "Marker pointing to the entry from where a property was inherited.
15498 Each call to `org-entry-get-with-inheritance' will set this marker to the
15499 location of the entry where the inheritance search matched. If there was
15500 no match, the marker will point nowhere.
15501 Note that also `org-entry-get' calls this function, if the INHERIT flag
15502 is set.")
15504 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15505 "Get PROPERTY of entry or content at point, search higher levels if needed.
15506 The search will stop at the first ancestor which has the property defined.
15507 If the value found is \"nil\", return nil to show that the property
15508 should be considered as undefined (this is the meaning of nil here).
15509 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15510 (move-marker org-entry-property-inherited-from nil)
15511 (let (tmp)
15512 (save-excursion
15513 (save-restriction
15514 (widen)
15515 (catch 'ex
15516 (while t
15517 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15518 (or (ignore-errors (org-back-to-heading t))
15519 (goto-char (point-min)))
15520 (move-marker org-entry-property-inherited-from (point))
15521 (throw 'ex tmp))
15522 (or (ignore-errors (org-up-heading-safe))
15523 (throw 'ex nil))))))
15524 (setq tmp (or tmp
15525 (cdr (assoc property org-file-properties))
15526 (cdr (assoc property org-global-properties))
15527 (cdr (assoc property org-global-properties-fixed))))
15528 (if literal-nil tmp (org-not-nil tmp))))
15530 (defvar org-property-changed-functions nil
15531 "Hook called when the value of a property has changed.
15532 Each hook function should accept two arguments, the name of the property
15533 and the new value.")
15535 (defun org-entry-put (pom property value)
15536 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15537 If the value is `nil', it is converted to the empty string.
15538 If it is not a string, an error is raised."
15539 (cond ((null value) (setq value ""))
15540 ((not (stringp value))
15541 (error "Properties values should be strings.")))
15542 (org-with-point-at pom
15543 (org-back-to-heading t)
15544 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15545 range)
15546 (cond
15547 ((equal property "TODO")
15548 (when (and (string-match "\\S-" value)
15549 (not (member value org-todo-keywords-1)))
15550 (user-error "\"%s\" is not a valid TODO state" value))
15551 (if (or (not value)
15552 (not (string-match "\\S-" value)))
15553 (setq value 'none))
15554 (org-todo value)
15555 (org-set-tags nil 'align))
15556 ((equal property "PRIORITY")
15557 (org-priority (if (and value (string-match "\\S-" value))
15558 (string-to-char value) ?\ ))
15559 (org-set-tags nil 'align))
15560 ((equal property "CLOCKSUM")
15561 (if (not (re-search-forward
15562 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15563 (error "Cannot find a clock log")
15564 (goto-char (- (match-end 1) 2))
15565 (cond
15566 ((eq value 'earlier) (org-timestamp-down))
15567 ((eq value 'later) (org-timestamp-up)))
15568 (org-clock-sum-current-item)))
15569 ((equal property "SCHEDULED")
15570 (if (re-search-forward org-scheduled-time-regexp end t)
15571 (cond
15572 ((eq value 'earlier) (org-timestamp-change -1 'day))
15573 ((eq value 'later) (org-timestamp-change 1 'day))
15574 (t (call-interactively 'org-schedule)))
15575 (call-interactively 'org-schedule)))
15576 ((equal property "DEADLINE")
15577 (if (re-search-forward org-deadline-time-regexp end t)
15578 (cond
15579 ((eq value 'earlier) (org-timestamp-change -1 'day))
15580 ((eq value 'later) (org-timestamp-change 1 'day))
15581 (t (call-interactively 'org-deadline)))
15582 (call-interactively 'org-deadline)))
15583 ((member property org-special-properties)
15584 (error "The %s property can not yet be set with `org-entry-put'"
15585 property))
15586 (t ; a non-special property
15587 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15588 (setq range (org-get-property-block beg end 'force))
15589 (goto-char (car range))
15590 (if (re-search-forward
15591 (org-re-property property) (cdr range) t)
15592 (progn
15593 (delete-region (match-beginning 0) (match-end 0))
15594 (goto-char (match-beginning 0)))
15595 (goto-char (cdr range))
15596 (insert "\n")
15597 (backward-char 1)
15598 (org-indent-line))
15599 (insert ":" property ":")
15600 (and value (insert " " value))
15601 (org-indent-line)))))
15602 (run-hook-with-args 'org-property-changed-functions property value)))
15604 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15605 "Get all property keys in the current buffer.
15606 With INCLUDE-SPECIALS, also list the special properties that reflect things
15607 like tags and TODO state.
15608 With INCLUDE-DEFAULTS, also include properties that has special meaning
15609 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15610 and others.
15611 With INCLUDE-COLUMNS, also include property names given in COLUMN
15612 formats in the current buffer."
15613 (let (rtn range cfmt s p)
15614 (save-excursion
15615 (save-restriction
15616 (widen)
15617 (goto-char (point-min))
15618 (while (re-search-forward org-property-start-re nil t)
15619 (setq range (org-get-property-block))
15620 (goto-char (car range))
15621 (while (re-search-forward org-property-re
15622 (cdr range) t)
15623 (add-to-list 'rtn (org-match-string-no-properties 2)))
15624 (outline-next-heading))))
15626 (when include-specials
15627 (setq rtn (append org-special-properties rtn)))
15629 (when include-defaults
15630 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15631 (add-to-list 'rtn org-effort-property))
15633 (when include-columns
15634 (save-excursion
15635 (save-restriction
15636 (widen)
15637 (goto-char (point-min))
15638 (while (re-search-forward
15639 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15640 nil t)
15641 (setq cfmt (match-string 2) s 0)
15642 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15643 cfmt s)
15644 (setq s (match-end 0)
15645 p (match-string 1 cfmt))
15646 (unless (or (equal p "ITEM")
15647 (member p org-special-properties))
15648 (add-to-list 'rtn (match-string 1 cfmt))))))))
15650 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15652 (defun org-property-values (key)
15653 "Return a list of all values of property KEY in the current buffer."
15654 (save-excursion
15655 (save-restriction
15656 (widen)
15657 (goto-char (point-min))
15658 (let ((re (org-re-property key))
15659 values)
15660 (while (re-search-forward re nil t)
15661 (add-to-list 'values (org-trim (match-string 3))))
15662 (delete "" values)))))
15664 (defun org-insert-property-drawer ()
15665 "Insert a property drawer into the current entry."
15666 (org-back-to-heading t)
15667 (looking-at org-outline-regexp)
15668 (let ((indent (if org-adapt-indentation
15669 (- (match-end 0) (match-beginning 0))
15671 (beg (point))
15672 (re (concat "^[ \t]*" org-keyword-time-regexp))
15673 end hiddenp)
15674 (outline-next-heading)
15675 (setq end (point))
15676 (goto-char beg)
15677 (while (re-search-forward re end t))
15678 (setq hiddenp (outline-invisible-p))
15679 (end-of-line 1)
15680 (and (equal (char-after) ?\n) (forward-char 1))
15681 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15682 (if (member (match-string 1) '("CLOCK:" ":END:"))
15683 ;; just skip this line
15684 (beginning-of-line 2)
15685 ;; Drawer start, find the end
15686 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15687 (beginning-of-line 1)))
15688 (org-skip-over-state-notes)
15689 (skip-chars-backward " \t\n\r")
15690 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15691 (forward-char 1))
15692 (goto-char (point-at-eol))
15693 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15694 (beginning-of-line 0)
15695 (org-indent-to-column indent)
15696 (beginning-of-line 2)
15697 (org-indent-to-column indent)
15698 (beginning-of-line 0)
15699 (if hiddenp
15700 (save-excursion
15701 (org-back-to-heading t)
15702 (hide-entry))
15703 (org-flag-drawer t))))
15705 (defun org-insert-drawer (&optional arg drawer)
15706 "Insert a drawer at point.
15708 Optional argument DRAWER, when non-nil, is a string representing
15709 drawer's name. Otherwise, the user is prompted for a name.
15711 If a region is active, insert the drawer around that region
15712 instead.
15714 Point is left between drawer's boundaries."
15715 (interactive "P")
15716 (let* ((drawer (if arg "PROPERTIES"
15717 (or drawer (read-from-minibuffer "Drawer: ")))))
15718 (cond
15719 ;; With C-u, fall back on `org-insert-property-drawer'
15720 (arg (org-insert-property-drawer))
15722 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15723 (user-error "Invalid drawer name"))
15724 ;; With an active region, insert a drawer at point.
15725 ((not (org-region-active-p))
15726 (progn
15727 (unless (bolp) (insert "\n"))
15728 (insert (format ":%s:\n\n:END:\n" drawer))
15729 (forward-line -2)))
15730 ;; Otherwise, insert the drawer at point
15732 (let ((rbeg (region-beginning))
15733 (rend (copy-marker (region-end))))
15734 (unwind-protect
15735 (progn
15736 (goto-char rbeg)
15737 (beginning-of-line)
15738 (when (save-excursion
15739 (re-search-forward org-outline-regexp-bol rend t))
15740 (user-error "Drawers cannot contain headlines"))
15741 ;; Position point at the beginning of the first
15742 ;; non-blank line in region. Insert drawer's opening
15743 ;; there, then indent it.
15744 (org-skip-whitespace)
15745 (beginning-of-line)
15746 (insert ":" drawer ":\n")
15747 (forward-line -1)
15748 (indent-for-tab-command)
15749 ;; Move point to the beginning of the first blank line
15750 ;; after the last non-blank line in region. Insert
15751 ;; drawer's closing, then indent it.
15752 (goto-char rend)
15753 (skip-chars-backward " \r\t\n")
15754 (insert "\n:END:")
15755 (deactivate-mark t)
15756 (indent-for-tab-command)
15757 (unless (eolp) (insert "\n")))
15758 ;; Clear marker, whatever the outcome of insertion is.
15759 (set-marker rend nil)))))))
15761 (defvar org-property-set-functions-alist nil
15762 "Property set function alist.
15763 Each entry should have the following format:
15765 (PROPERTY . READ-FUNCTION)
15767 The read function will be called with the same argument as
15768 `org-completing-read'.")
15770 (defun org-set-property-function (property)
15771 "Get the function that should be used to set PROPERTY.
15772 This is computed according to `org-property-set-functions-alist'."
15773 (or (cdr (assoc property org-property-set-functions-alist))
15774 'org-completing-read))
15776 (defun org-read-property-value (property)
15777 "Read PROPERTY value from user."
15778 (let* ((completion-ignore-case t)
15779 (allowed (org-property-get-allowed-values nil property 'table))
15780 (cur (org-entry-get nil property))
15781 (prompt (concat property " value"
15782 (if (and cur (string-match "\\S-" cur))
15783 (concat " [" cur "]") "") ": "))
15784 (set-function (org-set-property-function property))
15785 (val (if allowed
15786 (funcall set-function prompt allowed nil
15787 (not (get-text-property 0 'org-unrestricted
15788 (caar allowed))))
15789 (let (org-completion-use-ido org-completion-use-iswitchb)
15790 (funcall set-function prompt
15791 (mapcar 'list (org-property-values property))
15792 nil nil "" nil cur)))))
15793 (if (equal val "")
15795 val)))
15797 (defvar org-last-set-property nil)
15798 (defvar org-last-set-property-value nil)
15799 (defun org-read-property-name ()
15800 "Read a property name."
15801 (let* ((completion-ignore-case t)
15802 (keys (org-buffer-property-keys nil t t))
15803 (default-prop (or (save-excursion
15804 (save-match-data
15805 (beginning-of-line)
15806 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15807 (null (string= (match-string 1) "END"))
15808 (match-string 1))))
15809 org-last-set-property))
15810 (property (org-icompleting-read
15811 (concat "Property"
15812 (if default-prop (concat " [" default-prop "]") "")
15813 ": ")
15814 (mapcar 'list keys)
15815 nil nil nil nil
15816 default-prop)))
15817 (if (member property keys)
15818 property
15819 (or (cdr (assoc (downcase property)
15820 (mapcar (lambda (x) (cons (downcase x) x))
15821 keys)))
15822 property))))
15824 (defun org-set-property-and-value (use-last)
15825 "Allow to set [PROPERTY]: [value] direction from prompt.
15826 When use-default, don't even ask, just use the last
15827 \"[PROPERTY]: [value]\" string from the history."
15828 (interactive "P")
15829 (let* ((completion-ignore-case t)
15830 (pv (or (and use-last org-last-set-property-value)
15831 (org-completing-read
15832 "Enter a \"[Property]: [value]\" pair: "
15833 nil nil nil nil nil
15834 org-last-set-property-value)))
15835 prop val)
15836 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15837 (setq prop (match-string 1 pv)
15838 val (match-string 2 pv))
15839 (org-set-property prop val))))
15841 (defun org-set-property (property value)
15842 "In the current entry, set PROPERTY to VALUE.
15843 When called interactively, this will prompt for a property name, offering
15844 completion on existing and default properties. And then it will prompt
15845 for a value, offering completion either on allowed values (via an inherited
15846 xxx_ALL property) or on existing values in other instances of this property
15847 in the current file."
15848 (interactive (list nil nil))
15849 (let* ((property (or property (org-read-property-name)))
15850 (value (or value (org-read-property-value property)))
15851 (fn (cdr (assoc property org-properties-postprocess-alist))))
15852 (setq org-last-set-property property)
15853 (setq org-last-set-property-value (concat property ": " value))
15854 ;; Possibly postprocess the inserted value:
15855 (when fn (setq value (funcall fn value)))
15856 (unless (equal (org-entry-get nil property) value)
15857 (org-entry-put nil property value))))
15859 (defun org-delete-property (property)
15860 "In the current entry, delete PROPERTY."
15861 (interactive
15862 (let* ((completion-ignore-case t)
15863 (prop (org-icompleting-read "Property: "
15864 (org-entry-properties nil 'standard))))
15865 (list prop)))
15866 (message "Property %s %s" property
15867 (if (org-entry-delete nil property)
15868 "deleted"
15869 "was not present in the entry")))
15871 (defun org-delete-property-globally (property)
15872 "Remove PROPERTY globally, from all entries."
15873 (interactive
15874 (let* ((completion-ignore-case t)
15875 (prop (org-icompleting-read
15876 "Globally remove property: "
15877 (mapcar 'list (org-buffer-property-keys)))))
15878 (list prop)))
15879 (save-excursion
15880 (save-restriction
15881 (widen)
15882 (goto-char (point-min))
15883 (let ((cnt 0))
15884 (while (re-search-forward
15885 (org-re-property property)
15886 nil t)
15887 (setq cnt (1+ cnt))
15888 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15889 (message "Property \"%s\" removed from %d entries" property cnt)))))
15891 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15893 (defun org-compute-property-at-point ()
15894 "Compute the property at point.
15895 This looks for an enclosing column format, extracts the operator and
15896 then applies it to the property in the column format's scope."
15897 (interactive)
15898 (unless (org-at-property-p)
15899 (user-error "Not at a property"))
15900 (let ((prop (org-match-string-no-properties 2)))
15901 (org-columns-get-format-and-top-level)
15902 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15903 (user-error "No operator defined for property %s" prop))
15904 (org-columns-compute prop)))
15906 (defvar org-property-allowed-value-functions nil
15907 "Hook for functions supplying allowed values for a specific property.
15908 The functions must take a single argument, the name of the property, and
15909 return a flat list of allowed values. If \":ETC\" is one of
15910 the values, this means that these values are intended as defaults for
15911 completion, but that other values should be allowed too.
15912 The functions must return nil if they are not responsible for this
15913 property.")
15915 (defun org-property-get-allowed-values (pom property &optional table)
15916 "Get allowed values for the property PROPERTY.
15917 When TABLE is non-nil, return an alist that can directly be used for
15918 completion."
15919 (let (vals)
15920 (cond
15921 ((equal property "TODO")
15922 (setq vals (org-with-point-at pom
15923 (append org-todo-keywords-1 '("")))))
15924 ((equal property "PRIORITY")
15925 (let ((n org-lowest-priority))
15926 (while (>= n org-highest-priority)
15927 (push (char-to-string n) vals)
15928 (setq n (1- n)))))
15929 ((member property org-special-properties))
15930 ((setq vals (run-hook-with-args-until-success
15931 'org-property-allowed-value-functions property)))
15933 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15934 (when (and vals (string-match "\\S-" vals))
15935 (setq vals (car (read-from-string (concat "(" vals ")"))))
15936 (setq vals (mapcar (lambda (x)
15937 (cond ((stringp x) x)
15938 ((numberp x) (number-to-string x))
15939 ((symbolp x) (symbol-name x))
15940 (t "???")))
15941 vals)))))
15942 (when (member ":ETC" vals)
15943 (setq vals (remove ":ETC" vals))
15944 (org-add-props (car vals) '(org-unrestricted t)))
15945 (if table (mapcar 'list vals) vals)))
15947 (defun org-property-previous-allowed-value (&optional previous)
15948 "Switch to the next allowed value for this property."
15949 (interactive)
15950 (org-property-next-allowed-value t))
15952 (defun org-property-next-allowed-value (&optional previous)
15953 "Switch to the next allowed value for this property."
15954 (interactive)
15955 (unless (org-at-property-p)
15956 (user-error "Not at a property"))
15957 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15958 (key (match-string 2))
15959 (value (match-string 3))
15960 (allowed (or (org-property-get-allowed-values (point) key)
15961 (and (member value '("[ ]" "[-]" "[X]"))
15962 '("[ ]" "[X]"))))
15963 (heading (save-match-data (nth 4 (org-heading-components))))
15964 nval)
15965 (unless allowed
15966 (user-error "Allowed values for this property have not been defined"))
15967 (if previous (setq allowed (reverse allowed)))
15968 (if (member value allowed)
15969 (setq nval (car (cdr (member value allowed)))))
15970 (setq nval (or nval (car allowed)))
15971 (if (equal nval value)
15972 (user-error "Only one allowed value for this property"))
15973 (org-at-property-p)
15974 (replace-match (concat " :" key ": " nval) t t)
15975 (org-indent-line)
15976 (beginning-of-line 1)
15977 (skip-chars-forward " \t")
15978 (when (equal prop org-effort-property)
15979 (save-excursion
15980 (org-back-to-heading t)
15981 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15982 (when (string= org-clock-current-task heading)
15983 (setq org-clock-effort nval)
15984 (org-clock-update-mode-line)))
15985 (run-hook-with-args 'org-property-changed-functions key nval)))
15987 (defun org-find-olp (path &optional this-buffer)
15988 "Return a marker pointing to the entry at outline path OLP.
15989 If anything goes wrong, throw an error.
15990 You can wrap this call to catch the error like this:
15992 (condition-case msg
15993 (org-mobile-locate-entry (match-string 4))
15994 (error (nth 1 msg)))
15996 The return value will then be either a string with the error message,
15997 or a marker if everything is OK.
15999 If THIS-BUFFER is set, the outline path does not contain a file,
16000 only headings."
16001 (let* ((file (if this-buffer buffer-file-name (pop path)))
16002 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16003 (level 1)
16004 (lmin 1)
16005 (lmax 1)
16006 limit re end found pos heading cnt flevel)
16007 (unless buffer (error "File not found :%s" file))
16008 (with-current-buffer buffer
16009 (save-excursion
16010 (save-restriction
16011 (widen)
16012 (setq limit (point-max))
16013 (goto-char (point-min))
16014 (while (setq heading (pop path))
16015 (setq re (format org-complex-heading-regexp-format
16016 (regexp-quote heading)))
16017 (setq cnt 0 pos (point))
16018 (while (re-search-forward re end t)
16019 (setq level (- (match-end 1) (match-beginning 1)))
16020 (if (and (>= level lmin) (<= level lmax))
16021 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16022 (when (= cnt 0) (error "Heading not found on level %d: %s"
16023 lmax heading))
16024 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16025 lmax heading))
16026 (goto-char found)
16027 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16028 (setq end (save-excursion (org-end-of-subtree t t))))
16029 (when (org-at-heading-p)
16030 (point-marker)))))))
16032 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16033 "Find node HEADING in BUFFER.
16034 Return a marker to the heading if it was found, or nil if not.
16035 If POS-ONLY is set, return just the position instead of a marker.
16037 The heading text must match exact, but it may have a TODO keyword,
16038 a priority cookie and tags in the standard locations."
16039 (with-current-buffer (or buffer (current-buffer))
16040 (save-excursion
16041 (save-restriction
16042 (widen)
16043 (goto-char (point-min))
16044 (let (case-fold-search)
16045 (if (re-search-forward
16046 (format org-complex-heading-regexp-format
16047 (regexp-quote heading)) nil t)
16048 (if pos-only
16049 (match-beginning 0)
16050 (move-marker (make-marker) (match-beginning 0)))))))))
16052 (defun org-find-exact-heading-in-directory (heading &optional dir)
16053 "Find Org node headline HEADING in all .org files in directory DIR.
16054 When the target headline is found, return a marker to this location."
16055 (let ((files (directory-files (or dir default-directory)
16056 nil "\\`[^.#].*\\.org\\'"))
16057 file visiting m buffer)
16058 (catch 'found
16059 (while (setq file (pop files))
16060 (message "trying %s" file)
16061 (setq visiting (org-find-base-buffer-visiting file))
16062 (setq buffer (or visiting (find-file-noselect file)))
16063 (setq m (org-find-exact-headline-in-buffer
16064 heading buffer))
16065 (when (and (not m) (not visiting)) (kill-buffer buffer))
16066 (and m (throw 'found m))))))
16068 (defun org-find-entry-with-id (ident)
16069 "Locate the entry that contains the ID property with exact value IDENT.
16070 IDENT can be a string, a symbol or a number, this function will search for
16071 the string representation of it.
16072 Return the position where this entry starts, or nil if there is no such entry."
16073 (interactive "sID: ")
16074 (let ((id (cond
16075 ((stringp ident) ident)
16076 ((symbol-name ident) (symbol-name ident))
16077 ((numberp ident) (number-to-string ident))
16078 (t (error "IDENT %s must be a string, symbol or number" ident))))
16079 (case-fold-search nil))
16080 (save-excursion
16081 (save-restriction
16082 (widen)
16083 (goto-char (point-min))
16084 (when (re-search-forward
16085 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16086 nil t)
16087 (org-back-to-heading t)
16088 (point))))))
16090 ;;;; Timestamps
16092 (defvar org-last-changed-timestamp nil)
16093 (defvar org-last-inserted-timestamp nil
16094 "The last time stamp inserted with `org-insert-time-stamp'.")
16095 (defvar org-ts-what) ; dynamically scoped parameter
16097 (defun org-time-stamp (arg &optional inactive)
16098 "Prompt for a date/time and insert a time stamp.
16099 If the user specifies a time like HH:MM or if this command is
16100 called with at least one prefix argument, the time stamp contains
16101 the date and the time. Otherwise, only the date is be included.
16103 All parts of a date not specified by the user is filled in from
16104 the current date/time. So if you just press return without
16105 typing anything, the time stamp will represent the current
16106 date/time.
16108 If there is already a timestamp at the cursor, it will be
16109 modified.
16111 With two universal prefix arguments, insert an active timestamp
16112 with the current time without prompting the user.
16114 When called from lisp, the timestamp is inactive if INACTIVE is
16115 non-nil."
16116 (interactive "P")
16117 (let* ((ts nil)
16118 (default-time
16119 ;; Default time is either today, or, when entering a range,
16120 ;; the range start.
16121 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16122 (save-excursion
16123 (re-search-backward
16124 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16125 (- (point) 20) t)))
16126 (apply 'encode-time (org-parse-time-string (match-string 1)))
16127 (current-time)))
16128 (default-input (and ts (org-get-compact-tod ts)))
16129 (repeater (save-excursion
16130 (save-match-data
16131 (beginning-of-line)
16132 (when (re-search-forward
16133 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16134 (save-excursion (progn (end-of-line) (point))) t)
16135 (match-string 0)))))
16136 org-time-was-given org-end-time-was-given time)
16137 (cond
16138 ((and (org-at-timestamp-p t)
16139 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16140 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16141 (insert "--")
16142 (setq time (let ((this-command this-command))
16143 (org-read-date arg 'totime nil nil
16144 default-time default-input inactive)))
16145 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16146 ((org-at-timestamp-p t)
16147 (setq time (let ((this-command this-command))
16148 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16149 (when (org-at-timestamp-p t) ; just to get the match data
16150 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16151 (replace-match "")
16152 (setq org-last-changed-timestamp
16153 (org-insert-time-stamp
16154 time (or org-time-was-given arg)
16155 inactive nil nil (list org-end-time-was-given)))
16156 (when repeater (goto-char (1- (point))) (insert " " repeater)
16157 (setq org-last-changed-timestamp
16158 (concat (substring org-last-inserted-timestamp 0 -1)
16159 " " repeater ">"))))
16160 (message "Timestamp updated"))
16161 ((equal arg '(16))
16162 (org-insert-time-stamp (current-time) t inactive))
16164 (setq time (let ((this-command this-command))
16165 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16166 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16167 nil nil (list org-end-time-was-given))))))
16169 ;; FIXME: can we use this for something else, like computing time differences?
16170 (defun org-get-compact-tod (s)
16171 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16172 (let* ((t1 (match-string 1 s))
16173 (h1 (string-to-number (match-string 2 s)))
16174 (m1 (string-to-number (match-string 3 s)))
16175 (t2 (and (match-end 4) (match-string 5 s)))
16176 (h2 (and t2 (string-to-number (match-string 6 s))))
16177 (m2 (and t2 (string-to-number (match-string 7 s))))
16178 dh dm)
16179 (if (not t2)
16181 (setq dh (- h2 h1) dm (- m2 m1))
16182 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16183 (concat t1 "+" (number-to-string dh)
16184 (and (/= 0 dm) (format ":%02d" dm)))))))
16186 (defun org-time-stamp-inactive (&optional arg)
16187 "Insert an inactive time stamp.
16188 An inactive time stamp is enclosed in square brackets instead of angle
16189 brackets. It is inactive in the sense that it does not trigger agenda entries,
16190 does not link to the calendar and cannot be changed with the S-cursor keys.
16191 So these are more for recording a certain time/date."
16192 (interactive "P")
16193 (org-time-stamp arg 'inactive))
16195 (defvar org-date-ovl (make-overlay 1 1))
16196 (overlay-put org-date-ovl 'face 'org-date-selected)
16197 (org-detach-overlay org-date-ovl)
16199 (defvar org-ans1) ; dynamically scoped parameter
16200 (defvar org-ans2) ; dynamically scoped parameter
16202 (defvar org-plain-time-of-day-regexp) ; defined below
16204 (defvar org-overriding-default-time nil) ; dynamically scoped
16205 (defvar org-read-date-overlay nil)
16206 (defvar org-dcst nil) ; dynamically scoped
16207 (defvar org-read-date-history nil)
16208 (defvar org-read-date-final-answer nil)
16209 (defvar org-read-date-analyze-futurep nil)
16210 (defvar org-read-date-analyze-forced-year nil)
16211 (defvar org-read-date-inactive)
16213 (defvar org-read-date-minibuffer-local-map
16214 (let* ((org-replace-disputed-keys nil)
16215 (map (make-sparse-keymap)))
16216 (set-keymap-parent map minibuffer-local-map)
16217 (org-defkey map (kbd ".")
16218 (lambda () (interactive)
16219 ;; Are we at the beginning of the prompt?
16220 (if (looking-back "^[^:]+: ")
16221 (org-eval-in-calendar '(calendar-goto-today))
16222 (insert "."))))
16223 (org-defkey map (kbd "C-.")
16224 (lambda () (interactive)
16225 (org-eval-in-calendar '(calendar-goto-today))))
16226 (org-defkey map [(meta shift left)]
16227 (lambda () (interactive)
16228 (org-eval-in-calendar '(calendar-backward-month 1))))
16229 (org-defkey map [(meta shift right)]
16230 (lambda () (interactive)
16231 (org-eval-in-calendar '(calendar-forward-month 1))))
16232 (org-defkey map [(meta shift up)]
16233 (lambda () (interactive)
16234 (org-eval-in-calendar '(calendar-backward-year 1))))
16235 (org-defkey map [(meta shift down)]
16236 (lambda () (interactive)
16237 (org-eval-in-calendar '(calendar-forward-year 1))))
16238 (org-defkey map [?\e (shift left)]
16239 (lambda () (interactive)
16240 (org-eval-in-calendar '(calendar-backward-month 1))))
16241 (org-defkey map [?\e (shift right)]
16242 (lambda () (interactive)
16243 (org-eval-in-calendar '(calendar-forward-month 1))))
16244 (org-defkey map [?\e (shift up)]
16245 (lambda () (interactive)
16246 (org-eval-in-calendar '(calendar-backward-year 1))))
16247 (org-defkey map [?\e (shift down)]
16248 (lambda () (interactive)
16249 (org-eval-in-calendar '(calendar-forward-year 1))))
16250 (org-defkey map [(shift up)]
16251 (lambda () (interactive)
16252 (org-eval-in-calendar '(calendar-backward-week 1))))
16253 (org-defkey map [(shift down)]
16254 (lambda () (interactive)
16255 (org-eval-in-calendar '(calendar-forward-week 1))))
16256 (org-defkey map [(shift left)]
16257 (lambda () (interactive)
16258 (org-eval-in-calendar '(calendar-backward-day 1))))
16259 (org-defkey map [(shift right)]
16260 (lambda () (interactive)
16261 (org-eval-in-calendar '(calendar-forward-day 1))))
16262 (org-defkey map "!"
16263 (lambda () (interactive)
16264 (org-eval-in-calendar '(diary-view-entries))
16265 (message "")))
16266 (org-defkey map ">"
16267 (lambda () (interactive)
16268 (org-eval-in-calendar '(scroll-calendar-left 1))))
16269 (org-defkey map "<"
16270 (lambda () (interactive)
16271 (org-eval-in-calendar '(scroll-calendar-right 1))))
16272 (org-defkey map "\C-v"
16273 (lambda () (interactive)
16274 (org-eval-in-calendar
16275 '(calendar-scroll-left-three-months 1))))
16276 (org-defkey map "\M-v"
16277 (lambda () (interactive)
16278 (org-eval-in-calendar
16279 '(calendar-scroll-right-three-months 1))))
16280 map)
16281 "Keymap for minibuffer commands when using `org-read-date'.")
16283 (defvar org-def)
16284 (defvar org-defdecode)
16285 (defvar org-with-time)
16287 (defun org-read-date (&optional org-with-time to-time from-string prompt
16288 default-time default-input inactive)
16289 "Read a date, possibly a time, and make things smooth for the user.
16290 The prompt will suggest to enter an ISO date, but you can also enter anything
16291 which will at least partially be understood by `parse-time-string'.
16292 Unrecognized parts of the date will default to the current day, month, year,
16293 hour and minute. If this command is called to replace a timestamp at point,
16294 or to enter the second timestamp of a range, the default time is taken
16295 from the existing stamp. Furthermore, the command prefers the future,
16296 so if you are giving a date where the year is not given, and the day-month
16297 combination is already past in the current year, it will assume you
16298 mean next year. For details, see the manual. A few examples:
16300 3-2-5 --> 2003-02-05
16301 feb 15 --> currentyear-02-15
16302 2/15 --> currentyear-02-15
16303 sep 12 9 --> 2009-09-12
16304 12:45 --> today 12:45
16305 22 sept 0:34 --> currentyear-09-22 0:34
16306 12 --> currentyear-currentmonth-12
16307 Fri --> nearest Friday after today
16308 -Tue --> last Tuesday
16309 etc.
16311 Furthermore you can specify a relative date by giving, as the *first* thing
16312 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16313 change in days weeks, months, years.
16314 With a single plus or minus, the date is relative to today. With a double
16315 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16316 +4d --> four days from today
16317 +4 --> same as above
16318 +2w --> two weeks from today
16319 ++5 --> five days from default date
16321 The function understands only English month and weekday abbreviations.
16323 While prompting, a calendar is popped up - you can also select the
16324 date with the mouse (button 1). The calendar shows a period of three
16325 months. To scroll it to other months, use the keys `>' and `<'.
16326 If you don't like the calendar, turn it off with
16327 \(setq org-read-date-popup-calendar nil)
16329 With optional argument TO-TIME, the date will immediately be converted
16330 to an internal time.
16331 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16332 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16333 still enter a time, and this function will inform the calling routine
16334 about this change. The calling routine may then choose to change the
16335 format used to insert the time stamp into the buffer to include the time.
16336 With optional argument FROM-STRING, read from this string instead from
16337 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16338 the time/date that is used for everything that is not specified by the
16339 user."
16340 (require 'parse-time)
16341 (let* ((org-time-stamp-rounding-minutes
16342 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16343 (org-dcst org-display-custom-times)
16344 (ct (org-current-time))
16345 (org-def (or org-overriding-default-time default-time ct))
16346 (org-defdecode (decode-time org-def))
16347 (dummy (progn
16348 (when (< (nth 2 org-defdecode) org-extend-today-until)
16349 (setcar (nthcdr 2 org-defdecode) -1)
16350 (setcar (nthcdr 1 org-defdecode) 59)
16351 (setq org-def (apply 'encode-time org-defdecode)
16352 org-defdecode (decode-time org-def)))))
16353 (mouse-autoselect-window nil) ; Don't let the mouse jump
16354 (calendar-frame-setup nil)
16355 (calendar-setup nil)
16356 (calendar-move-hook nil)
16357 (calendar-view-diary-initially-flag nil)
16358 (calendar-view-holidays-initially-flag nil)
16359 (timestr (format-time-string
16360 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16361 (prompt (concat (if prompt (concat prompt " ") "")
16362 (format "Date+time [%s]: " timestr)))
16363 ans (org-ans0 "") org-ans1 org-ans2 final)
16365 (cond
16366 (from-string (setq ans from-string))
16367 (org-read-date-popup-calendar
16368 (save-excursion
16369 (save-window-excursion
16370 (calendar)
16371 (org-eval-in-calendar '(setq cursor-type nil) t)
16372 (unwind-protect
16373 (progn
16374 (calendar-forward-day (- (time-to-days org-def)
16375 (calendar-absolute-from-gregorian
16376 (calendar-current-date))))
16377 (org-eval-in-calendar nil t)
16378 (let* ((old-map (current-local-map))
16379 (map (copy-keymap calendar-mode-map))
16380 (minibuffer-local-map
16381 (copy-keymap org-read-date-minibuffer-local-map)))
16382 (org-defkey map (kbd "RET") 'org-calendar-select)
16383 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16384 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16385 (unwind-protect
16386 (progn
16387 (use-local-map map)
16388 (setq org-read-date-inactive inactive)
16389 (add-hook 'post-command-hook 'org-read-date-display)
16390 (setq org-ans0 (read-string prompt default-input
16391 'org-read-date-history nil))
16392 ;; org-ans0: from prompt
16393 ;; org-ans1: from mouse click
16394 ;; org-ans2: from calendar motion
16395 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16396 (remove-hook 'post-command-hook 'org-read-date-display)
16397 (use-local-map old-map)
16398 (when org-read-date-overlay
16399 (delete-overlay org-read-date-overlay)
16400 (setq org-read-date-overlay nil)))))
16401 (bury-buffer "*Calendar*")))))
16403 (t ; Naked prompt only
16404 (unwind-protect
16405 (setq ans (read-string prompt default-input
16406 'org-read-date-history timestr))
16407 (when org-read-date-overlay
16408 (delete-overlay org-read-date-overlay)
16409 (setq org-read-date-overlay nil)))))
16411 (setq final (org-read-date-analyze ans org-def org-defdecode))
16413 (when org-read-date-analyze-forced-year
16414 (message "Year was forced into %s"
16415 (if org-read-date-force-compatible-dates
16416 "compatible range (1970-2037)"
16417 "range representable on this machine"))
16418 (ding))
16420 ;; One round trip to get rid of 34th of August and stuff like that....
16421 (setq final (decode-time (apply 'encode-time final)))
16423 (setq org-read-date-final-answer ans)
16425 (if to-time
16426 (apply 'encode-time final)
16427 (if (and (boundp 'org-time-was-given) org-time-was-given)
16428 (format "%04d-%02d-%02d %02d:%02d"
16429 (nth 5 final) (nth 4 final) (nth 3 final)
16430 (nth 2 final) (nth 1 final))
16431 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16433 (defun org-read-date-display ()
16434 "Display the current date prompt interpretation in the minibuffer."
16435 (when org-read-date-display-live
16436 (when org-read-date-overlay
16437 (delete-overlay org-read-date-overlay))
16438 (when (minibufferp (current-buffer))
16439 (save-excursion
16440 (end-of-line 1)
16441 (while (not (equal (buffer-substring
16442 (max (point-min) (- (point) 4)) (point))
16443 " "))
16444 (insert " ")))
16445 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16446 " " (or org-ans1 org-ans2)))
16447 (org-end-time-was-given nil)
16448 (f (org-read-date-analyze ans org-def org-defdecode))
16449 (fmts (if org-dcst
16450 org-time-stamp-custom-formats
16451 org-time-stamp-formats))
16452 (fmt (if (or org-with-time
16453 (and (boundp 'org-time-was-given) org-time-was-given))
16454 (cdr fmts)
16455 (car fmts)))
16456 (txt (format-time-string fmt (apply 'encode-time f)))
16457 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16458 (txt (concat "=> " txt)))
16459 (when (and org-end-time-was-given
16460 (string-match org-plain-time-of-day-regexp txt))
16461 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16462 org-end-time-was-given
16463 (substring txt (match-end 0)))))
16464 (when org-read-date-analyze-futurep
16465 (setq txt (concat txt " (=>F)")))
16466 (setq org-read-date-overlay
16467 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16468 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16470 (defun org-read-date-analyze (ans org-def org-defdecode)
16471 "Analyze the combined answer of the date prompt."
16472 ;; FIXME: cleanup and comment
16473 (let ((nowdecode (decode-time (current-time)))
16474 delta deltan deltaw deltadef year month day
16475 hour minute second wday pm h2 m2 tl wday1
16476 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16477 (setq org-read-date-analyze-futurep nil
16478 org-read-date-analyze-forced-year nil)
16479 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16480 (setq ans "+0"))
16482 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16483 (setq ans (replace-match "" t t ans)
16484 deltan (car delta)
16485 deltaw (nth 1 delta)
16486 deltadef (nth 2 delta)))
16488 ;; Check if there is an iso week date in there. If yes, store the
16489 ;; info and postpone interpreting it until the rest of the parsing
16490 ;; is done.
16491 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16492 (setq iso-year (if (match-end 1)
16493 (org-small-year-to-year
16494 (string-to-number (match-string 1 ans))))
16495 iso-weekday (if (match-end 3)
16496 (string-to-number (match-string 3 ans)))
16497 iso-week (string-to-number (match-string 2 ans)))
16498 (setq ans (replace-match "" t t ans)))
16500 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16501 (when (string-match
16502 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16503 (setq year (if (match-end 2)
16504 (string-to-number (match-string 2 ans))
16505 (progn (setq kill-year t)
16506 (string-to-number (format-time-string "%Y"))))
16507 month (string-to-number (match-string 3 ans))
16508 day (string-to-number (match-string 4 ans)))
16509 (if (< year 100) (setq year (+ 2000 year)))
16510 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16511 t nil ans)))
16513 ;; Help matching dotted european dates
16514 (when (string-match
16515 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16516 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16517 (setq kill-year t)
16518 (string-to-number (format-time-string "%Y")))
16519 day (string-to-number (match-string 1 ans))
16520 month (string-to-number (match-string 2 ans))
16521 ans (replace-match (format "%04d-%02d-%02d" year month day)
16522 t nil ans)))
16524 ;; Help matching american dates, like 5/30 or 5/30/7
16525 (when (string-match
16526 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16527 (setq year (if (match-end 4)
16528 (string-to-number (match-string 4 ans))
16529 (progn (setq kill-year t)
16530 (string-to-number (format-time-string "%Y"))))
16531 month (string-to-number (match-string 1 ans))
16532 day (string-to-number (match-string 2 ans)))
16533 (if (< year 100) (setq year (+ 2000 year)))
16534 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16535 t nil ans)))
16536 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16537 ;; If there is a time with am/pm, and *no* time without it, we convert
16538 ;; so that matching will be successful.
16539 (loop for i from 1 to 2 do ; twice, for end time as well
16540 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16541 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16542 (setq hour (string-to-number (match-string 1 ans))
16543 minute (if (match-end 3)
16544 (string-to-number (match-string 3 ans))
16546 pm (equal ?p
16547 (string-to-char (downcase (match-string 4 ans)))))
16548 (if (and (= hour 12) (not pm))
16549 (setq hour 0)
16550 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16551 (setq ans (replace-match (format "%02d:%02d" hour minute)
16552 t t ans))))
16554 ;; Check if a time range is given as a duration
16555 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16556 (setq hour (string-to-number (match-string 1 ans))
16557 h2 (+ hour (string-to-number (match-string 3 ans)))
16558 minute (string-to-number (match-string 2 ans))
16559 m2 (+ minute (if (match-end 5) (string-to-number
16560 (match-string 5 ans))0)))
16561 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16562 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16563 t t ans)))
16565 ;; Check if there is a time range
16566 (when (boundp 'org-end-time-was-given)
16567 (setq org-time-was-given nil)
16568 (when (and (string-match org-plain-time-of-day-regexp ans)
16569 (match-end 8))
16570 (setq org-end-time-was-given (match-string 8 ans))
16571 (setq ans (concat (substring ans 0 (match-beginning 7))
16572 (substring ans (match-end 7))))))
16574 (setq tl (parse-time-string ans)
16575 day (or (nth 3 tl) (nth 3 org-defdecode))
16576 month (or (nth 4 tl)
16577 (if (and org-read-date-prefer-future
16578 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16579 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16580 (nth 4 org-defdecode)))
16581 year (or (and (not kill-year) (nth 5 tl))
16582 (if (and org-read-date-prefer-future
16583 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16584 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16585 (nth 5 org-defdecode)))
16586 hour (or (nth 2 tl) (nth 2 org-defdecode))
16587 minute (or (nth 1 tl) (nth 1 org-defdecode))
16588 second (or (nth 0 tl) 0)
16589 wday (nth 6 tl))
16591 (when (and (eq org-read-date-prefer-future 'time)
16592 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16593 (equal day (nth 3 nowdecode))
16594 (equal month (nth 4 nowdecode))
16595 (equal year (nth 5 nowdecode))
16596 (nth 2 tl)
16597 (or (< (nth 2 tl) (nth 2 nowdecode))
16598 (and (= (nth 2 tl) (nth 2 nowdecode))
16599 (nth 1 tl)
16600 (< (nth 1 tl) (nth 1 nowdecode)))))
16601 (setq day (1+ day)
16602 futurep t))
16604 ;; Special date definitions below
16605 (cond
16606 (iso-week
16607 ;; There was an iso week
16608 (require 'cal-iso)
16609 (setq futurep nil)
16610 (setq year (or iso-year year)
16611 day (or iso-weekday wday 1)
16612 wday nil ; to make sure that the trigger below does not match
16613 iso-date (calendar-gregorian-from-absolute
16614 (calendar-absolute-from-iso
16615 (list iso-week day year))))
16616 ; FIXME: Should we also push ISO weeks into the future?
16617 ; (when (and org-read-date-prefer-future
16618 ; (not iso-year)
16619 ; (< (calendar-absolute-from-gregorian iso-date)
16620 ; (time-to-days (current-time))))
16621 ; (setq year (1+ year)
16622 ; iso-date (calendar-gregorian-from-absolute
16623 ; (calendar-absolute-from-iso
16624 ; (list iso-week day year)))))
16625 (setq month (car iso-date)
16626 year (nth 2 iso-date)
16627 day (nth 1 iso-date)))
16628 (deltan
16629 (setq futurep nil)
16630 (unless deltadef
16631 (let ((now (decode-time (current-time))))
16632 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16633 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16634 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16635 ((equal deltaw "m") (setq month (+ month deltan)))
16636 ((equal deltaw "y") (setq year (+ year deltan)))))
16637 ((and wday (not (nth 3 tl)))
16638 ;; Weekday was given, but no day, so pick that day in the week
16639 ;; on or after the derived date.
16640 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16641 (unless (equal wday wday1)
16642 (setq day (+ day (% (- wday wday1 -7) 7))))))
16643 (if (and (boundp 'org-time-was-given)
16644 (nth 2 tl))
16645 (setq org-time-was-given t))
16646 (if (< year 100) (setq year (+ 2000 year)))
16647 ;; Check of the date is representable
16648 (if org-read-date-force-compatible-dates
16649 (progn
16650 (if (< year 1970)
16651 (setq year 1970 org-read-date-analyze-forced-year t))
16652 (if (> year 2037)
16653 (setq year 2037 org-read-date-analyze-forced-year t)))
16654 (condition-case nil
16655 (ignore (encode-time second minute hour day month year))
16656 (error
16657 (setq year (nth 5 org-defdecode))
16658 (setq org-read-date-analyze-forced-year t))))
16659 (setq org-read-date-analyze-futurep futurep)
16660 (list second minute hour day month year)))
16662 (defvar parse-time-weekdays)
16663 (defun org-read-date-get-relative (s today default)
16664 "Check string S for special relative date string.
16665 TODAY and DEFAULT are internal times, for today and for a default.
16666 Return shift list (N what def-flag)
16667 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16668 N is the number of WHATs to shift.
16669 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16670 the DEFAULT date rather than TODAY."
16671 (require 'parse-time)
16672 (when (and
16673 (string-match
16674 (concat
16675 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16676 "\\([0-9]+\\)?"
16677 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16678 "\\([ \t]\\|$\\)") s)
16679 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16680 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16681 (string-to-char (substring (match-string 1 s) -1))
16682 ?+))
16683 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16684 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16685 (what (if (match-end 3) (match-string 3 s) "d"))
16686 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16687 (date (if rel default today))
16688 (wday (nth 6 (decode-time date)))
16689 delta)
16690 (if wday1
16691 (progn
16692 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16693 (if (= delta 0) (setq delta 7))
16694 (if (= dir ?-)
16695 (progn
16696 (setq delta (- delta 7))
16697 (if (= delta 0) (setq delta -7))))
16698 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16699 (list delta "d" rel))
16700 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16702 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16703 "Turn a user-specified date into the internal representation.
16704 The internal representation needed by the calendar is (month day year).
16705 This is a wrapper to handle the brain-dead convention in calendar that
16706 user function argument order change dependent on argument order."
16707 (if (boundp 'calendar-date-style)
16708 (cond
16709 ((eq calendar-date-style 'american)
16710 (list arg1 arg2 arg3))
16711 ((eq calendar-date-style 'european)
16712 (list arg2 arg1 arg3))
16713 ((eq calendar-date-style 'iso)
16714 (list arg2 arg3 arg1)))
16715 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16716 (if (org-bound-and-true-p european-calendar-style)
16717 (list arg2 arg1 arg3)
16718 (list arg1 arg2 arg3)))))
16720 (defun org-eval-in-calendar (form &optional keepdate)
16721 "Eval FORM in the calendar window and return to current window.
16722 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16723 otherwise stick to the current value of `org-ans2'."
16724 (let ((sf (selected-frame))
16725 (sw (selected-window)))
16726 (select-window (get-buffer-window "*Calendar*" t))
16727 (eval form)
16728 (when (and (not keepdate) (calendar-cursor-to-date))
16729 (let* ((date (calendar-cursor-to-date))
16730 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16731 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16732 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16733 (select-window sw)
16734 (org-select-frame-set-input-focus sf)))
16736 (defun org-calendar-select ()
16737 "Return to `org-read-date' with the date currently selected.
16738 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16739 (interactive)
16740 (when (calendar-cursor-to-date)
16741 (let* ((date (calendar-cursor-to-date))
16742 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16743 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16744 (if (active-minibuffer-window) (exit-minibuffer))))
16746 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16747 "Insert a date stamp for the date given by the internal TIME.
16748 WITH-HM means use the stamp format that includes the time of the day.
16749 INACTIVE means use square brackets instead of angular ones, so that the
16750 stamp will not contribute to the agenda.
16751 PRE and POST are optional strings to be inserted before and after the
16752 stamp.
16753 The command returns the inserted time stamp."
16754 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16755 stamp)
16756 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16757 (insert-before-markers (or pre ""))
16758 (when (listp extra)
16759 (setq extra (car extra))
16760 (if (and (stringp extra)
16761 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16762 (setq extra (format "-%02d:%02d"
16763 (string-to-number (match-string 1 extra))
16764 (string-to-number (match-string 2 extra))))
16765 (setq extra nil)))
16766 (when extra
16767 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16768 (insert-before-markers (setq stamp (format-time-string fmt time)))
16769 (insert-before-markers (or post ""))
16770 (setq org-last-inserted-timestamp stamp)))
16772 (defun org-toggle-time-stamp-overlays ()
16773 "Toggle the use of custom time stamp formats."
16774 (interactive)
16775 (setq org-display-custom-times (not org-display-custom-times))
16776 (unless org-display-custom-times
16777 (let ((p (point-min)) (bmp (buffer-modified-p)))
16778 (while (setq p (next-single-property-change p 'display))
16779 (if (and (get-text-property p 'display)
16780 (eq (get-text-property p 'face) 'org-date))
16781 (remove-text-properties
16782 p (setq p (next-single-property-change p 'display))
16783 '(display t))))
16784 (set-buffer-modified-p bmp)))
16785 (if (featurep 'xemacs)
16786 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16787 (org-restart-font-lock)
16788 (setq org-table-may-need-update t)
16789 (if org-display-custom-times
16790 (message "Time stamps are overlaid with custom format")
16791 (message "Time stamp overlays removed")))
16793 (defun org-display-custom-time (beg end)
16794 "Overlay modified time stamp format over timestamp between BEG and END."
16795 (let* ((ts (buffer-substring beg end))
16796 t1 w1 with-hm tf time str w2 (off 0))
16797 (save-match-data
16798 (setq t1 (org-parse-time-string ts t))
16799 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16800 (setq off (- (match-end 0) (match-beginning 0)))))
16801 (setq end (- end off))
16802 (setq w1 (- end beg)
16803 with-hm (and (nth 1 t1) (nth 2 t1))
16804 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16805 time (org-fix-decoded-time t1)
16806 str (org-add-props
16807 (format-time-string
16808 (substring tf 1 -1) (apply 'encode-time time))
16809 nil 'mouse-face 'highlight)
16810 w2 (length str))
16811 (if (not (= w2 w1))
16812 (add-text-properties (1+ beg) (+ 2 beg)
16813 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16814 (if (featurep 'xemacs)
16815 (progn
16816 (put-text-property beg end 'invisible t)
16817 (put-text-property beg end 'end-glyph (make-glyph str)))
16818 (put-text-property beg end 'display str))))
16820 (defun org-translate-time (string)
16821 "Translate all timestamps in STRING to custom format.
16822 But do this only if the variable `org-display-custom-times' is set."
16823 (when org-display-custom-times
16824 (save-match-data
16825 (let* ((start 0)
16826 (re org-ts-regexp-both)
16827 t1 with-hm inactive tf time str beg end)
16828 (while (setq start (string-match re string start))
16829 (setq beg (match-beginning 0)
16830 end (match-end 0)
16831 t1 (save-match-data
16832 (org-parse-time-string (substring string beg end) t))
16833 with-hm (and (nth 1 t1) (nth 2 t1))
16834 inactive (equal (substring string beg (1+ beg)) "[")
16835 tf (funcall (if with-hm 'cdr 'car)
16836 org-time-stamp-custom-formats)
16837 time (org-fix-decoded-time t1)
16838 str (format-time-string
16839 (concat
16840 (if inactive "[" "<") (substring tf 1 -1)
16841 (if inactive "]" ">"))
16842 (apply 'encode-time time))
16843 string (replace-match str t t string)
16844 start (+ start (length str)))))))
16845 string)
16847 (defun org-fix-decoded-time (time)
16848 "Set 0 instead of nil for the first 6 elements of time.
16849 Don't touch the rest."
16850 (let ((n 0))
16851 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16853 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16855 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16856 "Difference between TIMESTAMP-STRING and now in days.
16857 If SECONDS is non-nil, return the difference in seconds."
16858 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16859 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16860 (funcall fdiff (current-time)))))
16862 (defun org-deadline-close (timestamp-string &optional ndays)
16863 "Is the time in TIMESTAMP-STRING close to the current date?"
16864 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16865 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16866 (not (org-entry-is-done-p))))
16868 (defun org-get-wdays (ts &optional delay zero-delay)
16869 "Get the deadline lead time appropriate for timestring TS.
16870 When DELAY is non-nil, get the delay time for scheduled items
16871 instead of the deadline lead time. When ZERO-DELAY is non-nil
16872 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16873 don't try to find the delay cookie in the scheduled timestamp."
16874 (let ((tv (if delay org-scheduled-delay-days
16875 org-deadline-warning-days)))
16876 (cond
16877 ((or (and delay (< tv 0))
16878 (and delay zero-delay (<= tv 0))
16879 (and (not delay) (<= tv 0)))
16880 ;; Enforce this value no matter what
16881 (- tv))
16882 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16883 ;; lead time is specified.
16884 (floor (* (string-to-number (match-string 1 ts))
16885 (cdr (assoc (match-string 2 ts)
16886 '(("d" . 1) ("w" . 7)
16887 ("m" . 30.4) ("y" . 365.25)
16888 ("h" . 0.041667)))))))
16889 ;; go for the default.
16890 (t tv))))
16892 (defun org-calendar-select-mouse (ev)
16893 "Return to `org-read-date' with the date currently selected.
16894 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16895 (interactive "e")
16896 (mouse-set-point ev)
16897 (when (calendar-cursor-to-date)
16898 (let* ((date (calendar-cursor-to-date))
16899 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16900 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16901 (if (active-minibuffer-window) (exit-minibuffer))))
16903 (defun org-check-deadlines (ndays)
16904 "Check if there are any deadlines due or past due.
16905 A deadline is considered due if it happens within `org-deadline-warning-days'
16906 days from today's date. If the deadline appears in an entry marked DONE,
16907 it is not shown. The prefix arg NDAYS can be used to test that many
16908 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16909 (interactive "P")
16910 (let* ((org-warn-days
16911 (cond
16912 ((equal ndays '(4)) 100000)
16913 (ndays (prefix-numeric-value ndays))
16914 (t (abs org-deadline-warning-days))))
16915 (case-fold-search nil)
16916 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16917 (callback
16918 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16920 (message "%d deadlines past-due or due within %d days"
16921 (org-occur regexp nil callback)
16922 org-warn-days)))
16924 (defsubst org-re-timestamp (type)
16925 "Return a regexp for timestamp TYPE.
16926 Allowed values for TYPE are:
16928 all: all timestamps
16929 active: only active timestamps (<...>)
16930 inactive: only inactive timestamps ([...])
16931 scheduled: only scheduled timestamps
16932 deadline: only deadline timestamps
16933 closed: only closed time-stamps
16935 When TYPE is nil, fall back on returning a regexp that matches
16936 both scheduled and deadline timestamps."
16937 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16938 ((eq type 'active) org-ts-regexp)
16939 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16940 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16941 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16942 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16943 ((eq type 'scheduled-or-deadline)
16944 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16946 (defun org-check-before-date (date)
16947 "Check if there are deadlines or scheduled entries before DATE."
16948 (interactive (list (org-read-date)))
16949 (let ((case-fold-search nil)
16950 (regexp (org-re-timestamp org-ts-type))
16951 (callback
16952 (lambda () (time-less-p
16953 (org-time-string-to-time (match-string 1))
16954 (org-time-string-to-time date)))))
16955 (message "%d entries before %s"
16956 (org-occur regexp nil callback) date)))
16958 (defun org-check-after-date (date)
16959 "Check if there are deadlines or scheduled entries after DATE."
16960 (interactive (list (org-read-date)))
16961 (let ((case-fold-search nil)
16962 (regexp (org-re-timestamp org-ts-type))
16963 (callback
16964 (lambda () (not
16965 (time-less-p
16966 (org-time-string-to-time (match-string 1))
16967 (org-time-string-to-time date))))))
16968 (message "%d entries after %s"
16969 (org-occur regexp nil callback) date)))
16971 (defun org-check-dates-range (start-date end-date)
16972 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16973 (interactive (list (org-read-date nil nil nil "Range starts")
16974 (org-read-date nil nil nil "Range end")))
16975 (let ((case-fold-search nil)
16976 (regexp (org-re-timestamp org-ts-type))
16977 (callback
16978 (lambda ()
16979 (let ((match (match-string 1)))
16980 (and
16981 (not (time-less-p
16982 (org-time-string-to-time match)
16983 (org-time-string-to-time start-date)))
16984 (time-less-p
16985 (org-time-string-to-time match)
16986 (org-time-string-to-time end-date)))))))
16987 (message "%d entries between %s and %s"
16988 (org-occur regexp nil callback) start-date end-date)))
16990 (defun org-evaluate-time-range (&optional to-buffer)
16991 "Evaluate a time range by computing the difference between start and end.
16992 Normally the result is just printed in the echo area, but with prefix arg
16993 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16994 If the time range is actually in a table, the result is inserted into the
16995 next column.
16996 For time difference computation, a year is assumed to be exactly 365
16997 days in order to avoid rounding problems."
16998 (interactive "P")
17000 (org-clock-update-time-maybe)
17001 (save-excursion
17002 (unless (org-at-date-range-p t)
17003 (goto-char (point-at-bol))
17004 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17005 (if (not (org-at-date-range-p t))
17006 (user-error "Not at a time-stamp range, and none found in current line")))
17007 (let* ((ts1 (match-string 1))
17008 (ts2 (match-string 2))
17009 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17010 (match-end (match-end 0))
17011 (time1 (org-time-string-to-time ts1))
17012 (time2 (org-time-string-to-time ts2))
17013 (t1 (org-float-time time1))
17014 (t2 (org-float-time time2))
17015 (diff (abs (- t2 t1)))
17016 (negative (< (- t2 t1) 0))
17017 ;; (ys (floor (* 365 24 60 60)))
17018 (ds (* 24 60 60))
17019 (hs (* 60 60))
17020 (fy "%dy %dd %02d:%02d")
17021 (fy1 "%dy %dd")
17022 (fd "%dd %02d:%02d")
17023 (fd1 "%dd")
17024 (fh "%02d:%02d")
17025 y d h m align)
17026 (if havetime
17027 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17029 d (floor (/ diff ds)) diff (mod diff ds)
17030 h (floor (/ diff hs)) diff (mod diff hs)
17031 m (floor (/ diff 60)))
17032 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17034 d (floor (+ (/ diff ds) 0.5))
17035 h 0 m 0))
17036 (if (not to-buffer)
17037 (message "%s" (org-make-tdiff-string y d h m))
17038 (if (org-at-table-p)
17039 (progn
17040 (goto-char match-end)
17041 (setq align t)
17042 (and (looking-at " *|") (goto-char (match-end 0))))
17043 (goto-char match-end))
17044 (if (looking-at
17045 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17046 (replace-match ""))
17047 (if negative (insert " -"))
17048 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17049 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17050 (insert " " (format fh h m))))
17051 (if align (org-table-align))
17052 (message "Time difference inserted")))))
17054 (defun org-make-tdiff-string (y d h m)
17055 (let ((fmt "")
17056 (l nil))
17057 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17058 l (push y l)))
17059 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17060 l (push d l)))
17061 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17062 l (push h l)))
17063 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17064 l (push m l)))
17065 (apply 'format fmt (nreverse l))))
17067 (defun org-time-string-to-time (s &optional buffer pos)
17068 "Convert a timestamp string into internal time."
17069 (condition-case errdata
17070 (apply 'encode-time (org-parse-time-string s))
17071 (error (error "Bad timestamp `%s'%s\nError was: %s"
17072 s (if (not (and buffer pos))
17074 (format " at %d in buffer `%s'" pos buffer))
17075 (cdr errdata)))))
17077 (defun org-time-string-to-seconds (s)
17078 "Convert a timestamp string to a number of seconds."
17079 (org-float-time (org-time-string-to-time s)))
17081 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17082 "Convert a time stamp to an absolute day number.
17083 If there is a specifier for a cyclic time stamp, get the closest
17084 date to DAYNR.
17085 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17086 The variable `date' is bound by the calendar when this is called."
17087 (cond
17088 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17089 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17090 daynr
17091 (+ daynr 1000)))
17092 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17093 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17094 (time-to-days (current-time))) (match-string 0 s)
17095 prefer show-all))
17096 (t (time-to-days
17097 (condition-case errdata
17098 (apply 'encode-time (org-parse-time-string s))
17099 (error (error "Bad timestamp `%s'%s\nError was: %s"
17100 s (if (not (and buffer pos))
17102 (format " at %d in buffer `%s'" pos buffer))
17103 (cdr errdata))))))))
17105 (defun org-days-to-iso-week (days)
17106 "Return the iso week number."
17107 (require 'cal-iso)
17108 (car (calendar-iso-from-absolute days)))
17110 (defun org-small-year-to-year (year)
17111 "Convert 2-digit years into 4-digit years.
17112 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17113 The year 2000 cannot be abbreviated. Any year larger than 99
17114 is returned unchanged."
17115 (if (< year 38)
17116 (setq year (+ 2000 year))
17117 (if (< year 100)
17118 (setq year (+ 1900 year))))
17119 year)
17121 (defun org-time-from-absolute (d)
17122 "Return the time corresponding to date D.
17123 D may be an absolute day number, or a calendar-type list (month day year)."
17124 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17125 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17127 (defun org-calendar-holiday ()
17128 "List of holidays, for Diary display in Org-mode."
17129 (require 'holidays)
17130 (let ((hl (funcall
17131 (if (fboundp 'calendar-check-holidays)
17132 'calendar-check-holidays 'check-calendar-holidays) date)))
17133 (if hl (mapconcat 'identity hl "; "))))
17135 (defun org-diary-sexp-entry (sexp entry date)
17136 "Process a SEXP diary ENTRY for DATE."
17137 (require 'diary-lib)
17138 (let ((result (if calendar-debug-sexp
17139 (let ((stack-trace-on-error t))
17140 (eval (car (read-from-string sexp))))
17141 (condition-case nil
17142 (eval (car (read-from-string sexp)))
17143 (error
17144 (beep)
17145 (message "Bad sexp at line %d in %s: %s"
17146 (org-current-line)
17147 (buffer-file-name) sexp)
17148 (sleep-for 2))))))
17149 (cond ((stringp result) (split-string result "; "))
17150 ((and (consp result)
17151 (not (consp (cdr result)))
17152 (stringp (cdr result))) (cdr result))
17153 ((and (consp result)
17154 (stringp (car result))) result)
17155 (result entry))))
17157 (defun org-diary-to-ical-string (frombuf)
17158 "Get iCalendar entries from diary entries in buffer FROMBUF.
17159 This uses the icalendar.el library."
17160 (let* ((tmpdir (if (featurep 'xemacs)
17161 (temp-directory)
17162 temporary-file-directory))
17163 (tmpfile (make-temp-name
17164 (expand-file-name "orgics" tmpdir)))
17165 buf rtn b e)
17166 (with-current-buffer frombuf
17167 (icalendar-export-region (point-min) (point-max) tmpfile)
17168 (setq buf (find-buffer-visiting tmpfile))
17169 (set-buffer buf)
17170 (goto-char (point-min))
17171 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17172 (setq b (match-beginning 0)))
17173 (goto-char (point-max))
17174 (if (re-search-backward "^END:VEVENT" nil t)
17175 (setq e (match-end 0)))
17176 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17177 (kill-buffer buf)
17178 (delete-file tmpfile)
17179 rtn))
17181 (defun org-closest-date (start current change prefer show-all)
17182 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17183 When PREFER is `past', return a date that is either CURRENT or past.
17184 When PREFER is `future', return a date that is either CURRENT or future.
17185 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17186 ;; Make the proper lists from the dates
17187 (catch 'exit
17188 (let ((a1 '(("h" . hour)
17189 ("d" . day)
17190 ("w" . week)
17191 ("m" . month)
17192 ("y" . year)))
17193 (shour (nth 2 (org-parse-time-string start)))
17194 dn dw sday cday n1 n2 n0
17195 d m y y1 y2 date1 date2 nmonths nm ny m2)
17197 (setq start (org-date-to-gregorian start)
17198 current (org-date-to-gregorian
17199 (if show-all
17200 current
17201 (time-to-days (current-time))))
17202 sday (calendar-absolute-from-gregorian start)
17203 cday (calendar-absolute-from-gregorian current))
17205 (if (<= cday sday) (throw 'exit sday))
17207 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17208 (setq dn (string-to-number (match-string 1 change))
17209 dw (cdr (assoc (match-string 2 change) a1)))
17210 (user-error "Invalid change specifier: %s" change))
17211 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17212 (cond
17213 ((eq dw 'hour)
17214 (let ((missing-hours
17215 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17216 dn)))
17217 (setq n1 (if (zerop missing-hours) cday
17218 (- cday (1+ (floor (/ missing-hours 24)))))
17219 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17220 ((eq dw 'day)
17221 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17222 n2 (+ n1 dn)))
17223 ((eq dw 'year)
17224 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17225 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17226 (setq date1 (list m d y1)
17227 n1 (calendar-absolute-from-gregorian date1)
17228 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17229 n2 (calendar-absolute-from-gregorian date2)))
17230 ((eq dw 'month)
17231 ;; approx number of month between the two dates
17232 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17233 ;; How often does dn fit in there?
17234 (setq d (nth 1 start) m (car start) y (nth 2 start)
17235 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17236 m (+ m nm)
17237 ny (floor (/ m 12))
17238 y (+ y ny)
17239 m (- m (* ny 12)))
17240 (while (> m 12) (setq m (- m 12) y (1+ y)))
17241 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17242 (setq m2 (+ m dn) y2 y)
17243 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17244 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17245 (while (<= n2 cday)
17246 (setq n1 n2 m m2 y y2)
17247 (setq m2 (+ m dn) y2 y)
17248 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17249 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17250 ;; Make sure n1 is the earlier date
17251 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17252 (if show-all
17253 (cond
17254 ((eq prefer 'past) (if (= cday n2) n2 n1))
17255 ((eq prefer 'future) (if (= cday n1) n1 n2))
17256 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17257 (cond
17258 ((eq prefer 'past) (if (= cday n2) n2 n1))
17259 ((eq prefer 'future) (if (= cday n1) n1 n2))
17260 (t (if (= cday n1) n1 n2)))))))
17262 (defun org-date-to-gregorian (date)
17263 "Turn any specification of DATE into a Gregorian date for the calendar."
17264 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17265 ((and (listp date) (= (length date) 3)) date)
17266 ((stringp date)
17267 (setq date (org-parse-time-string date))
17268 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17269 ((listp date)
17270 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17272 (defun org-parse-time-string (s &optional nodefault)
17273 "Parse the standard Org-mode time string.
17274 This should be a lot faster than the normal `parse-time-string'.
17275 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17276 hour and minute fields will be nil if not given."
17277 (cond ((string-match org-ts-regexp0 s)
17278 (list 0
17279 (if (or (match-beginning 8) (not nodefault))
17280 (string-to-number (or (match-string 8 s) "0")))
17281 (if (or (match-beginning 7) (not nodefault))
17282 (string-to-number (or (match-string 7 s) "0")))
17283 (string-to-number (match-string 4 s))
17284 (string-to-number (match-string 3 s))
17285 (string-to-number (match-string 2 s))
17286 nil nil nil))
17287 ((string-match "^<[^>]+>$" s)
17288 (decode-time (seconds-to-time (org-matcher-time s))))
17289 (t (error "Not a standard Org-mode time string: %s" s))))
17291 (defun org-timestamp-up (&optional arg)
17292 "Increase the date item at the cursor by one.
17293 If the cursor is on the year, change the year. If it is on the month,
17294 the day or the time, change that.
17295 With prefix ARG, change by that many units."
17296 (interactive "p")
17297 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17299 (defun org-timestamp-down (&optional arg)
17300 "Decrease the date item at the cursor by one.
17301 If the cursor is on the year, change the year. If it is on the month,
17302 the day or the time, change that.
17303 With prefix ARG, change by that many units."
17304 (interactive "p")
17305 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17307 (defun org-timestamp-up-day (&optional arg)
17308 "Increase the date in the time stamp by one day.
17309 With prefix ARG, change that many days."
17310 (interactive "p")
17311 (if (and (not (org-at-timestamp-p t))
17312 (org-at-heading-p))
17313 (org-todo 'up)
17314 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17316 (defun org-timestamp-down-day (&optional arg)
17317 "Decrease the date in the time stamp by one day.
17318 With prefix ARG, change that many days."
17319 (interactive "p")
17320 (if (and (not (org-at-timestamp-p t))
17321 (org-at-heading-p))
17322 (org-todo 'down)
17323 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17325 (defun org-at-timestamp-p (&optional inactive-ok)
17326 "Determine if the cursor is in or at a timestamp."
17327 (interactive)
17328 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17329 (pos (point))
17330 (ans (or (looking-at tsr)
17331 (save-excursion
17332 (skip-chars-backward "^[<\n\r\t")
17333 (if (> (point) (point-min)) (backward-char 1))
17334 (and (looking-at tsr)
17335 (> (- (match-end 0) pos) -1))))))
17336 (and ans
17337 (boundp 'org-ts-what)
17338 (setq org-ts-what
17339 (cond
17340 ((= pos (match-beginning 0)) 'bracket)
17341 ;; Point is considered to be "on the bracket" whether
17342 ;; it's really on it or right after it.
17343 ((= pos (1- (match-end 0))) 'bracket)
17344 ((= pos (match-end 0)) 'after)
17345 ((org-pos-in-match-range pos 2) 'year)
17346 ((org-pos-in-match-range pos 3) 'month)
17347 ((org-pos-in-match-range pos 7) 'hour)
17348 ((org-pos-in-match-range pos 8) 'minute)
17349 ((or (org-pos-in-match-range pos 4)
17350 (org-pos-in-match-range pos 5)) 'day)
17351 ((and (> pos (or (match-end 8) (match-end 5)))
17352 (< pos (match-end 0)))
17353 (- pos (or (match-end 8) (match-end 5))))
17354 (t 'day))))
17355 ans))
17357 (defun org-toggle-timestamp-type ()
17358 "Toggle the type (<active> or [inactive]) of a time stamp."
17359 (interactive)
17360 (when (org-at-timestamp-p t)
17361 (let ((beg (match-beginning 0)) (end (match-end 0))
17362 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17363 (save-excursion
17364 (goto-char beg)
17365 (while (re-search-forward "[][<>]" end t)
17366 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17367 t t)))
17368 (message "Timestamp is now %sactive"
17369 (if (equal (char-after beg) ?<) "" "in")))))
17371 (defun org-at-clock-log-p nil
17372 "Is the cursor on the clock log line?"
17373 (save-excursion
17374 (move-beginning-of-line 1)
17375 (looking-at "^[ \t]*CLOCK:")))
17377 (defvar org-clock-history) ; defined in org-clock.el
17378 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17379 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17380 "Change the date in the time stamp at point.
17381 The date will be changed by N times WHAT. WHAT can be `day', `month',
17382 `year', `minute', `second'. If WHAT is not given, the cursor position
17383 in the timestamp determines what will be changed.
17384 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17385 (let ((origin (point)) origin-cat
17386 with-hm inactive
17387 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17388 org-ts-what
17389 extra rem
17390 ts time time0 fixnext clrgx)
17391 (if (not (org-at-timestamp-p t))
17392 (user-error "Not at a timestamp"))
17393 (if (and (not what) (eq org-ts-what 'bracket))
17394 (org-toggle-timestamp-type)
17395 ;; Point isn't on brackets. Remember the part of the time-stamp
17396 ;; the point was in. Indeed, size of time-stamps may change,
17397 ;; but point must be kept in the same category nonetheless.
17398 (setq origin-cat org-ts-what)
17399 (if (and (not what) (not (eq org-ts-what 'day))
17400 org-display-custom-times
17401 (get-text-property (point) 'display)
17402 (not (get-text-property (1- (point)) 'display)))
17403 (setq org-ts-what 'day))
17404 (setq org-ts-what (or what org-ts-what)
17405 inactive (= (char-after (match-beginning 0)) ?\[)
17406 ts (match-string 0))
17407 (replace-match "")
17408 (when (string-match
17409 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17411 (setq extra (match-string 1 ts))
17412 (if suppress-tmp-delay
17413 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17414 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17415 (setq with-hm t))
17416 (setq time0 (org-parse-time-string ts))
17417 (when (and updown
17418 (eq org-ts-what 'minute)
17419 (not current-prefix-arg))
17420 ;; This looks like s-up and s-down. Change by one rounding step.
17421 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17422 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17423 (setcar (cdr time0) (+ (nth 1 time0)
17424 (if (> n 0) (- rem) (- dm rem))))))
17425 (setq time
17426 (encode-time (or (car time0) 0)
17427 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17428 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17429 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17430 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17431 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17432 (nthcdr 6 time0)))
17433 (when (and (member org-ts-what '(hour minute))
17434 extra
17435 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17436 (setq extra (org-modify-ts-extra
17437 extra
17438 (if (eq org-ts-what 'hour) 2 5)
17439 n dm)))
17440 (when (integerp org-ts-what)
17441 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17442 (if (eq what 'calendar)
17443 (let ((cal-date (org-get-date-from-calendar)))
17444 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17445 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17446 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17447 (setcar time0 (or (car time0) 0))
17448 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17449 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17450 (setq time (apply 'encode-time time0))))
17451 ;; Insert the new time-stamp, and ensure point stays in the same
17452 ;; category as before (i.e. not after the last position in that
17453 ;; category).
17454 (let ((pos (point)))
17455 ;; Stay before inserted string. `save-excursion' is of no use.
17456 (setq org-last-changed-timestamp
17457 (org-insert-time-stamp time with-hm inactive nil nil extra))
17458 (goto-char pos))
17459 (save-match-data
17460 (looking-at org-ts-regexp3)
17461 (goto-char (cond
17462 ;; `day' category ends before `hour' if any, or at
17463 ;; the end of the day name.
17464 ((eq origin-cat 'day)
17465 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17466 ((eq origin-cat 'hour) (min (match-end 7) origin))
17467 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17468 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17469 ;; `year' and `month' have both fixed size: point
17470 ;; couldn't have moved into another part.
17471 (t origin))))
17472 ;; Update clock if on a CLOCK line.
17473 (org-clock-update-time-maybe)
17474 ;; Maybe adjust the closest clock in `org-clock-history'
17475 (when org-clock-adjust-closest
17476 (if (not (and (org-at-clock-log-p)
17477 (< 1 (length (delq nil (mapcar 'marker-position
17478 org-clock-history))))))
17479 (message "No clock to adjust")
17480 (cond ((save-excursion ; fix previous clock?
17481 (re-search-backward org-ts-regexp0 nil t)
17482 (org-looking-back (concat org-clock-string " \\[")))
17483 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17484 ((save-excursion ; fix next clock?
17485 (re-search-backward org-ts-regexp0 nil t)
17486 (looking-at (concat org-ts-regexp0 "\\] =>")))
17487 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17488 (save-window-excursion
17489 ;; Find closest clock to point, adjust the previous/next one in history
17490 (let* ((p (save-excursion (org-back-to-heading t)))
17491 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17492 (clfixnth
17493 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17494 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17495 (if (not clfixpos)
17496 (message "No clock to adjust")
17497 (save-excursion
17498 (org-goto-marker-or-bmk clfixpos)
17499 (org-show-subtree)
17500 (when (re-search-forward clrgx nil t)
17501 (goto-char (match-beginning 1))
17502 (let (org-clock-adjust-closest)
17503 (org-timestamp-change n org-ts-what updown))
17504 (message "Clock adjusted in %s for heading: %s"
17505 (file-name-nondirectory (buffer-file-name))
17506 (org-get-heading t t)))))))))
17507 ;; Try to recenter the calendar window, if any.
17508 (if (and org-calendar-follow-timestamp-change
17509 (get-buffer-window "*Calendar*" t)
17510 (memq org-ts-what '(day month year)))
17511 (org-recenter-calendar (time-to-days time))))))
17513 (defun org-modify-ts-extra (s pos n dm)
17514 "Change the different parts of the lead-time and repeat fields in timestamp."
17515 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17516 ng h m new rem)
17517 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17518 (cond
17519 ((or (org-pos-in-match-range pos 2)
17520 (org-pos-in-match-range pos 3))
17521 (setq m (string-to-number (match-string 3 s))
17522 h (string-to-number (match-string 2 s)))
17523 (if (org-pos-in-match-range pos 2)
17524 (setq h (+ h n))
17525 (setq n (* dm (org-no-warnings (signum n))))
17526 (when (not (= 0 (setq rem (% m dm))))
17527 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17528 (setq m (+ m n)))
17529 (if (< m 0) (setq m (+ m 60) h (1- h)))
17530 (if (> m 59) (setq m (- m 60) h (1+ h)))
17531 (setq h (min 24 (max 0 h)))
17532 (setq ng 1 new (format "-%02d:%02d" h m)))
17533 ((org-pos-in-match-range pos 6)
17534 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17535 ((org-pos-in-match-range pos 5)
17536 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17538 ((org-pos-in-match-range pos 9)
17539 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17540 ((org-pos-in-match-range pos 8)
17541 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17543 (when ng
17544 (setq s (concat
17545 (substring s 0 (match-beginning ng))
17547 (substring s (match-end ng))))))
17550 (defun org-recenter-calendar (date)
17551 "If the calendar is visible, recenter it to DATE."
17552 (let ((cwin (get-buffer-window "*Calendar*" t)))
17553 (when cwin
17554 (let ((calendar-move-hook nil))
17555 (with-selected-window cwin
17556 (calendar-goto-date (if (listp date) date
17557 (calendar-gregorian-from-absolute date))))))))
17559 (defun org-goto-calendar (&optional arg)
17560 "Go to the Emacs calendar at the current date.
17561 If there is a time stamp in the current line, go to that date.
17562 A prefix ARG can be used to force the current date."
17563 (interactive "P")
17564 (let ((tsr org-ts-regexp) diff
17565 (calendar-move-hook nil)
17566 (calendar-view-holidays-initially-flag nil)
17567 (calendar-view-diary-initially-flag nil))
17568 (if (or (org-at-timestamp-p)
17569 (save-excursion
17570 (beginning-of-line 1)
17571 (looking-at (concat ".*" tsr))))
17572 (let ((d1 (time-to-days (current-time)))
17573 (d2 (time-to-days
17574 (org-time-string-to-time (match-string 1)))))
17575 (setq diff (- d2 d1))))
17576 (calendar)
17577 (calendar-goto-today)
17578 (if (and diff (not arg)) (calendar-forward-day diff))))
17580 (defun org-get-date-from-calendar ()
17581 "Return a list (month day year) of date at point in calendar."
17582 (with-current-buffer "*Calendar*"
17583 (save-match-data
17584 (calendar-cursor-to-date))))
17586 (defun org-date-from-calendar ()
17587 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17588 If there is already a time stamp at the cursor position, update it."
17589 (interactive)
17590 (if (org-at-timestamp-p t)
17591 (org-timestamp-change 0 'calendar)
17592 (let ((cal-date (org-get-date-from-calendar)))
17593 (org-insert-time-stamp
17594 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17596 (defcustom org-effort-durations
17597 `(("h" . 60)
17598 ("d" . ,(* 60 8))
17599 ("w" . ,(* 60 8 5))
17600 ("m" . ,(* 60 8 5 4))
17601 ("y" . ,(* 60 8 5 40)))
17602 "Conversion factor to minutes for an effort modifier.
17604 Each entry has the form (MODIFIER . MINUTES).
17606 In an effort string, a number followed by MODIFIER is multiplied
17607 by the specified number of MINUTES to obtain an effort in
17608 minutes.
17610 For example, if the value of this variable is ((\"hours\" . 60)), then an
17611 effort string \"2hours\" is equivalent to 120 minutes."
17612 :group 'org-agenda
17613 :version "24.1"
17614 :type '(alist :key-type (string :tag "Modifier")
17615 :value-type (number :tag "Minutes")))
17617 (defun org-minutes-to-clocksum-string (m)
17618 "Format number of minutes as a clocksum string.
17619 The format is determined by `org-time-clocksum-format',
17620 `org-time-clocksum-use-fractional' and
17621 `org-time-clocksum-fractional-format' and
17622 `org-time-clocksum-use-effort-durations'."
17623 (let ((clocksum "")
17624 (m (round m)) ; Don't allow fractions of minutes
17625 h d w mo y fmt n)
17626 (setq h (if org-time-clocksum-use-effort-durations
17627 (cdr (assoc "h" org-effort-durations)) 60)
17628 d (if org-time-clocksum-use-effort-durations
17629 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17630 w (if org-time-clocksum-use-effort-durations
17631 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17632 mo (if org-time-clocksum-use-effort-durations
17633 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17634 y (if org-time-clocksum-use-effort-durations
17635 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17636 ;; fractional format
17637 (if org-time-clocksum-use-fractional
17638 (cond
17639 ;; single format string
17640 ((stringp org-time-clocksum-fractional-format)
17641 (format org-time-clocksum-fractional-format (/ m (float h))))
17642 ;; choice of fractional formats for different time units
17643 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17644 (> (/ (truncate m) (* y d h)) 0))
17645 (format fmt (/ m (* y d (float h)))))
17646 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17647 (> (/ (truncate m) (* mo d h)) 0))
17648 (format fmt (/ m (* mo d (float h)))))
17649 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17650 (> (/ (truncate m) (* w d h)) 0))
17651 (format fmt (/ m (* w d (float h)))))
17652 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17653 (> (/ (truncate m) (* d h)) 0))
17654 (format fmt (/ m (* d (float h)))))
17655 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17656 (> (/ (truncate m) h) 0))
17657 (format fmt (/ m (float h))))
17658 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17659 (format fmt m))
17660 ;; fall back to smallest time unit with a format
17661 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17662 (format fmt (/ m (float h))))
17663 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17664 (format fmt (/ m (* d (float h)))))
17665 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17666 (format fmt (/ m (* w d (float h)))))
17667 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17668 (format fmt (/ m (* mo d (float h)))))
17669 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17670 (format fmt (/ m (* y d (float h))))))
17671 ;; standard (non-fractional) format, with single format string
17672 (if (stringp org-time-clocksum-format)
17673 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17674 ;; separate formats components
17675 (and (setq fmt (plist-get org-time-clocksum-format :years))
17676 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17677 (plist-get org-time-clocksum-format :require-years))
17678 (setq clocksum (concat clocksum (format fmt n))
17679 m (- m (* n y d h))))
17680 (and (setq fmt (plist-get org-time-clocksum-format :months))
17681 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17682 (plist-get org-time-clocksum-format :require-months))
17683 (setq clocksum (concat clocksum (format fmt n))
17684 m (- m (* n mo d h))))
17685 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17686 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17687 (plist-get org-time-clocksum-format :require-weeks))
17688 (setq clocksum (concat clocksum (format fmt n))
17689 m (- m (* n w d h))))
17690 (and (setq fmt (plist-get org-time-clocksum-format :days))
17691 (or (> (setq n (/ (truncate m) (* d h))) 0)
17692 (plist-get org-time-clocksum-format :require-days))
17693 (setq clocksum (concat clocksum (format fmt n))
17694 m (- m (* n d h))))
17695 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17696 (or (> (setq n (/ (truncate m) h)) 0)
17697 (plist-get org-time-clocksum-format :require-hours))
17698 (setq clocksum (concat clocksum (format fmt n))
17699 m (- m (* n h))))
17700 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17701 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17702 (setq clocksum (concat clocksum (format fmt m))))
17703 ;; return formatted time duration
17704 clocksum))))
17706 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17707 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17708 "Org mode version 8.0")
17710 (defun org-hours-to-clocksum-string (n)
17711 (org-minutes-to-clocksum-string (* n 60)))
17713 (defun org-hh:mm-string-to-minutes (s)
17714 "Convert a string H:MM to a number of minutes.
17715 If the string is just a number, interpret it as minutes.
17716 In fact, the first hh:mm or number in the string will be taken,
17717 there can be extra stuff in the string.
17718 If no number is found, the return value is 0."
17719 (cond
17720 ((integerp s) s)
17721 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17722 (+ (* (string-to-number (match-string 1 s)) 60)
17723 (string-to-number (match-string 2 s))))
17724 ((string-match "\\([0-9]+\\)" s)
17725 (string-to-number (match-string 1 s)))
17726 (t 0)))
17728 (defcustom org-image-actual-width t
17729 "Should we use the actual width of images when inlining them?
17731 When set to `t', always use the image width.
17733 When set to a number, use imagemagick (when available) to set
17734 the image's width to this value.
17736 When set to a number in a list, try to get the width from any
17737 #+ATTR.* keyword if it matches a width specification like
17739 #+ATTR_HTML: :width 300px
17741 and fall back on that number if none is found.
17743 When set to nil, try to get the width from an #+ATTR.* keyword
17744 and fall back on the original width if none is found.
17746 This requires Emacs >= 24.1, build with imagemagick support."
17747 :group 'org-appearance
17748 :version "24.4"
17749 :package-version '(Org . "8.0")
17750 :type '(choice
17751 (const :tag "Use the image width" t)
17752 (integer :tag "Use a number of pixels")
17753 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17754 (const :tag "Use #+ATTR* or don't resize" nil)))
17756 (defcustom org-agenda-inhibit-startup nil
17757 "Inhibit startup when preparing agenda buffers.
17758 When this variable is `t' (the default), the initialization of
17759 the Org agenda buffers is inhibited: e.g. the visibility state
17760 is not set, the tables are not re-aligned, etc."
17761 :type 'boolean
17762 :version "24.3"
17763 :group 'org-agenda)
17765 (defcustom org-agenda-ignore-drawer-properties nil
17766 "Avoid updating text properties when building the agenda.
17767 Properties are used to prepare buffers for effort estimates, appointments,
17768 and subtree-local categories.
17769 If you don't use these in the agenda, you can add them to this list and
17770 agenda building will be a bit faster.
17771 The value is a list, with zero or more of the symbols `effort', `appt',
17772 or `category'."
17773 :type '(set :greedy t
17774 (const effort)
17775 (const appt)
17776 (const category))
17777 :version "24.3"
17778 :group 'org-agenda)
17780 (defun org-duration-string-to-minutes (s &optional output-to-string)
17781 "Convert a duration string S to minutes.
17783 A bare number is interpreted as minutes, modifiers can be set by
17784 customizing `org-effort-durations' (which see).
17786 Entries containing a colon are interpreted as H:MM by
17787 `org-hh:mm-string-to-minutes'."
17788 (let ((result 0)
17789 (re (concat "\\([0-9.]+\\) *\\("
17790 (regexp-opt (mapcar 'car org-effort-durations))
17791 "\\)")))
17792 (while (string-match re s)
17793 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17794 (string-to-number (match-string 1 s))))
17795 (setq s (replace-match "" nil t s)))
17796 (setq result (floor result))
17797 (incf result (org-hh:mm-string-to-minutes s))
17798 (if output-to-string (number-to-string result) result)))
17800 ;;;; Files
17802 (defun org-save-all-org-buffers ()
17803 "Save all Org-mode buffers without user confirmation."
17804 (interactive)
17805 (message "Saving all Org-mode buffers...")
17806 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17807 (when (featurep 'org-id) (org-id-locations-save))
17808 (message "Saving all Org-mode buffers... done"))
17810 (defun org-revert-all-org-buffers ()
17811 "Revert all Org-mode buffers.
17812 Prompt for confirmation when there are unsaved changes.
17813 Be sure you know what you are doing before letting this function
17814 overwrite your changes.
17816 This function is useful in a setup where one tracks org files
17817 with a version control system, to revert on one machine after pulling
17818 changes from another. I believe the procedure must be like this:
17820 1. M-x org-save-all-org-buffers
17821 2. Pull changes from the other machine, resolve conflicts
17822 3. M-x org-revert-all-org-buffers"
17823 (interactive)
17824 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17825 (user-error "Abort"))
17826 (save-excursion
17827 (save-window-excursion
17828 (mapc
17829 (lambda (b)
17830 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17831 (with-current-buffer b buffer-file-name))
17832 (org-pop-to-buffer-same-window b)
17833 (revert-buffer t 'no-confirm)))
17834 (buffer-list))
17835 (when (and (featurep 'org-id) org-id-track-globally)
17836 (org-id-locations-load)))))
17838 ;;;; Agenda files
17840 ;;;###autoload
17841 (defun org-switchb (&optional arg)
17842 "Switch between Org buffers.
17843 With one prefix argument, restrict available buffers to files.
17844 With two prefix arguments, restrict available buffers to agenda files.
17846 Defaults to `iswitchb' for buffer name completion.
17847 Set `org-completion-use-ido' to make it use ido instead."
17848 (interactive "P")
17849 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17850 ((equal arg '(16)) (org-buffer-list 'agenda))
17851 (t (org-buffer-list))))
17852 (org-completion-use-iswitchb org-completion-use-iswitchb)
17853 (org-completion-use-ido org-completion-use-ido))
17854 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17855 (setq org-completion-use-iswitchb t))
17856 (org-pop-to-buffer-same-window
17857 (org-icompleting-read "Org buffer: "
17858 (mapcar 'list (mapcar 'buffer-name blist))
17859 nil t))))
17861 ;;; Define some older names previously used for this functionality
17862 ;;;###autoload
17863 (defalias 'org-ido-switchb 'org-switchb)
17864 ;;;###autoload
17865 (defalias 'org-iswitchb 'org-switchb)
17867 (defun org-buffer-list (&optional predicate exclude-tmp)
17868 "Return a list of Org buffers.
17869 PREDICATE can be `export', `files' or `agenda'.
17871 export restrict the list to Export buffers.
17872 files restrict the list to buffers visiting Org files.
17873 agenda restrict the list to buffers visiting agenda files.
17875 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17876 (let* ((bfn nil)
17877 (agenda-files (and (eq predicate 'agenda)
17878 (mapcar 'file-truename (org-agenda-files t))))
17879 (filter
17880 (cond
17881 ((eq predicate 'files)
17882 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17883 ((eq predicate 'export)
17884 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17885 ((eq predicate 'agenda)
17886 (lambda (b)
17887 (with-current-buffer b
17888 (and (derived-mode-p 'org-mode)
17889 (setq bfn (buffer-file-name b))
17890 (member (file-truename bfn) agenda-files)))))
17891 (t (lambda (b) (with-current-buffer b
17892 (or (derived-mode-p 'org-mode)
17893 (string-match "\*Org .*Export"
17894 (buffer-name b)))))))))
17895 (delq nil
17896 (mapcar
17897 (lambda(b)
17898 (if (and (funcall filter b)
17899 (or (not exclude-tmp)
17900 (not (string-match "tmp" (buffer-name b)))))
17902 nil))
17903 (buffer-list)))))
17905 (defun org-agenda-files (&optional unrestricted archives)
17906 "Get the list of agenda files.
17907 Optional UNRESTRICTED means return the full list even if a restriction
17908 is currently in place.
17909 When ARCHIVES is t, include all archive files that are really being
17910 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17911 `org-agenda-archives-mode' is t."
17912 (let ((files
17913 (cond
17914 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17915 ((stringp org-agenda-files) (org-read-agenda-file-list))
17916 ((listp org-agenda-files) org-agenda-files)
17917 (t (error "Invalid value of `org-agenda-files'")))))
17918 (setq files (apply 'append
17919 (mapcar (lambda (f)
17920 (if (file-directory-p f)
17921 (directory-files
17922 f t org-agenda-file-regexp)
17923 (list f)))
17924 files)))
17925 (when org-agenda-skip-unavailable-files
17926 (setq files (delq nil
17927 (mapcar (function
17928 (lambda (file)
17929 (and (file-readable-p file) file)))
17930 files))))
17931 (when (or (eq archives t)
17932 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17933 (setq files (org-add-archive-files files)))
17934 files))
17936 (defun org-agenda-file-p (&optional file)
17937 "Return non-nil, if FILE is an agenda file.
17938 If FILE is omitted, use the file associated with the current
17939 buffer."
17940 (member (or file (buffer-file-name))
17941 (org-agenda-files t)))
17943 (defun org-edit-agenda-file-list ()
17944 "Edit the list of agenda files.
17945 Depending on setup, this either uses customize to edit the variable
17946 `org-agenda-files', or it visits the file that is holding the list. In the
17947 latter case, the buffer is set up in a way that saving it automatically kills
17948 the buffer and restores the previous window configuration."
17949 (interactive)
17950 (if (stringp org-agenda-files)
17951 (let ((cw (current-window-configuration)))
17952 (find-file org-agenda-files)
17953 (org-set-local 'org-window-configuration cw)
17954 (org-add-hook 'after-save-hook
17955 (lambda ()
17956 (set-window-configuration
17957 (prog1 org-window-configuration
17958 (kill-buffer (current-buffer))))
17959 (org-install-agenda-files-menu)
17960 (message "New agenda file list installed"))
17961 nil 'local)
17962 (message "%s" (substitute-command-keys
17963 "Edit list and finish with \\[save-buffer]")))
17964 (customize-variable 'org-agenda-files)))
17966 (defun org-store-new-agenda-file-list (list)
17967 "Set new value for the agenda file list and save it correctly."
17968 (if (stringp org-agenda-files)
17969 (let ((fe (org-read-agenda-file-list t)) b u)
17970 (while (setq b (find-buffer-visiting org-agenda-files))
17971 (kill-buffer b))
17972 (with-temp-file org-agenda-files
17973 (insert
17974 (mapconcat
17975 (lambda (f) ;; Keep un-expanded entries.
17976 (if (setq u (assoc f fe))
17977 (cdr u)
17979 list "\n")
17980 "\n")))
17981 (let ((org-mode-hook nil) (org-inhibit-startup t)
17982 (org-insert-mode-line-in-empty-file nil))
17983 (setq org-agenda-files list)
17984 (customize-save-variable 'org-agenda-files org-agenda-files))))
17986 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17987 "Read the list of agenda files from a file.
17988 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17989 filenames, used by `org-store-new-agenda-file-list' to write back
17990 un-expanded file names."
17991 (when (file-directory-p org-agenda-files)
17992 (error "`org-agenda-files' cannot be a single directory"))
17993 (when (stringp org-agenda-files)
17994 (with-temp-buffer
17995 (insert-file-contents org-agenda-files)
17996 (mapcar
17997 (lambda (f)
17998 (let ((e (expand-file-name (substitute-in-file-name f)
17999 org-directory)))
18000 (if pair-with-expansion
18001 (cons e f)
18002 e)))
18003 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18005 ;;;###autoload
18006 (defun org-cycle-agenda-files ()
18007 "Cycle through the files in `org-agenda-files'.
18008 If the current buffer visits an agenda file, find the next one in the list.
18009 If the current buffer does not, find the first agenda file."
18010 (interactive)
18011 (let* ((fs (org-agenda-files t))
18012 (files (append fs (list (car fs))))
18013 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18014 file)
18015 (unless files (user-error "No agenda files"))
18016 (catch 'exit
18017 (while (setq file (pop files))
18018 (if (equal (file-truename file) tcf)
18019 (when (car files)
18020 (find-file (car files))
18021 (throw 'exit t))))
18022 (find-file (car fs)))
18023 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18025 (defun org-agenda-file-to-front (&optional to-end)
18026 "Move/add the current file to the top of the agenda file list.
18027 If the file is not present in the list, it is added to the front. If it is
18028 present, it is moved there. With optional argument TO-END, add/move to the
18029 end of the list."
18030 (interactive "P")
18031 (let ((org-agenda-skip-unavailable-files nil)
18032 (file-alist (mapcar (lambda (x)
18033 (cons (file-truename x) x))
18034 (org-agenda-files t)))
18035 (ctf (file-truename
18036 (or buffer-file-name
18037 (user-error "Please save the current buffer to a file"))))
18038 x had)
18039 (setq x (assoc ctf file-alist) had x)
18041 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18042 (if to-end
18043 (setq file-alist (append (delq x file-alist) (list x)))
18044 (setq file-alist (cons x (delq x file-alist))))
18045 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18046 (org-install-agenda-files-menu)
18047 (message "File %s to %s of agenda file list"
18048 (if had "moved" "added") (if to-end "end" "front"))))
18050 (defun org-remove-file (&optional file)
18051 "Remove current file from the list of files in variable `org-agenda-files'.
18052 These are the files which are being checked for agenda entries.
18053 Optional argument FILE means use this file instead of the current."
18054 (interactive)
18055 (let* ((org-agenda-skip-unavailable-files nil)
18056 (file (or file buffer-file-name
18057 (user-error "Current buffer does not visit a file")))
18058 (true-file (file-truename file))
18059 (afile (abbreviate-file-name file))
18060 (files (delq nil (mapcar
18061 (lambda (x)
18062 (if (equal true-file
18063 (file-truename x))
18064 nil x))
18065 (org-agenda-files t)))))
18066 (if (not (= (length files) (length (org-agenda-files t))))
18067 (progn
18068 (org-store-new-agenda-file-list files)
18069 (org-install-agenda-files-menu)
18070 (message "Removed file: %s" afile))
18071 (message "File was not in list: %s (not removed)" afile))))
18073 (defun org-file-menu-entry (file)
18074 (vector file (list 'find-file file) t))
18076 (defun org-check-agenda-file (file)
18077 "Make sure FILE exists. If not, ask user what to do."
18078 (when (not (file-exists-p file))
18079 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18080 (abbreviate-file-name file))
18081 (let ((r (downcase (read-char-exclusive))))
18082 (cond
18083 ((equal r ?r)
18084 (org-remove-file file)
18085 (throw 'nextfile t))
18086 (t (error "Abort"))))))
18088 (defun org-get-agenda-file-buffer (file)
18089 "Get a buffer visiting FILE. If the buffer needs to be created, add
18090 it to the list of buffers which might be released later."
18091 (let ((buf (org-find-base-buffer-visiting file)))
18092 (if buf
18093 buf ; just return it
18094 ;; Make a new buffer and remember it
18095 (setq buf (find-file-noselect file))
18096 (if buf (push buf org-agenda-new-buffers))
18097 buf)))
18099 (defun org-release-buffers (blist)
18100 "Release all buffers in list, asking the user for confirmation when needed.
18101 When a buffer is unmodified, it is just killed. When modified, it is saved
18102 \(if the user agrees) and then killed."
18103 (let (buf file)
18104 (while (setq buf (pop blist))
18105 (setq file (buffer-file-name buf))
18106 (when (and (buffer-modified-p buf)
18107 file
18108 (y-or-n-p (format "Save file %s? " file)))
18109 (with-current-buffer buf (save-buffer)))
18110 (kill-buffer buf))))
18112 (defun org-agenda-prepare-buffers (files)
18113 "Create buffers for all agenda files, protect archived trees and comments."
18114 (interactive)
18115 (let ((pa '(:org-archived t))
18116 (pc '(:org-comment t))
18117 (pall '(:org-archived t :org-comment t))
18118 (inhibit-read-only t)
18119 (org-inhibit-startup org-agenda-inhibit-startup)
18120 (rea (concat ":" org-archive-tag ":"))
18121 file re pos)
18122 (setq org-tag-alist-for-agenda nil
18123 org-tag-groups-alist-for-agenda nil)
18124 (save-window-excursion
18125 (save-restriction
18126 (while (setq file (pop files))
18127 (catch 'nextfile
18128 (if (bufferp file)
18129 (set-buffer file)
18130 (org-check-agenda-file file)
18131 (set-buffer (org-get-agenda-file-buffer file)))
18132 (widen)
18133 (org-set-regexps-and-options-for-tags)
18134 (setq pos (point))
18135 (goto-char (point-min))
18136 (let ((case-fold-search t))
18137 (when (search-forward "#+setupfile" nil t)
18138 ;; Don't set all regexps and options systematically as
18139 ;; this is only run for setting agenda tags from setup
18140 ;; file
18141 (org-set-regexps-and-options)))
18142 (or (memq 'category org-agenda-ignore-drawer-properties)
18143 (org-refresh-category-properties))
18144 (or (memq 'effort org-agenda-ignore-drawer-properties)
18145 (org-refresh-properties org-effort-property 'org-effort))
18146 (or (memq 'appt org-agenda-ignore-drawer-properties)
18147 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18148 (setq org-todo-keywords-for-agenda
18149 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18150 (setq org-done-keywords-for-agenda
18151 (append org-done-keywords-for-agenda org-done-keywords))
18152 (setq org-todo-keyword-alist-for-agenda
18153 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18154 (setq org-tag-alist-for-agenda
18155 (org-uniquify
18156 (append org-tag-alist-for-agenda
18157 org-tag-alist
18158 org-tag-persistent-alist)))
18159 (if org-group-tags
18160 (setq org-tag-groups-alist-for-agenda
18161 (org-uniquify-alist
18162 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18163 (org-with-silent-modifications
18164 (save-excursion
18165 (remove-text-properties (point-min) (point-max) pall)
18166 (when org-agenda-skip-archived-trees
18167 (goto-char (point-min))
18168 (while (re-search-forward rea nil t)
18169 (if (org-at-heading-p t)
18170 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18171 (goto-char (point-min))
18172 (setq re (format org-heading-keyword-regexp-format
18173 org-comment-string))
18174 (while (re-search-forward re nil t)
18175 (add-text-properties
18176 (match-beginning 0) (org-end-of-subtree t) pc))))
18177 (goto-char pos)))))
18178 (setq org-todo-keywords-for-agenda
18179 (org-uniquify org-todo-keywords-for-agenda))
18180 (setq org-todo-keyword-alist-for-agenda
18181 (org-uniquify org-todo-keyword-alist-for-agenda))))
18184 ;;;; CDLaTeX minor mode
18186 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18187 "Keymap for the minor `org-cdlatex-mode'.")
18189 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18190 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18191 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18192 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18193 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18195 (defvar org-cdlatex-texmathp-advice-is-done nil
18196 "Flag remembering if we have applied the advice to texmathp already.")
18198 (define-minor-mode org-cdlatex-mode
18199 "Toggle the minor `org-cdlatex-mode'.
18200 This mode supports entering LaTeX environment and math in LaTeX fragments
18201 in Org-mode.
18202 \\{org-cdlatex-mode-map}"
18203 nil " OCDL" nil
18204 (when org-cdlatex-mode
18205 (require 'cdlatex)
18206 (run-hooks 'cdlatex-mode-hook)
18207 (cdlatex-compute-tables))
18208 (unless org-cdlatex-texmathp-advice-is-done
18209 (setq org-cdlatex-texmathp-advice-is-done t)
18210 (defadvice texmathp (around org-math-always-on activate)
18211 "Always return t in org-mode buffers.
18212 This is because we want to insert math symbols without dollars even outside
18213 the LaTeX math segments. If Orgmode thinks that point is actually inside
18214 an embedded LaTeX fragment, let texmathp do its job.
18215 \\[org-cdlatex-mode-map]"
18216 (interactive)
18217 (let (p)
18218 (cond
18219 ((not (derived-mode-p 'org-mode)) ad-do-it)
18220 ((eq this-command 'cdlatex-math-symbol)
18221 (setq ad-return-value t
18222 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18224 (let ((p (org-inside-LaTeX-fragment-p)))
18225 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18226 (setq ad-return-value t
18227 texmathp-why '("Org-mode embedded math" . 0))
18228 (if p ad-do-it)))))))))
18230 (defun turn-on-org-cdlatex ()
18231 "Unconditionally turn on `org-cdlatex-mode'."
18232 (org-cdlatex-mode 1))
18234 (defun org-try-cdlatex-tab ()
18235 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18236 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18237 - inside a LaTeX fragment, or
18238 - after the first word in a line, where an abbreviation expansion could
18239 insert a LaTeX environment."
18240 (when org-cdlatex-mode
18241 (cond
18242 ;; Before any word on the line: No expansion possible.
18243 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18244 ;; Just after first word on the line: Expand it. Make sure it
18245 ;; cannot happen on headlines, though.
18246 ((save-excursion
18247 (skip-chars-backward "a-zA-Z0-9*")
18248 (skip-chars-backward " \t")
18249 (and (bolp) (not (org-at-heading-p))))
18250 (cdlatex-tab) t)
18251 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18253 (defun org-cdlatex-underscore-caret (&optional arg)
18254 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18255 Revert to the normal definition outside of these fragments."
18256 (interactive "P")
18257 (if (org-inside-LaTeX-fragment-p)
18258 (call-interactively 'cdlatex-sub-superscript)
18259 (let (org-cdlatex-mode)
18260 (call-interactively (key-binding (vector last-input-event))))))
18262 (defun org-cdlatex-math-modify (&optional arg)
18263 "Execute `cdlatex-math-modify' in LaTeX fragments.
18264 Revert to the normal definition outside of these fragments."
18265 (interactive "P")
18266 (if (org-inside-LaTeX-fragment-p)
18267 (call-interactively 'cdlatex-math-modify)
18268 (let (org-cdlatex-mode)
18269 (call-interactively (key-binding (vector last-input-event))))))
18273 ;;;; LaTeX fragments
18275 (defun org-inside-LaTeX-fragment-p ()
18276 "Test if point is inside a LaTeX fragment.
18277 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18278 sequence appearing also before point.
18279 Even though the matchers for math are configurable, this function assumes
18280 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18281 delimiters are skipped when they have been removed by customization.
18282 The return value is nil, or a cons cell with the delimiter and the
18283 position of this delimiter.
18285 This function does a reasonably good job, but can locally be fooled by
18286 for example currency specifications. For example it will assume being in
18287 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18288 fragments that are properly closed, but during editing, we have to live
18289 with the uncertainty caused by missing closing delimiters. This function
18290 looks only before point, not after."
18291 (catch 'exit
18292 (let ((pos (point))
18293 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18294 (lim (progn
18295 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18296 (point)))
18297 dd-on str (start 0) m re)
18298 (goto-char pos)
18299 (when dodollar
18300 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18301 re (nth 1 (assoc "$" org-latex-regexps)))
18302 (while (string-match re str start)
18303 (cond
18304 ((= (match-end 0) (length str))
18305 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18306 ((= (match-end 0) (- (length str) 5))
18307 (throw 'exit nil))
18308 (t (setq start (match-end 0))))))
18309 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18310 (goto-char pos)
18311 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18312 (and (match-beginning 2) (throw 'exit nil))
18313 ;; count $$
18314 (while (re-search-backward "\\$\\$" lim t)
18315 (setq dd-on (not dd-on)))
18316 (goto-char pos)
18317 (if dd-on (cons "$$" m))))))
18319 (defun org-inside-latex-macro-p ()
18320 "Is point inside a LaTeX macro or its arguments?"
18321 (save-match-data
18322 (org-in-regexp
18323 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18325 (defvar org-latex-fragment-image-overlays nil
18326 "List of overlays carrying the images of latex fragments.")
18327 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18329 (defun org-remove-latex-fragment-image-overlays ()
18330 "Remove all overlays with LaTeX fragment images in current buffer."
18331 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18332 (setq org-latex-fragment-image-overlays nil))
18334 (defun org-preview-latex-fragment (&optional subtree)
18335 "Preview the LaTeX fragment at point, or all locally or globally.
18336 If the cursor is in a LaTeX fragment, create the image and overlay
18337 it over the source code. If there is no fragment at point, display
18338 all fragments in the current text, from one headline to the next. With
18339 prefix SUBTREE, display all fragments in the current subtree. With a
18340 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18341 the cursor is before the first headline,
18342 display all fragments in the buffer.
18343 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18344 (interactive "P")
18345 (unless buffer-file-name
18346 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18347 (when (display-graphic-p)
18348 (org-remove-latex-fragment-image-overlays)
18349 (save-excursion
18350 (save-restriction
18351 (let (beg end at msg)
18352 (cond
18353 ((or (equal subtree '(16))
18354 (not (save-excursion
18355 (re-search-backward org-outline-regexp-bol nil t))))
18356 (setq beg (point-min) end (point-max)
18357 msg "Creating images for buffer...%s"))
18358 ((equal subtree '(4))
18359 (org-back-to-heading)
18360 (setq beg (point) end (org-end-of-subtree t)
18361 msg "Creating images for subtree...%s"))
18363 (if (setq at (org-inside-LaTeX-fragment-p))
18364 (goto-char (max (point-min) (- (cdr at) 2)))
18365 (org-back-to-heading))
18366 (setq beg (point) end (progn (outline-next-heading) (point))
18367 msg (if at "Creating image...%s"
18368 "Creating images for entry...%s"))))
18369 (message msg "")
18370 (narrow-to-region beg end)
18371 (goto-char beg)
18372 (org-format-latex
18373 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18374 (file-name-nondirectory
18375 buffer-file-name)))
18376 default-directory 'overlays msg at 'forbuffer
18377 org-latex-create-formula-image-program)
18378 (message msg "done. Use `C-c C-c' to remove images."))))))
18380 (defun org-format-latex (prefix &optional dir overlays msg at
18381 forbuffer processing-type)
18382 "Replace LaTeX fragments with links to an image, and produce images.
18383 Some of the options can be changed using the variable
18384 `org-format-latex-options'."
18385 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18386 (let* ((prefixnodir (file-name-nondirectory prefix))
18387 (absprefix (expand-file-name prefix dir))
18388 (todir (file-name-directory absprefix))
18389 (opt org-format-latex-options)
18390 (optnew org-format-latex-options)
18391 (matchers (plist-get opt :matchers))
18392 (re-list org-latex-regexps)
18393 (cnt 0) txt hash link beg end re e checkdir
18394 string
18395 m n block-type block linkfile movefile ov)
18396 ;; Check the different regular expressions
18397 (while (setq e (pop re-list))
18398 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18399 block (if block-type "\n\n" ""))
18400 (when (member m matchers)
18401 (goto-char (point-min))
18402 (while (re-search-forward re nil t)
18403 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18404 (or (not overlays)
18405 (not (eq (get-char-property (match-beginning n)
18406 'org-overlay-type)
18407 'org-latex-overlay))))
18408 (cond
18409 ((eq processing-type 'verbatim))
18410 ((eq processing-type 'mathjax)
18411 ;; Prepare for MathJax processing.
18412 (setq string (match-string n))
18413 (when (member m '("$" "$1"))
18414 (save-excursion
18415 (delete-region (match-beginning n) (match-end n))
18416 (goto-char (match-beginning n))
18417 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18418 ((or (eq processing-type 'dvipng)
18419 (eq processing-type 'imagemagick))
18420 ;; Process to an image.
18421 (setq txt (match-string n)
18422 beg (match-beginning n) end (match-end n)
18423 cnt (1+ cnt))
18424 (let ((face (face-at-point))
18425 (fg (plist-get opt :foreground))
18426 (bg (plist-get opt :background))
18427 ;; Ensure full list is printed.
18428 print-length print-level)
18429 (when forbuffer
18430 ;; Get the colors from the face at point.
18431 (goto-char beg)
18432 (when (eq fg 'auto)
18433 (setq fg (face-attribute face :foreground nil 'default)))
18434 (when (eq bg 'auto)
18435 (setq bg (face-attribute face :background nil 'default)))
18436 (setq optnew (copy-sequence opt))
18437 (plist-put optnew :foreground fg)
18438 (plist-put optnew :background bg))
18439 (setq hash (sha1 (prin1-to-string
18440 (list org-format-latex-header
18441 org-latex-default-packages-alist
18442 org-latex-packages-alist
18443 org-format-latex-options
18444 forbuffer txt fg bg)))
18445 linkfile (format "%s_%s.png" prefix hash)
18446 movefile (format "%s_%s.png" absprefix hash)))
18447 (setq link (concat block "[[file:" linkfile "]]" block))
18448 (if msg (message msg cnt))
18449 (goto-char beg)
18450 (unless checkdir ; Ensure the directory exists.
18451 (setq checkdir t)
18452 (or (file-directory-p todir) (make-directory todir t)))
18453 (unless (file-exists-p movefile)
18454 (org-create-formula-image
18455 txt movefile optnew forbuffer processing-type))
18456 (if overlays
18457 (progn
18458 (mapc (lambda (o)
18459 (if (eq (overlay-get o 'org-overlay-type)
18460 'org-latex-overlay)
18461 (delete-overlay o)))
18462 (overlays-in beg end))
18463 (setq ov (make-overlay beg end))
18464 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18465 (if (featurep 'xemacs)
18466 (progn
18467 (overlay-put ov 'invisible t)
18468 (overlay-put
18469 ov 'end-glyph
18470 (make-glyph (vector 'png :file movefile))))
18471 (overlay-put
18472 ov 'display
18473 (list 'image :type 'png :file movefile :ascent 'center)))
18474 (push ov org-latex-fragment-image-overlays)
18475 (goto-char end))
18476 (delete-region beg end)
18477 (insert (org-add-props link
18478 (list 'org-latex-src
18479 (replace-regexp-in-string
18480 "\"" "" txt)
18481 'org-latex-src-embed-type
18482 (if block-type 'paragraph 'character))))))
18483 ((eq processing-type 'mathml)
18484 ;; Process to MathML
18485 (unless (save-match-data (org-format-latex-mathml-available-p))
18486 (user-error "LaTeX to MathML converter not configured"))
18487 (setq txt (match-string n)
18488 beg (match-beginning n) end (match-end n)
18489 cnt (1+ cnt))
18490 (if msg (message msg cnt))
18491 (goto-char beg)
18492 (delete-region beg end)
18493 (insert (org-format-latex-as-mathml
18494 txt block-type prefix dir)))
18496 (error "Unknown conversion type %s for LaTeX fragments"
18497 processing-type)))))))))
18499 (defun org-create-math-formula (latex-frag &optional mathml-file)
18500 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18501 Use `org-latex-to-mathml-convert-command'. If the conversion is
18502 sucessful, return the portion between \"<math...> </math>\"
18503 elements otherwise return nil. When MATHML-FILE is specified,
18504 write the results in to that file. When invoked as an
18505 interactive command, prompt for LATEX-FRAG, with initial value
18506 set to the current active region and echo the results for user
18507 inspection."
18508 (interactive (list (let ((frag (when (org-region-active-p)
18509 (buffer-substring-no-properties
18510 (region-beginning) (region-end)))))
18511 (read-string "LaTeX Fragment: " frag nil frag))))
18512 (unless latex-frag (error "Invalid LaTeX fragment"))
18513 (let* ((tmp-in-file (file-relative-name
18514 (make-temp-name (expand-file-name "ltxmathml-in"))))
18515 (ignore (write-region latex-frag nil tmp-in-file))
18516 (tmp-out-file (file-relative-name
18517 (make-temp-name (expand-file-name "ltxmathml-out"))))
18518 (cmd (format-spec
18519 org-latex-to-mathml-convert-command
18520 `((?j . ,(shell-quote-argument
18521 (expand-file-name org-latex-to-mathml-jar-file)))
18522 (?I . ,(shell-quote-argument tmp-in-file))
18523 (?o . ,(shell-quote-argument tmp-out-file)))))
18524 mathml shell-command-output)
18525 (when (org-called-interactively-p 'any)
18526 (unless (org-format-latex-mathml-available-p)
18527 (user-error "LaTeX to MathML converter not configured")))
18528 (message "Running %s" cmd)
18529 (setq shell-command-output (shell-command-to-string cmd))
18530 (setq mathml
18531 (when (file-readable-p tmp-out-file)
18532 (with-current-buffer (find-file-noselect tmp-out-file t)
18533 (goto-char (point-min))
18534 (when (re-search-forward
18535 (concat
18536 (regexp-quote
18537 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18538 "\\(.\\|\n\\)*"
18539 (regexp-quote "</math>")) nil t)
18540 (prog1 (match-string 0) (kill-buffer))))))
18541 (cond
18542 (mathml
18543 (setq mathml
18544 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18545 (when mathml-file
18546 (write-region mathml nil mathml-file))
18547 (when (org-called-interactively-p 'any)
18548 (message mathml)))
18549 ((message "LaTeX to MathML conversion failed")
18550 (message shell-command-output)))
18551 (delete-file tmp-in-file)
18552 (when (file-exists-p tmp-out-file)
18553 (delete-file tmp-out-file))
18554 mathml))
18556 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18557 prefix &optional dir)
18558 "Use `org-create-math-formula' but check local cache first."
18559 (let* ((absprefix (expand-file-name prefix dir))
18560 (print-length nil) (print-level nil)
18561 (formula-id (concat
18562 "formula-"
18563 (sha1
18564 (prin1-to-string
18565 (list latex-frag
18566 org-latex-to-mathml-convert-command)))))
18567 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18568 (formula-cache-dir (file-name-directory formula-cache)))
18570 (unless (file-directory-p formula-cache-dir)
18571 (make-directory formula-cache-dir t))
18573 (unless (file-exists-p formula-cache)
18574 (org-create-math-formula latex-frag formula-cache))
18576 (if (file-exists-p formula-cache)
18577 ;; Successful conversion. Return the link to MathML file.
18578 (org-add-props
18579 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18580 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18581 'org-latex-src-embed-type (if latex-frag-type
18582 'paragraph 'character)))
18583 ;; Failed conversion. Return the LaTeX fragment verbatim
18584 latex-frag)))
18586 (defun org-create-formula-image (string tofile options buffer &optional type)
18587 "Create an image from LaTeX source using dvipng or convert.
18588 This function calls either `org-create-formula-image-with-dvipng'
18589 or `org-create-formula-image-with-imagemagick' depending on the
18590 value of `org-latex-create-formula-image-program' or on the value
18591 of the optional TYPE variable.
18593 Note: ultimately these two function should be combined as they
18594 share a good deal of logic."
18595 (org-check-external-command
18596 "latex" "needed to convert LaTeX fragments to images")
18597 (funcall
18598 (case (or type org-latex-create-formula-image-program)
18599 ('dvipng
18600 (org-check-external-command
18601 "dvipng" "needed to convert LaTeX fragments to images")
18602 #'org-create-formula-image-with-dvipng)
18603 ('imagemagick
18604 (org-check-external-command
18605 "convert" "you need to install imagemagick")
18606 #'org-create-formula-image-with-imagemagick)
18607 (t (error
18608 "Invalid value of `org-latex-create-formula-image-program'")))
18609 string tofile options buffer))
18611 (declare-function org-export-get-backend "ox" (name))
18612 (declare-function org-export--get-global-options "ox" (&optional backend))
18613 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18614 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18615 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18616 (defun org-create-formula--latex-header ()
18617 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18618 (let ((info (org-combine-plists (org-export--get-global-options
18619 (org-export-get-backend 'latex))
18620 (org-export--get-inbuffer-options
18621 (org-export-get-backend 'latex)))))
18622 (org-latex-guess-babel-language
18623 (org-latex-guess-inputenc
18624 (org-splice-latex-header
18625 org-format-latex-header
18626 org-latex-default-packages-alist
18627 org-latex-packages-alist t
18628 (plist-get info :latex-header)))
18629 info)))
18631 ;; This function borrows from Ganesh Swami's latex2png.el
18632 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18633 "This calls dvipng."
18634 (require 'ox-latex)
18635 (let* ((tmpdir (if (featurep 'xemacs)
18636 (temp-directory)
18637 temporary-file-directory))
18638 (texfilebase (make-temp-name
18639 (expand-file-name "orgtex" tmpdir)))
18640 (texfile (concat texfilebase ".tex"))
18641 (dvifile (concat texfilebase ".dvi"))
18642 (pngfile (concat texfilebase ".png"))
18643 (fnh (if (featurep 'xemacs)
18644 (font-height (face-font 'default))
18645 (face-attribute 'default :height nil)))
18646 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18647 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18648 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18649 "Black"))
18650 (bg (or (plist-get options (if buffer :background :html-background))
18651 "Transparent")))
18652 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18653 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18654 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18655 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18656 (let ((latex-header (org-create-formula--latex-header)))
18657 (with-temp-file texfile
18658 (insert latex-header)
18659 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18660 (let ((dir default-directory))
18661 (condition-case nil
18662 (progn
18663 (cd tmpdir)
18664 (call-process "latex" nil nil nil texfile))
18665 (error nil))
18666 (cd dir))
18667 (if (not (file-exists-p dvifile))
18668 (progn (message "Failed to create dvi file from %s" texfile) nil)
18669 (condition-case nil
18670 (if (featurep 'xemacs)
18671 (call-process "dvipng" nil nil nil
18672 "-fg" fg "-bg" bg
18673 "-T" "tight"
18674 "-o" pngfile
18675 dvifile)
18676 (call-process "dvipng" nil nil nil
18677 "-fg" fg "-bg" bg
18678 "-D" dpi
18679 ;;"-x" scale "-y" scale
18680 "-T" "tight"
18681 "-o" pngfile
18682 dvifile))
18683 (error nil))
18684 (if (not (file-exists-p pngfile))
18685 (if org-format-latex-signal-error
18686 (error "Failed to create png file from %s" texfile)
18687 (message "Failed to create png file from %s" texfile)
18688 nil)
18689 ;; Use the requested file name and clean up
18690 (copy-file pngfile tofile 'replace)
18691 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18692 (if (file-exists-p (concat texfilebase e))
18693 (delete-file (concat texfilebase e))))
18694 pngfile))))
18696 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18697 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18698 "This calls convert, which is included into imagemagick."
18699 (require 'ox-latex)
18700 (let* ((tmpdir (if (featurep 'xemacs)
18701 (temp-directory)
18702 temporary-file-directory))
18703 (texfilebase (make-temp-name
18704 (expand-file-name "orgtex" tmpdir)))
18705 (texfile (concat texfilebase ".tex"))
18706 (pdffile (concat texfilebase ".pdf"))
18707 (pngfile (concat texfilebase ".png"))
18708 (fnh (if (featurep 'xemacs)
18709 (font-height (face-font 'default))
18710 (face-attribute 'default :height nil)))
18711 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18712 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18713 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18714 "black"))
18715 (bg (or (plist-get options (if buffer :background :html-background))
18716 "white")))
18717 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18718 (setq fg (org-latex-color-format fg)))
18719 (if (eq bg 'default) (setq bg (org-latex-color :background))
18720 (setq bg (org-latex-color-format
18721 (if (string= bg "Transparent") "white" bg))))
18722 (let ((latex-header (org-create-formula--latex-header)))
18723 (with-temp-file texfile
18724 (insert latex-header)
18725 (insert "\n\\begin{document}\n"
18726 "\\definecolor{fg}{rgb}{" fg "}\n"
18727 "\\definecolor{bg}{rgb}{" bg "}\n"
18728 "\n\\pagecolor{bg}\n"
18729 "\n{\\color{fg}\n"
18730 string
18731 "\n}\n"
18732 "\n\\end{document}\n")))
18733 (org-latex-compile texfile t)
18734 (if (not (file-exists-p pdffile))
18735 (progn (message "Failed to create pdf file from %s" texfile) nil)
18736 (condition-case nil
18737 (if (featurep 'xemacs)
18738 (call-process "convert" nil nil nil
18739 "-density" "96"
18740 "-trim"
18741 "-antialias"
18742 pdffile
18743 "-quality" "100"
18744 ;; "-sharpen" "0x1.0"
18745 pngfile)
18746 (call-process "convert" nil nil nil
18747 "-density" dpi
18748 "-trim"
18749 "-antialias"
18750 pdffile
18751 "-quality" "100"
18752 ;; "-sharpen" "0x1.0"
18753 pngfile))
18754 (error nil))
18755 (if (not (file-exists-p pngfile))
18756 (if org-format-latex-signal-error
18757 (error "Failed to create png file from %s" texfile)
18758 (message "Failed to create png file from %s" texfile)
18759 nil)
18760 ;; Use the requested file name and clean up
18761 (copy-file pngfile tofile 'replace)
18762 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18763 (if (file-exists-p (concat texfilebase e))
18764 (delete-file (concat texfilebase e))))
18765 pngfile))))
18767 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18768 "Fill a LaTeX header template TPL.
18769 In the template, the following place holders will be recognized:
18771 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18772 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18773 [PACKAGES] \\usepackage statements for PKG
18774 [NO-PACKAGES] do not include PKG
18775 [EXTRA] the string EXTRA
18776 [NO-EXTRA] do not include EXTRA
18778 For backward compatibility, if both the positive and the negative place
18779 holder is missing, the positive one (without the \"NO-\") will be
18780 assumed to be present at the end of the template.
18781 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18782 EXTRA is a string.
18783 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18784 (let (rpl (end ""))
18785 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18786 (setq rpl (if (or (match-end 1) (not def-pkg))
18787 "" (org-latex-packages-to-string def-pkg snippets-p t))
18788 tpl (replace-match rpl t t tpl))
18789 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18791 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18792 (setq rpl (if (or (match-end 1) (not pkg))
18793 "" (org-latex-packages-to-string pkg snippets-p t))
18794 tpl (replace-match rpl t t tpl))
18795 (if pkg (setq end
18796 (concat end "\n"
18797 (org-latex-packages-to-string pkg snippets-p)))))
18799 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18800 (setq rpl (if (or (match-end 1) (not extra))
18801 "" (concat extra "\n"))
18802 tpl (replace-match rpl t t tpl))
18803 (if (and extra (string-match "\\S-" extra))
18804 (setq end (concat end "\n" extra))))
18806 (if (string-match "\\S-" end)
18807 (concat tpl "\n" end)
18808 tpl)))
18810 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18811 "Turn an alist of packages into a string with the \\usepackage macros."
18812 (setq pkg (mapconcat (lambda(p)
18813 (cond
18814 ((stringp p) p)
18815 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18816 (format "%% Package %s omitted" (cadr p)))
18817 ((equal "" (car p))
18818 (format "\\usepackage{%s}" (cadr p)))
18820 (format "\\usepackage[%s]{%s}"
18821 (car p) (cadr p)))))
18823 "\n"))
18824 (if newline (concat pkg "\n") pkg))
18826 (defun org-dvipng-color (attr)
18827 "Return a RGB color specification for dvipng."
18828 (apply 'format "rgb %s %s %s"
18829 (mapcar 'org-normalize-color
18830 (if (featurep 'xemacs)
18831 (color-rgb-components
18832 (face-property 'default
18833 (cond ((eq attr :foreground) 'foreground)
18834 ((eq attr :background) 'background))))
18835 (color-values (face-attribute 'default attr nil))))))
18837 (defun org-dvipng-color-format (color-name)
18838 "Convert COLOR-NAME to a RGB color value for dvipng."
18839 (apply 'format "rgb %s %s %s"
18840 (mapcar 'org-normalize-color
18841 (color-values color-name))))
18843 (defun org-latex-color (attr)
18844 "Return a RGB color for the LaTeX color package."
18845 (apply 'format "%s,%s,%s"
18846 (mapcar 'org-normalize-color
18847 (if (featurep 'xemacs)
18848 (color-rgb-components
18849 (face-property 'default
18850 (cond ((eq attr :foreground) 'foreground)
18851 ((eq attr :background) 'background))))
18852 (color-values (face-attribute 'default attr nil))))))
18854 (defun org-latex-color-format (color-name)
18855 "Convert COLOR-NAME to a RGB color value."
18856 (apply 'format "%s,%s,%s"
18857 (mapcar 'org-normalize-color
18858 (color-values color-name))))
18860 (defun org-normalize-color (value)
18861 "Return string to be used as color value for an RGB component."
18862 (format "%g" (/ value 65535.0)))
18866 ;; Image display
18868 (defvar org-inline-image-overlays nil)
18869 (make-variable-buffer-local 'org-inline-image-overlays)
18871 (defun org-toggle-inline-images (&optional include-linked)
18872 "Toggle the display of inline images.
18873 INCLUDE-LINKED is passed to `org-display-inline-images'."
18874 (interactive "P")
18875 (if org-inline-image-overlays
18876 (progn
18877 (org-remove-inline-images)
18878 (message "Inline image display turned off"))
18879 (org-display-inline-images include-linked)
18880 (if (and (org-called-interactively-p)
18881 org-inline-image-overlays)
18882 (message "%d images displayed inline"
18883 (length org-inline-image-overlays))
18884 (message "No images to display inline"))))
18886 (defun org-redisplay-inline-images ()
18887 "Refresh the display of inline images."
18888 (interactive)
18889 (if (not org-inline-image-overlays)
18890 (org-toggle-inline-images)
18891 (org-toggle-inline-images)
18892 (org-toggle-inline-images)))
18894 (defun org-display-inline-images (&optional include-linked refresh beg end)
18895 "Display inline images.
18897 An inline image is a link which follows either of these
18898 conventions:
18900 1. Its path is a file with an extension matching return value
18901 from `image-file-name-regexp' and it has no contents.
18903 2. Its description consists in a single link of the previous
18904 type.
18906 When optional argument INCLUDE-LINKED is non-nil, also links with
18907 a text description part will be inlined. This can be nice for
18908 a quick look at those images, but it does not reflect what
18909 exported files will look like.
18911 When optional argument REFRESH is non-nil, refresh existing
18912 images between BEG and END. This will create new image displays
18913 only if necessary. BEG and END default to the buffer
18914 boundaries."
18915 (interactive "P")
18916 (when (display-graphic-p)
18917 (unless refresh
18918 (org-remove-inline-images)
18919 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18920 (org-with-wide-buffer
18921 (goto-char (or beg (point-min)))
18922 (let ((case-fold-search t)
18923 (file-extension-re (org-image-file-name-regexp)))
18924 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
18925 (let ((link (save-match-data (org-element-context))))
18926 ;; Check if we're at an inline image.
18927 (when (and (equal (org-element-property :type link) "file")
18928 (or include-linked
18929 (not (org-element-property :contents-begin link)))
18930 (let ((parent (org-element-property :parent link)))
18931 (or (not (eq (org-element-type parent) 'link))
18932 (not (cdr (org-element-contents parent)))))
18933 (org-string-match-p file-extension-re
18934 (org-element-property :path link)))
18935 (let ((file (expand-file-name (org-element-property :path link))))
18936 (when (file-exists-p file)
18937 (let ((width
18938 ;; Apply `org-image-actual-width' specifications.
18939 (cond
18940 ((not (image-type-available-p 'imagemagick)) nil)
18941 ((eq org-image-actual-width t) nil)
18942 ((listp org-image-actual-width)
18944 ;; First try to find a width among
18945 ;; attributes associated to the paragraph
18946 ;; containing link.
18947 (let ((paragraph
18948 (let ((e link))
18949 (while (and (setq e (org-element-property
18950 :parent e))
18951 (not (eq (org-element-type e)
18952 'paragraph))))
18953 e)))
18954 (when paragraph
18955 (save-excursion
18956 (goto-char (org-element-property :begin paragraph))
18957 (when (save-match-data
18958 (re-search-forward
18959 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18960 (org-element-property
18961 :post-affiliated paragraph)
18963 (string-to-number (match-string 1))))))
18964 ;; Otherwise, fall-back to provided number.
18965 (car org-image-actual-width)))
18966 ((numberp org-image-actual-width)
18967 org-image-actual-width)))
18968 (old (get-char-property-and-overlay
18969 (org-element-property :begin link)
18970 'org-image-overlay)))
18971 (if (and (car-safe old) refresh)
18972 (image-refresh (overlay-get (cdr old) 'display))
18973 (let ((image (save-match-data
18974 (create-image file
18975 (and width 'imagemagick)
18977 :width width))))
18978 (when image
18979 (let* ((link
18980 ;; If inline image is the description
18981 ;; of another link, be sure to
18982 ;; consider the latter as the one to
18983 ;; apply the overlay on.
18984 (let ((parent
18985 (org-element-property :parent link)))
18986 (if (eq (org-element-type parent) 'link)
18987 parent
18988 link)))
18989 (ov (make-overlay
18990 (org-element-property :begin link)
18991 (progn
18992 (goto-char
18993 (org-element-property :end link))
18994 (skip-chars-backward " \t")
18995 (point)))))
18996 (overlay-put ov 'display image)
18997 (overlay-put ov 'face 'default)
18998 (overlay-put ov 'org-image-overlay t)
18999 (overlay-put
19000 ov 'modification-hooks
19001 (list 'org-display-inline-remove-overlay))
19002 (push ov org-inline-image-overlays)))))))))))))))
19004 (define-obsolete-function-alias
19005 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19007 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19008 "Remove inline-display overlay if a corresponding region is modified."
19009 (let ((inhibit-modification-hooks t))
19010 (when (and ov after)
19011 (delete ov org-inline-image-overlays)
19012 (delete-overlay ov))))
19014 (defun org-remove-inline-images ()
19015 "Remove inline display of images."
19016 (interactive)
19017 (mapc 'delete-overlay org-inline-image-overlays)
19018 (setq org-inline-image-overlays nil))
19020 ;;;; Key bindings
19022 ;; Outline functions from `outline-mode-prefix-map'
19023 ;; that can be remapped in Org:
19024 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19025 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19026 (define-key org-mode-map [remap outline-forward-same-level]
19027 'org-forward-heading-same-level)
19028 (define-key org-mode-map [remap outline-backward-same-level]
19029 'org-backward-heading-same-level)
19030 (define-key org-mode-map [remap show-branches]
19031 'org-kill-note-or-show-branches)
19032 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19033 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19034 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19036 ;; Outline functions from `outline-mode-prefix-map' that can not
19037 ;; be remapped in Org:
19039 ;; - the column "key binding" shows whether the Outline function is still
19040 ;; available in Org mode on the same key that it has been bound to in
19041 ;; Outline mode:
19042 ;; - "overridden": key used for a different functionality in Org mode
19043 ;; - else: key still bound to the same Outline function in Org mode
19045 ;; | Outline function | key binding | Org replacement |
19046 ;; |------------------------------------+-------------+-----------------------|
19047 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19048 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19049 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19050 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19051 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19052 ;; | `show-entry' | overridden | no replacement |
19053 ;; | `show-children' | `C-c C-i' | visibility cycling |
19054 ;; | `show-branches' | `C-c C-k' | still same function |
19055 ;; | `show-subtree' | overridden | visibility cycling |
19056 ;; | `show-all' | overridden | no replacement |
19057 ;; | `hide-subtree' | overridden | visibility cycling |
19058 ;; | `hide-body' | overridden | no replacement |
19059 ;; | `hide-entry' | overridden | visibility cycling |
19060 ;; | `hide-leaves' | overridden | no replacement |
19061 ;; | `hide-sublevels' | overridden | no replacement |
19062 ;; | `hide-other' | overridden | no replacement |
19064 ;; Make `C-c C-x' a prefix key
19065 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19067 ;; TAB key with modifiers
19068 (org-defkey org-mode-map "\C-i" 'org-cycle)
19069 (org-defkey org-mode-map [(tab)] 'org-cycle)
19070 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19071 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19072 ;; The following line is necessary under Suse GNU/Linux
19073 (unless (featurep 'xemacs)
19074 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19075 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19076 (define-key org-mode-map [backtab] 'org-shifttab)
19078 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19079 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19080 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19082 ;; Cursor keys with modifiers
19083 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19084 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19085 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19086 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19088 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19089 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19090 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19091 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19093 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19094 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19095 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19096 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19098 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19099 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19100 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19101 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19103 ;; Babel keys
19104 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19105 (mapc (lambda (pair)
19106 (define-key org-babel-map (car pair) (cdr pair)))
19107 org-babel-key-bindings)
19109 ;;; Extra keys for tty access.
19110 ;; We only set them when really needed because otherwise the
19111 ;; menus don't show the simple keys
19113 (when (or org-use-extra-keys
19114 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19115 (not window-system))
19116 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19117 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19118 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19119 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19120 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19121 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19122 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19123 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19124 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19125 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19126 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19127 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19128 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19129 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19130 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19131 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19132 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19133 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19134 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19135 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19136 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19137 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19138 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19139 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19140 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19141 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19142 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19143 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19145 ;; All the other keys
19147 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19148 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19149 (if (boundp 'narrow-map)
19150 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19151 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19152 (if (boundp 'narrow-map)
19153 (org-defkey narrow-map "b" 'org-narrow-to-block)
19154 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19155 (if (boundp 'narrow-map)
19156 (org-defkey narrow-map "e" 'org-narrow-to-element)
19157 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19158 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19159 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19160 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19161 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19162 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19163 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19164 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19165 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19166 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19167 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19168 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19169 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19170 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19171 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19172 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19173 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19174 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19175 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19176 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19177 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19178 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19179 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19180 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19181 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19182 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19183 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19184 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19185 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19186 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19187 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19188 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19189 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19190 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19191 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19192 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19193 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19194 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19195 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19196 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19197 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19198 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19199 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19200 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19201 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19202 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19203 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19204 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19205 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19206 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19207 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19208 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19209 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19210 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19211 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19212 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19213 (org-defkey org-mode-map "\C-c^" 'org-sort)
19214 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19215 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19216 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19217 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19218 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19219 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19220 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19221 (org-defkey org-mode-map "\C-m" 'org-return)
19222 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19223 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19224 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19225 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19226 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19227 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19228 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19229 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19230 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19231 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19232 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19233 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19234 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19235 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19236 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19237 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19238 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19239 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19240 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19241 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19242 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19243 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19244 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19246 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19247 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19248 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19250 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19251 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19252 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19253 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19254 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19255 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19256 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19257 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19258 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19259 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19260 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19261 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19262 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19263 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19264 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19265 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19266 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19267 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19268 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19269 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19270 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19271 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19272 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19274 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19275 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19276 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19277 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19278 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19280 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19282 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19284 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19285 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19287 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19290 (when (featurep 'xemacs)
19291 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19294 (defconst org-speed-commands-default
19296 ("Outline Navigation")
19297 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19298 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19299 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19300 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19301 ("F" . org-next-block)
19302 ("B" . org-previous-block)
19303 ("u" . (org-speed-move-safe 'outline-up-heading))
19304 ("j" . org-goto)
19305 ("g" . (org-refile t))
19306 ("Outline Visibility")
19307 ("c" . org-cycle)
19308 ("C" . org-shifttab)
19309 (" " . org-display-outline-path)
19310 ("s" . org-narrow-to-subtree)
19311 ("=" . org-columns)
19312 ("Outline Structure Editing")
19313 ("U" . org-shiftmetaup)
19314 ("D" . org-shiftmetadown)
19315 ("r" . org-metaright)
19316 ("l" . org-metaleft)
19317 ("R" . org-shiftmetaright)
19318 ("L" . org-shiftmetaleft)
19319 ("i" . (progn (forward-char 1) (call-interactively
19320 'org-insert-heading-respect-content)))
19321 ("^" . org-sort)
19322 ("w" . org-refile)
19323 ("a" . org-archive-subtree-default-with-confirmation)
19324 ("@" . org-mark-subtree)
19325 ("#" . org-toggle-comment)
19326 ("Clock Commands")
19327 ("I" . org-clock-in)
19328 ("O" . org-clock-out)
19329 ("Meta Data Editing")
19330 ("t" . org-todo)
19331 ("," . (org-priority))
19332 ("0" . (org-priority ?\ ))
19333 ("1" . (org-priority ?A))
19334 ("2" . (org-priority ?B))
19335 ("3" . (org-priority ?C))
19336 (":" . org-set-tags-command)
19337 ("e" . org-set-effort)
19338 ("E" . org-inc-effort)
19339 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19340 (org-entry-put (point) "APPT_WARNTIME" m)))
19341 ("Agenda Views etc")
19342 ("v" . org-agenda)
19343 ("/" . org-sparse-tree)
19344 ("Misc")
19345 ("o" . org-open-at-point)
19346 ("?" . org-speed-command-help)
19347 ("<" . (org-agenda-set-restriction-lock 'subtree))
19348 (">" . (org-agenda-remove-restriction-lock))
19350 "The default speed commands.")
19352 (defun org-print-speed-command (e)
19353 (if (> (length (car e)) 1)
19354 (progn
19355 (princ "\n")
19356 (princ (car e))
19357 (princ "\n")
19358 (princ (make-string (length (car e)) ?-))
19359 (princ "\n"))
19360 (princ (car e))
19361 (princ " ")
19362 (if (symbolp (cdr e))
19363 (princ (symbol-name (cdr e)))
19364 (prin1 (cdr e)))
19365 (princ "\n")))
19367 (defun org-speed-command-help ()
19368 "Show the available speed commands."
19369 (interactive)
19370 (if (not org-use-speed-commands)
19371 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19372 (with-output-to-temp-buffer "*Help*"
19373 (princ "User-defined Speed commands\n===========================\n")
19374 (mapc 'org-print-speed-command org-speed-commands-user)
19375 (princ "\n")
19376 (princ "Built-in Speed commands\n=======================\n")
19377 (mapc 'org-print-speed-command org-speed-commands-default))
19378 (with-current-buffer "*Help*"
19379 (setq truncate-lines t))))
19381 (defun org-speed-move-safe (cmd)
19382 "Execute CMD, but make sure that the cursor always ends up in a headline.
19383 If not, return to the original position and throw an error."
19384 (interactive)
19385 (let ((pos (point)))
19386 (call-interactively cmd)
19387 (unless (and (bolp) (org-at-heading-p))
19388 (goto-char pos)
19389 (error "Boundary reached while executing %s" cmd))))
19391 (defvar org-self-insert-command-undo-counter 0)
19393 (defvar org-table-auto-blank-field) ; defined in org-table.el
19394 (defvar org-speed-command nil)
19396 (define-obsolete-function-alias
19397 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19399 (defun org-speed-command-activate (keys)
19400 "Hook for activating single-letter speed commands.
19401 `org-speed-commands-default' specifies a minimal command set.
19402 Use `org-speed-commands-user' for further customization."
19403 (when (or (and (bolp) (looking-at org-outline-regexp))
19404 (and (functionp org-use-speed-commands)
19405 (funcall org-use-speed-commands)))
19406 (cdr (assoc keys (append org-speed-commands-user
19407 org-speed-commands-default)))))
19409 (define-obsolete-function-alias
19410 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19412 (defun org-babel-speed-command-activate (keys)
19413 "Hook for activating single-letter code block commands."
19414 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19415 (cdr (assoc keys org-babel-key-bindings))))
19417 (defcustom org-speed-command-hook
19418 '(org-speed-command-default-hook org-babel-speed-command-hook)
19419 "Hook for activating speed commands at strategic locations.
19420 Hook functions are called in sequence until a valid handler is
19421 found.
19423 Each hook takes a single argument, a user-pressed command key
19424 which is also a `self-insert-command' from the global map.
19426 Within the hook, examine the cursor position and the command key
19427 and return nil or a valid handler as appropriate. Handler could
19428 be one of an interactive command, a function, or a form.
19430 Set `org-use-speed-commands' to non-nil value to enable this
19431 hook. The default setting is `org-speed-command-activate'."
19432 :group 'org-structure
19433 :version "24.1"
19434 :type 'hook)
19436 (defun org-self-insert-command (N)
19437 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19438 If the cursor is in a table looking at whitespace, the whitespace is
19439 overwritten, and the table is not marked as requiring realignment."
19440 (interactive "p")
19441 (org-check-before-invisible-edit 'insert)
19442 (cond
19443 ((and org-use-speed-commands
19444 (setq org-speed-command
19445 (run-hook-with-args-until-success
19446 'org-speed-command-hook (this-command-keys))))
19447 (cond
19448 ((commandp org-speed-command)
19449 (setq this-command org-speed-command)
19450 (call-interactively org-speed-command))
19451 ((functionp org-speed-command)
19452 (funcall org-speed-command))
19453 ((and org-speed-command (listp org-speed-command))
19454 (eval org-speed-command))
19455 (t (let (org-use-speed-commands)
19456 (call-interactively 'org-self-insert-command)))))
19457 ((and
19458 (org-table-p)
19459 (progn
19460 ;; check if we blank the field, and if that triggers align
19461 (and (featurep 'org-table) org-table-auto-blank-field
19462 (member last-command
19463 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19464 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19465 ;; got extra space, this field does not determine column width
19466 (let (org-table-may-need-update) (org-table-blank-field))
19467 ;; no extra space, this field may determine column width
19468 (org-table-blank-field)))
19470 (eq N 1)
19471 (looking-at "[^|\n]* |"))
19472 (let (org-table-may-need-update)
19473 (goto-char (1- (match-end 0)))
19474 (backward-delete-char 1)
19475 (goto-char (match-beginning 0))
19476 (self-insert-command N)))
19478 (setq org-table-may-need-update t)
19479 (self-insert-command N)
19480 (org-fix-tags-on-the-fly)
19481 (if org-self-insert-cluster-for-undo
19482 (if (not (eq last-command 'org-self-insert-command))
19483 (setq org-self-insert-command-undo-counter 1)
19484 (if (>= org-self-insert-command-undo-counter 20)
19485 (setq org-self-insert-command-undo-counter 1)
19486 (and (> org-self-insert-command-undo-counter 0)
19487 buffer-undo-list (listp buffer-undo-list)
19488 (not (cadr buffer-undo-list)) ; remove nil entry
19489 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19490 (setq org-self-insert-command-undo-counter
19491 (1+ org-self-insert-command-undo-counter))))))))
19493 (defun org-check-before-invisible-edit (kind)
19494 "Check is editing if kind KIND would be dangerous with invisible text around.
19495 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19496 ;; First, try to get out of here as quickly as possible, to reduce overhead
19497 (if (and org-catch-invisible-edits
19498 (or (not (boundp 'visible-mode)) (not visible-mode))
19499 (or (get-char-property (point) 'invisible)
19500 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19501 ;; OK, we need to take a closer look
19502 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19503 (invisible-before-point (if (bobp) nil (get-char-property
19504 (1- (point)) 'invisible)))
19505 (border-and-ok-direction
19507 ;; Check if we are acting predictably before invisible text
19508 (and invisible-at-point (not invisible-before-point)
19509 (memq kind '(insert delete-backward)))
19510 ;; Check if we are acting predictably after invisible text
19511 ;; This works not well, and I have turned it off. It seems
19512 ;; better to always show and stop after invisible text.
19513 ;; (and (not invisible-at-point) invisible-before-point
19514 ;; (memq kind '(insert delete)))
19516 (when (or (memq invisible-at-point '(outline org-hide-block t))
19517 (memq invisible-before-point '(outline org-hide-block t)))
19518 (if (eq org-catch-invisible-edits 'error)
19519 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19520 (if (and org-custom-properties-overlays
19521 (y-or-n-p "Display invisible properties in this buffer? "))
19522 (org-toggle-custom-properties-visibility)
19523 ;; Make the area visible
19524 (save-excursion
19525 (if invisible-before-point
19526 (goto-char (previous-single-char-property-change
19527 (point) 'invisible)))
19528 (org-cycle))
19529 (cond
19530 ((eq org-catch-invisible-edits 'show)
19531 ;; That's it, we do the edit after showing
19532 (message
19533 "Unfolding invisible region around point before editing")
19534 (sit-for 1))
19535 ((and (eq org-catch-invisible-edits 'smart)
19536 border-and-ok-direction)
19537 (message "Unfolding invisible region around point before editing"))
19539 ;; Don't do the edit, make the user repeat it in full visibility
19540 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19542 (defun org-fix-tags-on-the-fly ()
19543 (when (and (equal (char-after (point-at-bol)) ?*)
19544 (org-at-heading-p))
19545 (org-align-tags-here org-tags-column)))
19547 (defun org-delete-backward-char (N)
19548 "Like `delete-backward-char', insert whitespace at field end in tables.
19549 When deleting backwards, in tables this function will insert whitespace in
19550 front of the next \"|\" separator, to keep the table aligned. The table will
19551 still be marked for re-alignment if the field did fill the entire column,
19552 because, in this case the deletion might narrow the column."
19553 (interactive "p")
19554 (save-match-data
19555 (org-check-before-invisible-edit 'delete-backward)
19556 (if (and (org-table-p)
19557 (eq N 1)
19558 (string-match "|" (buffer-substring (point-at-bol) (point)))
19559 (looking-at ".*?|"))
19560 (let ((pos (point))
19561 (noalign (looking-at "[^|\n\r]* |"))
19562 (c org-table-may-need-update))
19563 (backward-delete-char N)
19564 (if (not overwrite-mode)
19565 (progn
19566 (skip-chars-forward "^|")
19567 (insert " ")
19568 (goto-char (1- pos))))
19569 ;; noalign: if there were two spaces at the end, this field
19570 ;; does not determine the width of the column.
19571 (if noalign (setq org-table-may-need-update c)))
19572 (backward-delete-char N)
19573 (org-fix-tags-on-the-fly))))
19575 (defun org-delete-char (N)
19576 "Like `delete-char', but insert whitespace at field end in tables.
19577 When deleting characters, in tables this function will insert whitespace in
19578 front of the next \"|\" separator, to keep the table aligned. The table will
19579 still be marked for re-alignment if the field did fill the entire column,
19580 because, in this case the deletion might narrow the column."
19581 (interactive "p")
19582 (save-match-data
19583 (org-check-before-invisible-edit 'delete)
19584 (if (and (org-table-p)
19585 (not (bolp))
19586 (not (= (char-after) ?|))
19587 (eq N 1))
19588 (if (looking-at ".*?|")
19589 (let ((pos (point))
19590 (noalign (looking-at "[^|\n\r]* |"))
19591 (c org-table-may-need-update))
19592 (replace-match
19593 (concat (substring (match-string 0) 1 -1) " |") nil t)
19594 (goto-char pos)
19595 ;; noalign: if there were two spaces at the end, this field
19596 ;; does not determine the width of the column.
19597 (if noalign (setq org-table-may-need-update c)))
19598 (delete-char N))
19599 (delete-char N)
19600 (org-fix-tags-on-the-fly))))
19602 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19603 (put 'org-self-insert-command 'delete-selection
19604 (lambda ()
19605 (not (run-hook-with-args-until-success
19606 'self-insert-uses-region-functions))))
19607 (put 'orgtbl-self-insert-command 'delete-selection
19608 (lambda ()
19609 (not (run-hook-with-args-until-success
19610 'self-insert-uses-region-functions))))
19611 (put 'org-delete-char 'delete-selection 'supersede)
19612 (put 'org-delete-backward-char 'delete-selection 'supersede)
19613 (put 'org-yank 'delete-selection 'yank)
19615 ;; Make `flyspell-mode' delay after some commands
19616 (put 'org-self-insert-command 'flyspell-delayed t)
19617 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19618 (put 'org-delete-char 'flyspell-delayed t)
19619 (put 'org-delete-backward-char 'flyspell-delayed t)
19621 ;; Make pabbrev-mode expand after org-mode commands
19622 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19623 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19625 (defun org-remap (map &rest commands)
19626 "In MAP, remap the functions given in COMMANDS.
19627 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19628 (let (new old)
19629 (while commands
19630 (setq old (pop commands) new (pop commands))
19631 (if (fboundp 'command-remapping)
19632 (org-defkey map (vector 'remap old) new)
19633 (substitute-key-definition old new map global-map)))))
19635 (defun org-transpose-words ()
19636 "Transpose words for Org.
19637 This uses the `org-mode-transpose-word-syntax-table' syntax
19638 table, which interprets characters in `org-emphasis-alist' as
19639 word constituents."
19640 (interactive)
19641 (with-syntax-table org-mode-transpose-word-syntax-table
19642 (call-interactively 'transpose-words)))
19643 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19645 (when (eq org-enable-table-editor 'optimized)
19646 ;; If the user wants maximum table support, we need to hijack
19647 ;; some standard editing functions
19648 (org-remap org-mode-map
19649 'self-insert-command 'org-self-insert-command
19650 'delete-char 'org-delete-char
19651 'delete-backward-char 'org-delete-backward-char)
19652 (org-defkey org-mode-map "|" 'org-force-self-insert))
19654 (defvar org-ctrl-c-ctrl-c-hook nil
19655 "Hook for functions attaching themselves to `C-c C-c'.
19657 This can be used to add additional functionality to the C-c C-c
19658 key which executes context-dependent commands. This hook is run
19659 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19660 run after the last test.
19662 Each function will be called with no arguments. The function
19663 must check if the context is appropriate for it to act. If yes,
19664 it should do its thing and then return a non-nil value. If the
19665 context is wrong, just do nothing and return nil.")
19667 (defvar org-ctrl-c-ctrl-c-final-hook nil
19668 "Hook for functions attaching themselves to `C-c C-c'.
19670 This can be used to add additional functionality to the C-c C-c
19671 key which executes context-dependent commands. This hook is run
19672 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19673 before the first test.
19675 Each function will be called with no arguments. The function
19676 must check if the context is appropriate for it to act. If yes,
19677 it should do its thing and then return a non-nil value. If the
19678 context is wrong, just do nothing and return nil.")
19680 (defvar org-tab-first-hook nil
19681 "Hook for functions to attach themselves to TAB.
19682 See `org-ctrl-c-ctrl-c-hook' for more information.
19683 This hook runs as the first action when TAB is pressed, even before
19684 `org-cycle' messes around with the `outline-regexp' to cater for
19685 inline tasks and plain list item folding.
19686 If any function in this hook returns t, any other actions that
19687 would have been caused by TAB (such as table field motion or visibility
19688 cycling) will not occur.")
19690 (defvar org-tab-after-check-for-table-hook nil
19691 "Hook for functions to attach themselves to TAB.
19692 See `org-ctrl-c-ctrl-c-hook' for more information.
19693 This hook runs after it has been established that the cursor is not in a
19694 table, but before checking if the cursor is in a headline or if global cycling
19695 should be done.
19696 If any function in this hook returns t, not other actions like visibility
19697 cycling will be done.")
19699 (defvar org-tab-after-check-for-cycling-hook nil
19700 "Hook for functions to attach themselves to TAB.
19701 See `org-ctrl-c-ctrl-c-hook' for more information.
19702 This hook runs after it has been established that not table field motion and
19703 not visibility should be done because of current context. This is probably
19704 the place where a package like yasnippets can hook in.")
19706 (defvar org-tab-before-tab-emulation-hook nil
19707 "Hook for functions to attach themselves to TAB.
19708 See `org-ctrl-c-ctrl-c-hook' for more information.
19709 This hook runs after every other options for TAB have been exhausted, but
19710 before indentation and \t insertion takes place.")
19712 (defvar org-metaleft-hook nil
19713 "Hook for functions attaching themselves to `M-left'.
19714 See `org-ctrl-c-ctrl-c-hook' for more information.")
19715 (defvar org-metaright-hook nil
19716 "Hook for functions attaching themselves to `M-right'.
19717 See `org-ctrl-c-ctrl-c-hook' for more information.")
19718 (defvar org-metaup-hook nil
19719 "Hook for functions attaching themselves to `M-up'.
19720 See `org-ctrl-c-ctrl-c-hook' for more information.")
19721 (defvar org-metadown-hook nil
19722 "Hook for functions attaching themselves to `M-down'.
19723 See `org-ctrl-c-ctrl-c-hook' for more information.")
19724 (defvar org-shiftmetaleft-hook nil
19725 "Hook for functions attaching themselves to `M-S-left'.
19726 See `org-ctrl-c-ctrl-c-hook' for more information.")
19727 (defvar org-shiftmetaright-hook nil
19728 "Hook for functions attaching themselves to `M-S-right'.
19729 See `org-ctrl-c-ctrl-c-hook' for more information.")
19730 (defvar org-shiftmetaup-hook nil
19731 "Hook for functions attaching themselves to `M-S-up'.
19732 See `org-ctrl-c-ctrl-c-hook' for more information.")
19733 (defvar org-shiftmetadown-hook nil
19734 "Hook for functions attaching themselves to `M-S-down'.
19735 See `org-ctrl-c-ctrl-c-hook' for more information.")
19736 (defvar org-metareturn-hook nil
19737 "Hook for functions attaching themselves to `M-RET'.
19738 See `org-ctrl-c-ctrl-c-hook' for more information.")
19739 (defvar org-shiftup-hook nil
19740 "Hook for functions attaching themselves to `S-up'.
19741 See `org-ctrl-c-ctrl-c-hook' for more information.")
19742 (defvar org-shiftup-final-hook nil
19743 "Hook for functions attaching themselves to `S-up'.
19744 This one runs after all other options except shift-select have been excluded.
19745 See `org-ctrl-c-ctrl-c-hook' for more information.")
19746 (defvar org-shiftdown-hook nil
19747 "Hook for functions attaching themselves to `S-down'.
19748 See `org-ctrl-c-ctrl-c-hook' for more information.")
19749 (defvar org-shiftdown-final-hook nil
19750 "Hook for functions attaching themselves to `S-down'.
19751 This one runs after all other options except shift-select have been excluded.
19752 See `org-ctrl-c-ctrl-c-hook' for more information.")
19753 (defvar org-shiftleft-hook nil
19754 "Hook for functions attaching themselves to `S-left'.
19755 See `org-ctrl-c-ctrl-c-hook' for more information.")
19756 (defvar org-shiftleft-final-hook nil
19757 "Hook for functions attaching themselves to `S-left'.
19758 This one runs after all other options except shift-select have been excluded.
19759 See `org-ctrl-c-ctrl-c-hook' for more information.")
19760 (defvar org-shiftright-hook nil
19761 "Hook for functions attaching themselves to `S-right'.
19762 See `org-ctrl-c-ctrl-c-hook' for more information.")
19763 (defvar org-shiftright-final-hook nil
19764 "Hook for functions attaching themselves to `S-right'.
19765 This one runs after all other options except shift-select have been excluded.
19766 See `org-ctrl-c-ctrl-c-hook' for more information.")
19768 (defun org-modifier-cursor-error ()
19769 "Throw an error, a modified cursor command was applied in wrong context."
19770 (user-error "This command is active in special context like tables, headlines or items"))
19772 (defun org-shiftselect-error ()
19773 "Throw an error because Shift-Cursor command was applied in wrong context."
19774 (if (and (boundp 'shift-select-mode) shift-select-mode)
19775 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19776 (user-error "This command works only in special context like headlines or timestamps")))
19778 (defun org-call-for-shift-select (cmd)
19779 (let ((this-command-keys-shift-translated t))
19780 (call-interactively cmd)))
19782 (defun org-shifttab (&optional arg)
19783 "Global visibility cycling or move to previous table field.
19784 Call `org-table-previous-field' within a table.
19785 When ARG is nil, cycle globally through visibility states.
19786 When ARG is a numeric prefix, show contents of this level."
19787 (interactive "P")
19788 (cond
19789 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19790 ((integerp arg)
19791 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19792 (message "Content view to level: %d" arg)
19793 (org-content (prefix-numeric-value arg2))
19794 (org-cycle-show-empty-lines t)
19795 (setq org-cycle-global-status 'overview)))
19796 (t (call-interactively 'org-global-cycle))))
19798 (defun org-shiftmetaleft ()
19799 "Promote subtree or delete table column.
19800 Calls `org-promote-subtree', `org-outdent-item-tree', or
19801 `org-table-delete-column', depending on context. See the
19802 individual commands for more information."
19803 (interactive)
19804 (cond
19805 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19806 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19807 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19808 ((if (not (org-region-active-p)) (org-at-item-p)
19809 (save-excursion (goto-char (region-beginning))
19810 (org-at-item-p)))
19811 (call-interactively 'org-outdent-item-tree))
19812 (t (org-modifier-cursor-error))))
19814 (defun org-shiftmetaright ()
19815 "Demote subtree or insert table column.
19816 Calls `org-demote-subtree', `org-indent-item-tree', or
19817 `org-table-insert-column', depending on context. See the
19818 individual commands for more information."
19819 (interactive)
19820 (cond
19821 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19822 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19823 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19824 ((if (not (org-region-active-p)) (org-at-item-p)
19825 (save-excursion (goto-char (region-beginning))
19826 (org-at-item-p)))
19827 (call-interactively 'org-indent-item-tree))
19828 (t (org-modifier-cursor-error))))
19830 (defun org-shiftmetaup (&optional arg)
19831 "Move subtree up or kill table row.
19832 Calls `org-move-subtree-up' or `org-table-kill-row' or
19833 `org-move-item-up' or `org-timestamp-up', depending on context.
19834 See the individual commands for more information."
19835 (interactive "P")
19836 (cond
19837 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19838 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19839 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19840 ((org-at-item-p) (call-interactively 'org-move-item-up))
19841 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19842 (call-interactively 'org-timestamp-up)))
19843 (t (call-interactively 'org-drag-line-backward))))
19845 (defun org-shiftmetadown (&optional arg)
19846 "Move subtree down or insert table row.
19847 Calls `org-move-subtree-down' or `org-table-insert-row' or
19848 `org-move-item-down' or `org-timestamp-up', depending on context.
19849 See the individual commands for more information."
19850 (interactive "P")
19851 (cond
19852 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19853 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19854 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19855 ((org-at-item-p) (call-interactively 'org-move-item-down))
19856 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19857 (call-interactively 'org-timestamp-down)))
19858 (t (call-interactively 'org-drag-line-forward))))
19860 (defsubst org-hidden-tree-error ()
19861 (user-error
19862 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19864 (defun org-metaleft (&optional arg)
19865 "Promote heading or move table column to left.
19866 Calls `org-do-promote' or `org-table-move-column', depending on context.
19867 With no specific context, calls the Emacs default `backward-word'.
19868 See the individual commands for more information."
19869 (interactive "P")
19870 (cond
19871 ((run-hook-with-args-until-success 'org-metaleft-hook))
19872 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19873 ((org-with-limited-levels
19874 (or (org-at-heading-p)
19875 (and (org-region-active-p)
19876 (save-excursion
19877 (goto-char (region-beginning))
19878 (org-at-heading-p)))))
19879 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19880 (call-interactively 'org-do-promote))
19881 ;; At an inline task.
19882 ((org-at-heading-p)
19883 (call-interactively 'org-inlinetask-promote))
19884 ((or (org-at-item-p)
19885 (and (org-region-active-p)
19886 (save-excursion
19887 (goto-char (region-beginning))
19888 (org-at-item-p))))
19889 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19890 (call-interactively 'org-outdent-item))
19891 (t (call-interactively 'backward-word))))
19893 (defun org-metaright (&optional arg)
19894 "Demote a subtree, a list item or move table column to right.
19895 In front of a drawer or a block keyword, indent it correctly.
19896 With no specific context, calls the Emacs default `forward-word'.
19897 See the individual commands for more information."
19898 (interactive "P")
19899 (cond
19900 ((run-hook-with-args-until-success 'org-metaright-hook))
19901 ((org-at-table-p) (call-interactively 'org-table-move-column))
19902 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19903 ((org-at-block-p) (call-interactively 'org-indent-block))
19904 ((org-with-limited-levels
19905 (or (org-at-heading-p)
19906 (and (org-region-active-p)
19907 (save-excursion
19908 (goto-char (region-beginning))
19909 (org-at-heading-p)))))
19910 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19911 (call-interactively 'org-do-demote))
19912 ;; At an inline task.
19913 ((org-at-heading-p)
19914 (call-interactively 'org-inlinetask-demote))
19915 ((or (org-at-item-p)
19916 (and (org-region-active-p)
19917 (save-excursion
19918 (goto-char (region-beginning))
19919 (org-at-item-p))))
19920 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19921 (call-interactively 'org-indent-item))
19922 (t (call-interactively 'forward-word))))
19924 (defun org-check-for-hidden (what)
19925 "Check if there are hidden headlines/items in the current visual line.
19926 WHAT can be either `headlines' or `items'. If the current line is
19927 an outline or item heading and it has a folded subtree below it,
19928 this function returns t, nil otherwise."
19929 (let ((re (cond
19930 ((eq what 'headlines) org-outline-regexp-bol)
19931 ((eq what 'items) (org-item-beginning-re))
19932 (t (error "This should not happen"))))
19933 beg end)
19934 (save-excursion
19935 (catch 'exit
19936 (unless (org-region-active-p)
19937 (setq beg (point-at-bol))
19938 (beginning-of-line 2)
19939 (while (and (not (eobp)) ;; this is like `next-line'
19940 (get-char-property (1- (point)) 'invisible))
19941 (beginning-of-line 2))
19942 (setq end (point))
19943 (goto-char beg)
19944 (goto-char (point-at-eol))
19945 (setq end (max end (point)))
19946 (while (re-search-forward re end t)
19947 (if (get-char-property (match-beginning 0) 'invisible)
19948 (throw 'exit t))))
19949 nil))))
19951 (defun org-metaup (&optional arg)
19952 "Move subtree up or move table row up.
19953 Calls `org-move-subtree-up' or `org-table-move-row' or
19954 `org-move-item-up', depending on context. See the individual commands
19955 for more information."
19956 (interactive "P")
19957 (cond
19958 ((run-hook-with-args-until-success 'org-metaup-hook))
19959 ((org-region-active-p)
19960 (let* ((a (min (region-beginning) (region-end)))
19961 (b (1- (max (region-beginning) (region-end))))
19962 (c (save-excursion (goto-char a)
19963 (move-beginning-of-line 0)))
19964 (d (save-excursion (goto-char a)
19965 (move-end-of-line 0) (point))))
19966 (transpose-regions a b c d)
19967 (goto-char c)))
19968 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19969 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19970 ((org-at-item-p) (call-interactively 'org-move-item-up))
19971 (t (org-drag-element-backward))))
19973 (defun org-metadown (&optional arg)
19974 "Move subtree down or move table row down.
19975 Calls `org-move-subtree-down' or `org-table-move-row' or
19976 `org-move-item-down', depending on context. See the individual
19977 commands for more information."
19978 (interactive "P")
19979 (cond
19980 ((run-hook-with-args-until-success 'org-metadown-hook))
19981 ((org-region-active-p)
19982 (let* ((a (min (region-beginning) (region-end)))
19983 (b (max (region-beginning) (region-end)))
19984 (c (save-excursion (goto-char b)
19985 (move-beginning-of-line 1)))
19986 (d (save-excursion (goto-char b)
19987 (move-end-of-line 1) (1+ (point)))))
19988 (transpose-regions a b c d)
19989 (goto-char d)))
19990 ((org-at-table-p) (call-interactively 'org-table-move-row))
19991 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19992 ((org-at-item-p) (call-interactively 'org-move-item-down))
19993 (t (org-drag-element-forward))))
19995 (defun org-shiftup (&optional arg)
19996 "Increase item in timestamp or increase priority of current headline.
19997 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19998 depending on context. See the individual commands for more information."
19999 (interactive "P")
20000 (cond
20001 ((run-hook-with-args-until-success 'org-shiftup-hook))
20002 ((and org-support-shift-select (org-region-active-p))
20003 (org-call-for-shift-select 'previous-line))
20004 ((org-at-timestamp-p t)
20005 (call-interactively (if org-edit-timestamp-down-means-later
20006 'org-timestamp-down 'org-timestamp-up)))
20007 ((and (not (eq org-support-shift-select 'always))
20008 org-enable-priority-commands
20009 (org-at-heading-p))
20010 (call-interactively 'org-priority-up))
20011 ((and (not org-support-shift-select) (org-at-item-p))
20012 (call-interactively 'org-previous-item))
20013 ((org-clocktable-try-shift 'up arg))
20014 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20015 (org-support-shift-select
20016 (org-call-for-shift-select 'previous-line))
20017 (t (org-shiftselect-error))))
20019 (defun org-shiftdown (&optional arg)
20020 "Decrease item in timestamp or decrease priority of current headline.
20021 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20022 depending on context. See the individual commands for more information."
20023 (interactive "P")
20024 (cond
20025 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20026 ((and org-support-shift-select (org-region-active-p))
20027 (org-call-for-shift-select 'next-line))
20028 ((org-at-timestamp-p t)
20029 (call-interactively (if org-edit-timestamp-down-means-later
20030 'org-timestamp-up 'org-timestamp-down)))
20031 ((and (not (eq org-support-shift-select 'always))
20032 org-enable-priority-commands
20033 (org-at-heading-p))
20034 (call-interactively 'org-priority-down))
20035 ((and (not org-support-shift-select) (org-at-item-p))
20036 (call-interactively 'org-next-item))
20037 ((org-clocktable-try-shift 'down arg))
20038 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20039 (org-support-shift-select
20040 (org-call-for-shift-select 'next-line))
20041 (t (org-shiftselect-error))))
20043 (defun org-shiftright (&optional arg)
20044 "Cycle the thing at point or in the current line, depending on context.
20045 Depending on context, this does one of the following:
20047 - switch a timestamp at point one day into the future
20048 - on a headline, switch to the next TODO keyword.
20049 - on an item, switch entire list to the next bullet type
20050 - on a property line, switch to the next allowed value
20051 - on a clocktable definition line, move time block into the future"
20052 (interactive "P")
20053 (cond
20054 ((run-hook-with-args-until-success 'org-shiftright-hook))
20055 ((and org-support-shift-select (org-region-active-p))
20056 (org-call-for-shift-select 'forward-char))
20057 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20058 ((and (not (eq org-support-shift-select 'always))
20059 (org-at-heading-p))
20060 (let ((org-inhibit-logging
20061 (not org-treat-S-cursor-todo-selection-as-state-change))
20062 (org-inhibit-blocking
20063 (not org-treat-S-cursor-todo-selection-as-state-change)))
20064 (org-call-with-arg 'org-todo 'right)))
20065 ((or (and org-support-shift-select
20066 (not (eq org-support-shift-select 'always))
20067 (org-at-item-bullet-p))
20068 (and (not org-support-shift-select) (org-at-item-p)))
20069 (org-call-with-arg 'org-cycle-list-bullet nil))
20070 ((and (not (eq org-support-shift-select 'always))
20071 (org-at-property-p))
20072 (call-interactively 'org-property-next-allowed-value))
20073 ((org-clocktable-try-shift 'right arg))
20074 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20075 (org-support-shift-select
20076 (org-call-for-shift-select 'forward-char))
20077 (t (org-shiftselect-error))))
20079 (defun org-shiftleft (&optional arg)
20080 "Cycle the thing at point or in the current line, depending on context.
20081 Depending on context, this does one of the following:
20083 - switch a timestamp at point one day into the past
20084 - on a headline, switch to the previous TODO keyword.
20085 - on an item, switch entire list to the previous bullet type
20086 - on a property line, switch to the previous allowed value
20087 - on a clocktable definition line, move time block into the past"
20088 (interactive "P")
20089 (cond
20090 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20091 ((and org-support-shift-select (org-region-active-p))
20092 (org-call-for-shift-select 'backward-char))
20093 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20094 ((and (not (eq org-support-shift-select 'always))
20095 (org-at-heading-p))
20096 (let ((org-inhibit-logging
20097 (not org-treat-S-cursor-todo-selection-as-state-change))
20098 (org-inhibit-blocking
20099 (not org-treat-S-cursor-todo-selection-as-state-change)))
20100 (org-call-with-arg 'org-todo 'left)))
20101 ((or (and org-support-shift-select
20102 (not (eq org-support-shift-select 'always))
20103 (org-at-item-bullet-p))
20104 (and (not org-support-shift-select) (org-at-item-p)))
20105 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20106 ((and (not (eq org-support-shift-select 'always))
20107 (org-at-property-p))
20108 (call-interactively 'org-property-previous-allowed-value))
20109 ((org-clocktable-try-shift 'left arg))
20110 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20111 (org-support-shift-select
20112 (org-call-for-shift-select 'backward-char))
20113 (t (org-shiftselect-error))))
20115 (defun org-shiftcontrolright ()
20116 "Switch to next TODO set."
20117 (interactive)
20118 (cond
20119 ((and org-support-shift-select (org-region-active-p))
20120 (org-call-for-shift-select 'forward-word))
20121 ((and (not (eq org-support-shift-select 'always))
20122 (org-at-heading-p))
20123 (org-call-with-arg 'org-todo 'nextset))
20124 (org-support-shift-select
20125 (org-call-for-shift-select 'forward-word))
20126 (t (org-shiftselect-error))))
20128 (defun org-shiftcontrolleft ()
20129 "Switch to previous TODO set."
20130 (interactive)
20131 (cond
20132 ((and org-support-shift-select (org-region-active-p))
20133 (org-call-for-shift-select 'backward-word))
20134 ((and (not (eq org-support-shift-select 'always))
20135 (org-at-heading-p))
20136 (org-call-with-arg 'org-todo 'previousset))
20137 (org-support-shift-select
20138 (org-call-for-shift-select 'backward-word))
20139 (t (org-shiftselect-error))))
20141 (defun org-shiftcontrolup (&optional n)
20142 "Change timestamps synchronously up in CLOCK log lines.
20143 Optional argument N tells to change by that many units."
20144 (interactive "P")
20145 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20146 (let (org-support-shift-select)
20147 (org-clock-timestamps-up n))
20148 (user-error "Not at a clock log")))
20150 (defun org-shiftcontroldown (&optional n)
20151 "Change timestamps synchronously down in CLOCK log lines.
20152 Optional argument N tells to change by that many units."
20153 (interactive "P")
20154 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20155 (let (org-support-shift-select)
20156 (org-clock-timestamps-down n))
20157 (user-error "Not at a clock log")))
20159 (defun org-ctrl-c-ret ()
20160 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20161 (interactive)
20162 (cond
20163 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20164 (t (call-interactively 'org-insert-heading))))
20166 (defun org-find-visible ()
20167 (let ((s (point)))
20168 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20169 (get-char-property s 'invisible)))
20171 (defun org-find-invisible ()
20172 (let ((s (point)))
20173 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20174 (not (get-char-property s 'invisible))))
20177 (defun org-copy-visible (beg end)
20178 "Copy the visible parts of the region."
20179 (interactive "r")
20180 (let (snippets s)
20181 (save-excursion
20182 (save-restriction
20183 (narrow-to-region beg end)
20184 (setq s (goto-char (point-min)))
20185 (while (not (= (point) (point-max)))
20186 (goto-char (org-find-invisible))
20187 (push (buffer-substring s (point)) snippets)
20188 (setq s (goto-char (org-find-visible))))))
20189 (kill-new (apply 'concat (nreverse snippets)))))
20191 (defun org-copy-special ()
20192 "Copy region in table or copy current subtree.
20193 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20194 See the individual commands for more information."
20195 (interactive)
20196 (call-interactively
20197 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20199 (defun org-cut-special ()
20200 "Cut region in table or cut current subtree.
20201 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20202 See the individual commands for more information."
20203 (interactive)
20204 (call-interactively
20205 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20207 (defun org-paste-special (arg)
20208 "Paste rectangular region into table, or past subtree relative to level.
20209 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20210 See the individual commands for more information."
20211 (interactive "P")
20212 (if (org-at-table-p)
20213 (org-table-paste-rectangle)
20214 (org-paste-subtree arg)))
20216 (defsubst org-in-fixed-width-region-p ()
20217 "Is point in a fixed-width region?"
20218 (save-match-data
20219 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20221 (defun org-edit-special (&optional arg)
20222 "Call a special editor for the element at point.
20223 When at a table, call the formula editor with `org-table-edit-formulas'.
20224 When in a source code block, call `org-edit-src-code'.
20225 When in a fixed-width region, call `org-edit-fixed-width-region'.
20226 When at an #+INCLUDE keyword, visit the included file.
20227 On a link, call `ffap' to visit the link at point.
20228 Otherwise, return a user error."
20229 (interactive "P")
20230 (let ((element (org-element-at-point)))
20231 (assert (not buffer-read-only) nil
20232 "Buffer is read-only: %s" (buffer-name))
20233 (case (org-element-type element)
20234 (src-block
20235 (if (not arg) (org-edit-src-code)
20236 (let* ((info (org-babel-get-src-block-info))
20237 (lang (nth 0 info))
20238 (params (nth 2 info))
20239 (session (cdr (assq :session params))))
20240 (if (not session) (org-edit-src-code)
20241 ;; At a src-block with a session and function called with
20242 ;; an ARG: switch to the buffer related to the inferior
20243 ;; process.
20244 (switch-to-buffer
20245 (funcall (intern (concat "org-babel-prep-session:" lang))
20246 session params))))))
20247 (keyword
20248 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20249 (find-file-other-window
20250 (org-remove-double-quotes
20251 (car (org-split-string (org-element-property :value element)))))
20252 (user-error "No special environment to edit here")))
20253 (table
20254 (if (eq (org-element-property :type element) 'table.el)
20255 (org-edit-src-code)
20256 (call-interactively 'org-table-edit-formulas)))
20257 ;; Only Org tables contain `table-row' type elements.
20258 (table-row (call-interactively 'org-table-edit-formulas))
20259 ((example-block export-block) (org-edit-src-code))
20260 (fixed-width (org-edit-fixed-width-region))
20261 (otherwise
20262 ;; No notable element at point. Though, we may be at a link,
20263 ;; which is an object. Thus, scan deeper.
20264 (if (eq (org-element-type (org-element-context element)) 'link)
20265 (call-interactively 'ffap)
20266 (user-error "No special environment to edit here"))))))
20268 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20269 (defun org-ctrl-c-ctrl-c (&optional arg)
20270 "Set tags in headline, or update according to changed information at point.
20272 This command does many different things, depending on context:
20274 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20275 this is what we do.
20277 - If the cursor is on a statistics cookie, update it.
20279 - If the cursor is in a headline, prompt for tags and insert them
20280 into the current line, aligned to `org-tags-column'. When called
20281 with prefix arg, realign all tags in the current buffer.
20283 - If the cursor is in one of the special #+KEYWORD lines, this
20284 triggers scanning the buffer for these lines and updating the
20285 information.
20287 - If the cursor is inside a table, realign the table. This command
20288 works even if the automatic table editor has been turned off.
20290 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20291 the entire table.
20293 - If the cursor is at a footnote reference or definition, jump to
20294 the corresponding definition or references, respectively.
20296 - If the cursor is a the beginning of a dynamic block, update it.
20298 - If the current buffer is a capture buffer, close note and file it.
20300 - If the cursor is on a <<<target>>>, update radio targets and
20301 corresponding links in this buffer.
20303 - If the cursor is on a numbered item in a plain list, renumber the
20304 ordered list.
20306 - If the cursor is on a checkbox, toggle it.
20308 - If the cursor is on a code block, evaluate it. The variable
20309 `org-confirm-babel-evaluate' can be used to control prompting
20310 before code block evaluation, by default every code block
20311 evaluation requires confirmation. Code block evaluation can be
20312 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20313 (interactive "P")
20314 (cond
20315 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20316 org-occur-highlights
20317 org-latex-fragment-image-overlays)
20318 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20319 (org-remove-occur-highlights)
20320 (org-remove-latex-fragment-image-overlays)
20321 (message "Temporary highlights/overlays removed from current buffer"))
20322 ((and (local-variable-p 'org-finish-function (current-buffer))
20323 (fboundp org-finish-function))
20324 (funcall org-finish-function))
20325 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20327 (let* ((context (org-element-context)) (type (org-element-type context)))
20328 ;; Test if point is within a blank line.
20329 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20330 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20331 (user-error "C-c C-c can do nothing useful at this location"))
20332 (case type
20333 ;; When at a link, act according to the parent instead.
20334 (link (setq context (org-element-property :parent context))
20335 (setq type (org-element-type context)))
20336 ;; Unsupported object types: check parent element instead.
20337 ((bold code entity export-snippet inline-babel-call inline-src-block
20338 italic latex-fragment line-break macro strike-through subscript
20339 superscript underline verbatim)
20340 (while (and (setq context (org-element-property :parent context))
20341 (not (memq (setq type (org-element-type context))
20342 '(paragraph verse-block)))))))
20343 ;; For convenience: at the first line of a paragraph on the
20344 ;; same line as an item, apply function on that item instead.
20345 (when (eq type 'paragraph)
20346 (let ((parent (org-element-property :parent context)))
20347 (when (and (eq (org-element-type parent) 'item)
20348 (= (point-at-bol) (org-element-property :begin parent)))
20349 (setq context parent type 'item))))
20350 ;; Act according to type of element or object at point.
20351 (case type
20352 (clock (org-clock-update-time-maybe))
20353 (dynamic-block
20354 (save-excursion
20355 (goto-char (org-element-property :post-affiliated context))
20356 (org-update-dblock)))
20357 (footnote-definition
20358 (goto-char (org-element-property :post-affiliated context))
20359 (call-interactively 'org-footnote-action))
20360 (footnote-reference (call-interactively 'org-footnote-action))
20361 ((headline inlinetask)
20362 (save-excursion (goto-char (org-element-property :begin context))
20363 (call-interactively 'org-set-tags)))
20364 (item
20365 ;; At an item: a double C-u set checkbox to "[-]"
20366 ;; unconditionally, whereas a single one will toggle its
20367 ;; presence. Without an universal argument, if the item
20368 ;; has a checkbox, toggle it. Otherwise repair the list.
20369 (let* ((box (org-element-property :checkbox context))
20370 (struct (org-element-property :structure context))
20371 (old-struct (copy-tree struct))
20372 (parents (org-list-parents-alist struct))
20373 (prevs (org-list-prevs-alist struct))
20374 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20375 (org-list-set-checkbox
20376 (org-element-property :begin context) struct
20377 (cond ((equal arg '(16)) "[-]")
20378 ((and (not box) (equal arg '(4))) "[ ]")
20379 ((or (not box) (equal arg '(4))) nil)
20380 ((eq box 'on) "[ ]")
20381 (t "[X]")))
20382 ;; Mimic `org-list-write-struct' but with grabbing
20383 ;; a return value from `org-list-struct-fix-box'.
20384 (org-list-struct-fix-ind struct parents 2)
20385 (org-list-struct-fix-item-end struct)
20386 (org-list-struct-fix-bul struct prevs)
20387 (org-list-struct-fix-ind struct parents)
20388 (let ((block-item
20389 (org-list-struct-fix-box struct parents prevs orderedp)))
20390 (if (and box (equal struct old-struct))
20391 (if (equal arg '(16))
20392 (message "Checkboxes already reset")
20393 (user-error "Cannot toggle this checkbox: %s"
20394 (if (eq box 'on)
20395 "all subitems checked"
20396 "unchecked subitems")))
20397 (org-list-struct-apply-struct struct old-struct)
20398 (org-update-checkbox-count-maybe))
20399 (when block-item
20400 (message "Checkboxes were removed due to empty box at line %d"
20401 (org-current-line block-item))))))
20402 (keyword
20403 (let ((org-inhibit-startup-visibility-stuff t)
20404 (org-startup-align-all-tables nil))
20405 (when (boundp 'org-table-coordinate-overlays)
20406 (mapc 'delete-overlay org-table-coordinate-overlays)
20407 (setq org-table-coordinate-overlays nil))
20408 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20409 (message "Local setup has been refreshed"))
20410 (plain-list
20411 ;; At a plain list, with a double C-u argument, set
20412 ;; checkboxes of each item to "[-]", whereas a single one
20413 ;; will toggle their presence according to the state of the
20414 ;; first item in the list. Without an argument, repair the
20415 ;; list.
20416 (let* ((begin (org-element-property :contents-begin context))
20417 (beginm (move-marker (make-marker) begin))
20418 (struct (org-element-property :structure context))
20419 (old-struct (copy-tree struct))
20420 (first-box (save-excursion
20421 (goto-char begin)
20422 (looking-at org-list-full-item-re)
20423 (match-string-no-properties 3)))
20424 (new-box (cond ((equal arg '(16)) "[-]")
20425 ((equal arg '(4)) (unless first-box "[ ]"))
20426 ((equal first-box "[X]") "[ ]")
20427 (t "[X]"))))
20428 (cond
20429 (arg
20430 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20431 (org-list-get-all-items
20432 begin struct (org-list-prevs-alist struct))))
20433 ((and first-box (eq (point) begin))
20434 ;; For convenience, when point is at bol on the first
20435 ;; item of the list and no argument is provided, simply
20436 ;; toggle checkbox of that item, if any.
20437 (org-list-set-checkbox begin struct new-box)))
20438 (org-list-write-struct
20439 struct (org-list-parents-alist struct) old-struct)
20440 (org-update-checkbox-count-maybe)
20441 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20442 ((property-drawer node-property)
20443 (call-interactively 'org-property-action))
20444 ((radio-target target)
20445 (call-interactively 'org-update-radio-target-regexp))
20446 (statistics-cookie
20447 (call-interactively 'org-update-statistics-cookies))
20448 ((table table-cell table-row)
20449 ;; At a table, recalculate every field and align it. Also
20450 ;; send the table if necessary. If the table has
20451 ;; a `table.el' type, just give up. At a table row or
20452 ;; cell, maybe recalculate line but always align table.
20453 (if (eq (org-element-property :type context) 'table.el)
20454 (message "Use C-c ' to edit table.el tables")
20455 (let ((org-enable-table-editor t))
20456 (if (or (eq type 'table)
20457 ;; Check if point is at a TBLFM line.
20458 (and (eq type 'table-row)
20459 (= (point) (org-element-property :end context))))
20460 (save-excursion
20461 (if (org-at-TBLFM-p)
20462 (progn (require 'org-table)
20463 (org-table-calc-current-TBLFM))
20464 (goto-char (org-element-property :contents-begin context))
20465 (org-call-with-arg 'org-table-recalculate (or arg t))
20466 (orgtbl-send-table 'maybe)))
20467 (org-table-maybe-eval-formula)
20468 (cond (arg (call-interactively 'org-table-recalculate))
20469 ((org-table-maybe-recalculate-line))
20470 (t (org-table-align)))))))
20471 (timestamp (org-timestamp-change 0 'day))
20472 (otherwise
20473 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20474 (user-error
20475 "C-c C-c can do nothing useful at this location")))))))))
20477 (defun org-mode-restart ()
20478 (interactive)
20479 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20480 (funcall major-mode)
20481 (hack-local-variables)
20482 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20483 (org-indent-mode -1)))
20484 (message "%s restarted" major-mode))
20486 (defun org-kill-note-or-show-branches ()
20487 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20488 (interactive)
20489 (if (not org-finish-function)
20490 (progn
20491 (hide-subtree)
20492 (call-interactively 'show-branches))
20493 (let ((org-note-abort t))
20494 (funcall org-finish-function))))
20496 (defun org-open-line (n)
20497 "Insert a new row in tables, call `open-line' elsewhere.
20498 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20499 (interactive "*p")
20500 (cond
20501 ((not org-special-ctrl-o)
20502 (open-line n))
20503 ((org-at-table-p)
20504 (org-table-insert-row))
20506 (open-line n))))
20508 (defun org-return (&optional indent)
20509 "Goto next table row or insert a newline.
20510 Calls `org-table-next-row' or `newline', depending on context.
20511 See the individual commands for more information."
20512 (interactive)
20513 (let (org-ts-what)
20514 (cond
20515 ((or (bobp) (org-in-src-block-p))
20516 (if indent (newline-and-indent) (newline)))
20517 ((org-at-table-p)
20518 (org-table-justify-field-maybe)
20519 (call-interactively 'org-table-next-row))
20520 ;; when `newline-and-indent' is called within a list, make sure
20521 ;; text moved stays inside the item.
20522 ((and (org-in-item-p) indent)
20523 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20524 (progn
20525 (save-match-data (newline))
20526 (org-indent-line-to (length (match-string 0))))
20527 (let ((ind (org-get-indentation)))
20528 (newline)
20529 (if (org-looking-back org-list-end-re)
20530 (org-indent-line)
20531 (org-indent-line-to ind)))))
20532 ((and org-return-follows-link
20533 (org-at-timestamp-p t)
20534 (not (eq org-ts-what 'after)))
20535 (org-follow-timestamp-link))
20536 ((and org-return-follows-link
20537 (let ((tprop (get-text-property (point) 'face)))
20538 (or (eq tprop 'org-link)
20539 (and (listp tprop) (memq 'org-link tprop)))))
20540 (call-interactively 'org-open-at-point))
20541 ((and (org-at-heading-p)
20542 (looking-at
20543 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20544 (org-show-entry)
20545 (end-of-line 1)
20546 (newline))
20547 (t (if indent (newline-and-indent) (newline))))))
20549 (defun org-return-indent ()
20550 "Goto next table row or insert a newline and indent.
20551 Calls `org-table-next-row' or `newline-and-indent', depending on
20552 context. See the individual commands for more information."
20553 (interactive)
20554 (org-return t))
20556 (defun org-ctrl-c-star ()
20557 "Compute table, or change heading status of lines.
20558 Calls `org-table-recalculate' or `org-toggle-heading',
20559 depending on context."
20560 (interactive)
20561 (cond
20562 ((org-at-table-p)
20563 (call-interactively 'org-table-recalculate))
20565 ;; Convert all lines in region to list items
20566 (call-interactively 'org-toggle-heading))))
20568 (defun org-ctrl-c-minus ()
20569 "Insert separator line in table or modify bullet status of line.
20570 Also turns a plain line or a region of lines into list items.
20571 Calls `org-table-insert-hline', `org-toggle-item', or
20572 `org-cycle-list-bullet', depending on context."
20573 (interactive)
20574 (cond
20575 ((org-at-table-p)
20576 (call-interactively 'org-table-insert-hline))
20577 ((org-region-active-p)
20578 (call-interactively 'org-toggle-item))
20579 ((org-in-item-p)
20580 (call-interactively 'org-cycle-list-bullet))
20582 (call-interactively 'org-toggle-item))))
20584 (defun org-toggle-item (arg)
20585 "Convert headings or normal lines to items, items to normal lines.
20586 If there is no active region, only the current line is considered.
20588 If the first non blank line in the region is a headline, convert
20589 all headlines to items, shifting text accordingly.
20591 If it is an item, convert all items to normal lines.
20593 If it is normal text, change region into a list of items.
20594 With a prefix argument ARG, change the region in a single item."
20595 (interactive "P")
20596 (let ((shift-text
20597 (function
20598 ;; Shift text in current section to IND, from point to END.
20599 ;; The function leaves point to END line.
20600 (lambda (ind end)
20601 (let ((min-i 1000) (end (copy-marker end)))
20602 ;; First determine the minimum indentation (MIN-I) of
20603 ;; the text.
20604 (save-excursion
20605 (catch 'exit
20606 (while (< (point) end)
20607 (let ((i (org-get-indentation)))
20608 (cond
20609 ;; Skip blank lines and inline tasks.
20610 ((looking-at "^[ \t]*$"))
20611 ((looking-at org-outline-regexp-bol))
20612 ;; We can't find less than 0 indentation.
20613 ((zerop i) (throw 'exit (setq min-i 0)))
20614 ((< i min-i) (setq min-i i))))
20615 (forward-line))))
20616 ;; Then indent each line so that a line indented to
20617 ;; MIN-I becomes indented to IND. Ignore blank lines
20618 ;; and inline tasks in the process.
20619 (let ((delta (- ind min-i)))
20620 (while (< (point) end)
20621 (unless (or (looking-at "^[ \t]*$")
20622 (looking-at org-outline-regexp-bol))
20623 (org-indent-line-to (+ (org-get-indentation) delta)))
20624 (forward-line)))))))
20625 (skip-blanks
20626 (function
20627 ;; Return beginning of first non-blank line, starting from
20628 ;; line at POS.
20629 (lambda (pos)
20630 (save-excursion
20631 (goto-char pos)
20632 (skip-chars-forward " \r\t\n")
20633 (point-at-bol)))))
20634 beg end)
20635 ;; Determine boundaries of changes.
20636 (if (org-region-active-p)
20637 (setq beg (funcall skip-blanks (region-beginning))
20638 end (copy-marker (region-end)))
20639 (setq beg (funcall skip-blanks (point-at-bol))
20640 end (copy-marker (point-at-eol))))
20641 ;; Depending on the starting line, choose an action on the text
20642 ;; between BEG and END.
20643 (org-with-limited-levels
20644 (save-excursion
20645 (goto-char beg)
20646 (cond
20647 ;; Case 1. Start at an item: de-itemize. Note that it only
20648 ;; happens when a region is active: `org-ctrl-c-minus'
20649 ;; would call `org-cycle-list-bullet' otherwise.
20650 ((org-at-item-p)
20651 (while (< (point) end)
20652 (when (org-at-item-p)
20653 (skip-chars-forward " \t")
20654 (delete-region (point) (match-end 0)))
20655 (forward-line)))
20656 ;; Case 2. Start at an heading: convert to items.
20657 ((org-at-heading-p)
20658 (let* ((bul (org-list-bullet-string "-"))
20659 (bul-len (length bul))
20660 (done (org-entry-is-done-p))
20661 (todo (org-entry-is-todo-p))
20662 ;; Indentation of the first heading. It should be
20663 ;; relative to the indentation of its parent, if any.
20664 (start-ind (save-excursion
20665 (cond
20666 ((not org-adapt-indentation) 0)
20667 ((not (outline-previous-heading)) 0)
20668 (t (length (match-string 0))))))
20669 ;; Level of first heading. Further headings will be
20670 ;; compared to it to determine hierarchy in the list.
20671 (ref-level (org-reduced-level (org-outline-level))))
20672 (when (or done todo) (org-todo ""))
20673 (while (< (point) end)
20674 (let* ((level (org-reduced-level (org-outline-level)))
20675 (delta (max 0 (- level ref-level))))
20676 ;; If current headline is less indented than the first
20677 ;; one, set it as reference, in order to preserve
20678 ;; subtrees.
20679 (when (< level ref-level) (setq ref-level level))
20680 (replace-match bul t t)
20681 (org-indent-line-to (+ start-ind (* delta bul-len)))
20682 (when (or done todo)
20683 (let* ((struct (org-list-struct))
20684 (old (copy-tree struct)))
20685 (org-list-set-checkbox (line-beginning-position)
20686 struct
20687 (if done "[X]" "[ ]"))
20688 (org-list-write-struct struct
20689 (org-list-parents-alist struct)
20690 old)))
20691 ;; Ensure all text down to END (or SECTION-END) belongs
20692 ;; to the newly created item.
20693 (let ((section-end (save-excursion
20694 (or (outline-next-heading) (point)))))
20695 (forward-line)
20696 (funcall shift-text
20697 (+ start-ind (* (1+ delta) bul-len))
20698 (min end section-end)))))))
20699 ;; Case 3. Normal line with ARG: make the first line of region
20700 ;; an item, and shift indentation of others lines to
20701 ;; set them as item's body.
20702 (arg (let* ((bul (org-list-bullet-string "-"))
20703 (bul-len (length bul))
20704 (ref-ind (org-get-indentation)))
20705 (skip-chars-forward " \t")
20706 (insert bul)
20707 (forward-line)
20708 (while (< (point) end)
20709 ;; Ensure that lines less indented than first one
20710 ;; still get included in item body.
20711 (funcall shift-text
20712 (+ ref-ind bul-len)
20713 (min end (save-excursion (or (outline-next-heading)
20714 (point)))))
20715 (forward-line))))
20716 ;; Case 4. Normal line without ARG: turn each non-item line
20717 ;; into an item.
20719 (while (< (point) end)
20720 (unless (or (org-at-heading-p) (org-at-item-p))
20721 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20722 (replace-match
20723 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20724 (forward-line))))))))
20726 (defun org-toggle-heading (&optional nstars)
20727 "Convert headings to normal text, or items or text to headings.
20728 If there is no active region, only convert the current line.
20730 With a \\[universal-argument] prefix, convert the whole list at
20731 point into heading.
20733 In a region:
20735 - If the first non blank line is a headline, remove the stars
20736 from all headlines in the region.
20738 - If it is a normal line, turn each and every normal line (i.e.,
20739 not an heading or an item) in the region into headings. If you
20740 want to convert only the first line of this region, use one
20741 universal prefix argument.
20743 - If it is a plain list item, turn all plain list items into headings.
20745 When converting a line into a heading, the number of stars is chosen
20746 such that the lines become children of the current entry. However,
20747 when a numeric prefix argument is given, its value determines the
20748 number of stars to add."
20749 (interactive "P")
20750 (let ((skip-blanks
20751 (function
20752 ;; Return beginning of first non-blank line, starting from
20753 ;; line at POS.
20754 (lambda (pos)
20755 (save-excursion
20756 (goto-char pos)
20757 (while (org-at-comment-p) (forward-line))
20758 (skip-chars-forward " \r\t\n")
20759 (point-at-bol)))))
20760 beg end toggled)
20761 ;; Determine boundaries of changes. If a universal prefix has
20762 ;; been given, put the list in a region. If region ends at a bol,
20763 ;; do not consider the last line to be in the region.
20765 (when (and current-prefix-arg (org-at-item-p))
20766 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20767 (org-mark-element))
20769 (if (org-region-active-p)
20770 (setq beg (funcall skip-blanks (region-beginning))
20771 end (copy-marker (save-excursion
20772 (goto-char (region-end))
20773 (if (bolp) (point) (point-at-eol)))))
20774 (setq beg (funcall skip-blanks (point-at-bol))
20775 end (copy-marker (point-at-eol))))
20776 ;; Ensure inline tasks don't count as headings.
20777 (org-with-limited-levels
20778 (save-excursion
20779 (goto-char beg)
20780 (cond
20781 ;; Case 1. Started at an heading: de-star headings.
20782 ((org-at-heading-p)
20783 (while (< (point) end)
20784 (when (org-at-heading-p t)
20785 (looking-at org-outline-regexp) (replace-match "")
20786 (setq toggled t))
20787 (forward-line)))
20788 ;; Case 2. Started at an item: change items into headlines.
20789 ;; One star will be added by `org-list-to-subtree'.
20790 ((org-at-item-p)
20791 (let* ((stars (make-string
20792 ;; subtract the star that will be added again by
20793 ;; `org-list-to-subtree'
20794 (if (numberp nstars) (1- nstars)
20795 (or (org-current-level) 0))
20796 ?*))
20797 (add-stars
20798 (cond (nstars "") ; stars from prefix only
20799 ((equal stars "") "") ; before first heading
20800 (org-odd-levels-only "*") ; inside heading, odd
20801 (t "")))) ; inside heading, oddeven
20802 (while (< (point) end)
20803 (when (org-at-item-p)
20804 ;; Pay attention to cases when region ends before list.
20805 (let* ((struct (org-list-struct))
20806 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20807 (save-restriction
20808 (narrow-to-region (point) list-end)
20809 (insert
20810 (org-list-to-subtree
20811 (org-list-parse-list t)
20812 '(:istart (concat stars add-stars (funcall get-stars depth))
20813 :icount (concat stars add-stars (funcall get-stars depth)))))))
20814 (setq toggled t))
20815 (forward-line))))
20816 ;; Case 3. Started at normal text: make every line an heading,
20817 ;; skipping headlines and items.
20818 (t (let* ((stars
20819 (make-string
20820 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20821 (add-stars
20822 (cond (nstars "") ; stars from prefix only
20823 ((equal stars "") "*") ; before first heading
20824 (org-odd-levels-only "**") ; inside heading, odd
20825 (t "*"))) ; inside heading, oddeven
20826 (rpl (concat stars add-stars " "))
20827 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20828 (while (< (point) (if (equal nstars '(4)) lend end))
20829 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20830 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20831 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20832 (forward-line)))))))
20833 (unless toggled (message "Cannot toggle heading from here"))))
20835 (defun org-meta-return (&optional arg)
20836 "Insert a new heading or wrap a region in a table.
20837 Calls `org-insert-heading' or `org-table-wrap-region', depending
20838 on context. See the individual commands for more information."
20839 (interactive "P")
20840 (org-check-before-invisible-edit 'insert)
20841 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20842 (let* ((element (org-element-at-point))
20843 (type (org-element-type element)))
20844 (when (eq type 'table-row)
20845 (setq element (org-element-property :parent element))
20846 (setq type 'table))
20847 (if (and (eq type 'table)
20848 (eq (org-element-property :type element) 'org)
20849 (>= (point) (org-element-property :contents-begin element))
20850 (< (point) (org-element-property :contents-end element)))
20851 (call-interactively 'org-table-wrap-region)
20852 (call-interactively 'org-insert-heading)))))
20854 ;;; Menu entries
20856 (defsubst org-in-subtree-not-table-p ()
20857 "Are we in a subtree and not in a table?"
20858 (and (not (org-before-first-heading-p))
20859 (not (org-at-table-p))))
20861 ;; Define the Org-mode menus
20862 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20863 '("Tbl"
20864 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20865 ["Next Field" org-cycle (org-at-table-p)]
20866 ["Previous Field" org-shifttab (org-at-table-p)]
20867 ["Next Row" org-return (org-at-table-p)]
20868 "--"
20869 ["Blank Field" org-table-blank-field (org-at-table-p)]
20870 ["Edit Field" org-table-edit-field (org-at-table-p)]
20871 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20872 "--"
20873 ("Column"
20874 ["Move Column Left" org-metaleft (org-at-table-p)]
20875 ["Move Column Right" org-metaright (org-at-table-p)]
20876 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20877 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20878 ("Row"
20879 ["Move Row Up" org-metaup (org-at-table-p)]
20880 ["Move Row Down" org-metadown (org-at-table-p)]
20881 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20882 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20883 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20884 "--"
20885 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20886 ("Rectangle"
20887 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20888 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20889 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20890 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20891 "--"
20892 ("Calculate"
20893 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20894 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20895 ["Edit Formulas" org-edit-special (org-at-table-p)]
20896 "--"
20897 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20898 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20899 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20900 "--"
20901 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20902 "--"
20903 ["Sum Column/Rectangle" org-table-sum
20904 (or (org-at-table-p) (org-region-active-p))]
20905 ["Which Column?" org-table-current-column (org-at-table-p)])
20906 ["Debug Formulas"
20907 org-table-toggle-formula-debugger
20908 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20909 ["Show Col/Row Numbers"
20910 org-table-toggle-coordinate-overlays
20911 :style toggle
20912 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20913 "--"
20914 ["Create" org-table-create (and (not (org-at-table-p))
20915 org-enable-table-editor)]
20916 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20917 ["Import from File" org-table-import (not (org-at-table-p))]
20918 ["Export to File" org-table-export (org-at-table-p)]
20919 "--"
20920 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20922 (easy-menu-define org-org-menu org-mode-map "Org menu"
20923 '("Org"
20924 ("Show/Hide"
20925 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20926 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20927 ["Sparse Tree..." org-sparse-tree t]
20928 ["Reveal Context" org-reveal t]
20929 ["Show All" show-all t]
20930 "--"
20931 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20932 "--"
20933 ["New Heading" org-insert-heading t]
20934 ("Navigate Headings"
20935 ["Up" outline-up-heading t]
20936 ["Next" outline-next-visible-heading t]
20937 ["Previous" outline-previous-visible-heading t]
20938 ["Next Same Level" outline-forward-same-level t]
20939 ["Previous Same Level" outline-backward-same-level t]
20940 "--"
20941 ["Jump" org-goto t])
20942 ("Edit Structure"
20943 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20944 "--"
20945 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20946 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20947 "--"
20948 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20949 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20950 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20951 "--"
20952 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20953 "--"
20954 ["Copy visible text" org-copy-visible t]
20955 "--"
20956 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20957 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20958 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20959 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20960 "--"
20961 ["Sort Region/Children" org-sort t]
20962 "--"
20963 ["Convert to odd levels" org-convert-to-odd-levels t]
20964 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20965 ("Editing"
20966 ["Emphasis..." org-emphasize t]
20967 ["Edit Source Example" org-edit-special t]
20968 "--"
20969 ["Footnote new/jump" org-footnote-action t]
20970 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20971 ("Archive"
20972 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20973 "--"
20974 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20975 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20976 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20978 "--"
20979 ("Hyperlinks"
20980 ["Store Link (Global)" org-store-link t]
20981 ["Find existing link to here" org-occur-link-in-agenda-files t]
20982 ["Insert Link" org-insert-link t]
20983 ["Follow Link" org-open-at-point t]
20984 "--"
20985 ["Next link" org-next-link t]
20986 ["Previous link" org-previous-link t]
20987 "--"
20988 ["Descriptive Links"
20989 org-toggle-link-display
20990 :style radio
20991 :selected org-descriptive-links
20993 ["Literal Links"
20994 org-toggle-link-display
20995 :style radio
20996 :selected (not org-descriptive-links)])
20997 "--"
20998 ("TODO Lists"
20999 ["TODO/DONE/-" org-todo t]
21000 ("Select keyword"
21001 ["Next keyword" org-shiftright (org-at-heading-p)]
21002 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21003 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21004 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21005 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21006 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21007 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21008 "--"
21009 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21010 :selected org-enforce-todo-dependencies :style toggle :active t]
21011 "Settings for tree at point"
21012 ["Do Children sequentially" org-toggle-ordered-property :style radio
21013 :selected (org-entry-get nil "ORDERED")
21014 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21015 ["Do Children parallel" org-toggle-ordered-property :style radio
21016 :selected (not (org-entry-get nil "ORDERED"))
21017 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21018 "--"
21019 ["Set Priority" org-priority t]
21020 ["Priority Up" org-shiftup t]
21021 ["Priority Down" org-shiftdown t]
21022 "--"
21023 ["Get news from all feeds" org-feed-update-all t]
21024 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21025 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21026 ("TAGS and Properties"
21027 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21028 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21029 "--"
21030 ["Set property" org-set-property (not (org-before-first-heading-p))]
21031 ["Column view of properties" org-columns t]
21032 ["Insert Column View DBlock" org-insert-columns-dblock t])
21033 ("Dates and Scheduling"
21034 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21035 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21036 ("Change Date"
21037 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21038 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21039 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21040 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21041 ["Compute Time Range" org-evaluate-time-range t]
21042 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21043 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21044 "--"
21045 ["Custom time format" org-toggle-time-stamp-overlays
21046 :style radio :selected org-display-custom-times]
21047 "--"
21048 ["Goto Calendar" org-goto-calendar t]
21049 ["Date from Calendar" org-date-from-calendar t]
21050 "--"
21051 ["Start/Restart Timer" org-timer-start t]
21052 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21053 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21054 ["Insert Timer String" org-timer t]
21055 ["Insert Timer Item" org-timer-item t])
21056 ("Logging work"
21057 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21058 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21059 ["Clock out" org-clock-out t]
21060 ["Clock cancel" org-clock-cancel t]
21061 "--"
21062 ["Mark as default task" org-clock-mark-default-task t]
21063 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21064 ["Goto running clock" org-clock-goto t]
21065 "--"
21066 ["Display times" org-clock-display t]
21067 ["Create clock table" org-clock-report t]
21068 "--"
21069 ["Record DONE time"
21070 (progn (setq org-log-done (not org-log-done))
21071 (message "Switching to %s will %s record a timestamp"
21072 (car org-done-keywords)
21073 (if org-log-done "automatically" "not")))
21074 :style toggle :selected org-log-done])
21075 "--"
21076 ["Agenda Command..." org-agenda t]
21077 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21078 ("File List for Agenda")
21079 ("Special views current file"
21080 ["TODO Tree" org-show-todo-tree t]
21081 ["Check Deadlines" org-check-deadlines t]
21082 ["Timeline" org-timeline t]
21083 ["Tags/Property tree" org-match-sparse-tree t])
21084 "--"
21085 ["Export/Publish..." org-export-dispatch t]
21086 ("LaTeX"
21087 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21088 :selected org-cdlatex-mode]
21089 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21090 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21091 ["Modify math symbol" org-cdlatex-math-modify
21092 (org-inside-LaTeX-fragment-p)]
21093 ["Insert citation" org-reftex-citation t]
21094 "--"
21095 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21096 "--"
21097 ("MobileOrg"
21098 ["Push Files and Views" org-mobile-push t]
21099 ["Get Captured and Flagged" org-mobile-pull t]
21100 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21101 "--"
21102 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21103 "--"
21104 ("Documentation"
21105 ["Show Version" org-version t]
21106 ["Info Documentation" org-info t])
21107 ("Customize"
21108 ["Browse Org Group" org-customize t]
21109 "--"
21110 ["Expand This Menu" org-create-customize-menu
21111 (fboundp 'customize-menu-create)])
21112 ["Send bug report" org-submit-bug-report t]
21113 "--"
21114 ("Refresh/Reload"
21115 ["Refresh setup current buffer" org-mode-restart t]
21116 ["Reload Org (after update)" org-reload t]
21117 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21120 (defun org-info (&optional node)
21121 "Read documentation for Org-mode in the info system.
21122 With optional NODE, go directly to that node."
21123 (interactive)
21124 (info (format "(org)%s" (or node ""))))
21126 ;;;###autoload
21127 (defun org-submit-bug-report ()
21128 "Submit a bug report on Org-mode via mail.
21130 Don't hesitate to report any problems or inaccurate documentation.
21132 If you don't have setup sending mail from (X)Emacs, please copy the
21133 output buffer into your mail program, as it gives us important
21134 information about your Org-mode version and configuration."
21135 (interactive)
21136 (require 'reporter)
21137 (org-load-modules-maybe)
21138 (org-require-autoloaded-modules)
21139 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21140 (reporter-submit-bug-report
21141 "emacs-orgmode@gnu.org"
21142 (org-version nil 'full)
21143 (let (list)
21144 (save-window-excursion
21145 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21146 (delete-other-windows)
21147 (erase-buffer)
21148 (insert "You are about to submit a bug report to the Org-mode mailing list.
21150 We would like to add your full Org-mode and Outline configuration to the
21151 bug report. This greatly simplifies the work of the maintainer and
21152 other experts on the mailing list.
21154 HOWEVER, some variables you have customized may contain private
21155 information. The names of customers, colleagues, or friends, might
21156 appear in the form of file names, tags, todo states, or search strings.
21157 If you answer yes to the prompt, you might want to check and remove
21158 such private information before sending the email.")
21159 (add-text-properties (point-min) (point-max) '(face org-warning))
21160 (when (yes-or-no-p "Include your Org-mode configuration ")
21161 (mapatoms
21162 (lambda (v)
21163 (and (boundp v)
21164 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21165 (or (and (symbol-value v)
21166 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21167 (and
21168 (get v 'custom-type) (get v 'standard-value)
21169 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21170 (push v list)))))
21171 (kill-buffer (get-buffer "*Warn about privacy*"))
21172 list))
21173 nil nil
21174 "Remember to cover the basics, that is, what you expected to happen and
21175 what in fact did happen. You don't know how to make a good report? See
21177 http://orgmode.org/manual/Feedback.html#Feedback
21179 Your bug report will be posted to the Org-mode mailing list.
21180 ------------------------------------------------------------------------")
21181 (save-excursion
21182 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21183 (replace-match "\\1Bug: \\3 [\\2]")))))
21186 (defun org-install-agenda-files-menu ()
21187 (let ((bl (buffer-list)))
21188 (save-excursion
21189 (while bl
21190 (set-buffer (pop bl))
21191 (if (derived-mode-p 'org-mode) (setq bl nil)))
21192 (when (derived-mode-p 'org-mode)
21193 (easy-menu-change
21194 '("Org") "File List for Agenda"
21195 (append
21196 (list
21197 ["Edit File List" (org-edit-agenda-file-list) t]
21198 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21199 ["Remove Current File from List" org-remove-file t]
21200 ["Cycle through agenda files" org-cycle-agenda-files t]
21201 ["Occur in all agenda files" org-occur-in-agenda-files t]
21202 "--")
21203 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21205 ;;;; Documentation
21207 (defun org-require-autoloaded-modules ()
21208 (interactive)
21209 (mapc 'require
21210 '(org-agenda org-archive org-attach org-clock org-colview org-id
21211 org-table org-timer)))
21213 ;;;###autoload
21214 (defun org-reload (&optional uncompiled)
21215 "Reload all org lisp files.
21216 With prefix arg UNCOMPILED, load the uncompiled versions."
21217 (interactive "P")
21218 (require 'loadhist)
21219 (let* ((org-dir (org-find-library-dir "org"))
21220 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21221 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21222 (remove-re (mapconcat 'identity
21223 (mapcar (lambda (f) (concat "^" f "$"))
21224 (list (if (featurep 'xemacs)
21225 "org-colview"
21226 "org-colview-xemacs")
21227 "org" "org-loaddefs" "org-version"))
21228 "\\|"))
21229 (feats (delete-dups
21230 (mapcar 'file-name-sans-extension
21231 (mapcar 'file-name-nondirectory
21232 (delq nil
21233 (mapcar 'feature-file
21234 features))))))
21235 (lfeat (append
21236 (sort
21237 (setq feats
21238 (delq nil (mapcar
21239 (lambda (f)
21240 (if (and (string-match feature-re f)
21241 (not (string-match remove-re f)))
21242 f nil))
21243 feats)))
21244 'string-lessp)
21245 (list "org-version" "org")))
21246 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21247 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21248 load-uncore load-misses)
21249 (setq load-misses
21250 (delq 't
21251 (mapcar (lambda (f)
21252 (or (org-load-noerror-mustsuffix (concat org-dir f))
21253 (and (string= org-dir contrib-dir)
21254 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21255 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21256 (add-to-list 'load-uncore f 'append)
21259 lfeat)))
21260 (if load-uncore
21261 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21262 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21263 (if load-misses
21264 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21265 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21266 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21268 ;;;###autoload
21269 (defun org-customize ()
21270 "Call the customize function with org as argument."
21271 (interactive)
21272 (org-load-modules-maybe)
21273 (org-require-autoloaded-modules)
21274 (customize-browse 'org))
21276 (defun org-create-customize-menu ()
21277 "Create a full customization menu for Org-mode, insert it into the menu."
21278 (interactive)
21279 (org-load-modules-maybe)
21280 (org-require-autoloaded-modules)
21281 (if (fboundp 'customize-menu-create)
21282 (progn
21283 (easy-menu-change
21284 '("Org") "Customize"
21285 `(["Browse Org group" org-customize t]
21286 "--"
21287 ,(customize-menu-create 'org)
21288 ["Set" Custom-set t]
21289 ["Save" Custom-save t]
21290 ["Reset to Current" Custom-reset-current t]
21291 ["Reset to Saved" Custom-reset-saved t]
21292 ["Reset to Standard Settings" Custom-reset-standard t]))
21293 (message "\"Org\"-menu now contains full customization menu"))
21294 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21296 ;;;; Miscellaneous stuff
21298 ;;; Generally useful functions
21300 (defun org-get-at-bol (property)
21301 "Get text property PROPERTY at beginning of line."
21302 (get-text-property (point-at-bol) property))
21304 (defun org-find-text-property-in-string (prop s)
21305 "Return the first non-nil value of property PROP in string S."
21306 (or (get-text-property 0 prop s)
21307 (get-text-property (or (next-single-property-change 0 prop s) 0)
21308 prop s)))
21310 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21311 "Display the given MESSAGE as a warning."
21312 (if (fboundp 'display-warning)
21313 (display-warning 'org message
21314 (if (featurep 'xemacs) 'warning :warning))
21315 (let ((buf (get-buffer-create "*Org warnings*")))
21316 (with-current-buffer buf
21317 (goto-char (point-max))
21318 (insert "Warning (Org): " message)
21319 (unless (bolp)
21320 (newline)))
21321 (display-buffer buf)
21322 (sit-for 0))))
21324 (defun org-eval (form)
21325 "Eval FORM and return result."
21326 (condition-case error
21327 (eval form)
21328 (error (format "%%![Error: %s]" error))))
21330 (defun org-in-clocktable-p ()
21331 "Check if the cursor is in a clocktable."
21332 (let ((pos (point)) start)
21333 (save-excursion
21334 (end-of-line 1)
21335 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21336 (setq start (match-beginning 0))
21337 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21338 (>= (match-end 0) pos)
21339 start))))
21341 (defun org-in-commented-line ()
21342 "Is point in a line starting with `#'?"
21343 (equal (char-after (point-at-bol)) ?#))
21345 (defun org-in-indented-comment-line ()
21346 "Is point in a line starting with `#' after some white space?"
21347 (save-excursion
21348 (save-match-data
21349 (goto-char (point-at-bol))
21350 (looking-at "[ \t]*#"))))
21352 (defun org-in-verbatim-emphasis ()
21353 (save-match-data
21354 (and (org-in-regexp org-emph-re 2)
21355 (>= (point) (match-beginning 3))
21356 (<= (point) (match-end 4))
21357 (member (match-string 3) '("=" "~")))))
21359 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21360 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21361 (if (and marker (marker-buffer marker)
21362 (buffer-live-p (marker-buffer marker)))
21363 (progn
21364 (org-pop-to-buffer-same-window (marker-buffer marker))
21365 (if (or (> marker (point-max)) (< marker (point-min)))
21366 (widen))
21367 (goto-char marker)
21368 (org-show-context 'org-goto))
21369 (if bookmark
21370 (bookmark-jump bookmark)
21371 (error "Cannot find location"))))
21373 (defun org-quote-csv-field (s)
21374 "Quote field for inclusion in CSV material."
21375 (if (string-match "[\",]" s)
21376 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21379 (defun org-force-self-insert (N)
21380 "Needed to enforce self-insert under remapping."
21381 (interactive "p")
21382 (self-insert-command N))
21384 (defun org-string-width (s)
21385 "Compute width of string, ignoring invisible characters.
21386 This ignores character with invisibility property `org-link', and also
21387 characters with property `org-cwidth', because these will become invisible
21388 upon the next fontification round."
21389 (let (b l)
21390 (when (or (eq t buffer-invisibility-spec)
21391 (assq 'org-link buffer-invisibility-spec))
21392 (while (setq b (text-property-any 0 (length s)
21393 'invisible 'org-link s))
21394 (setq s (concat (substring s 0 b)
21395 (substring s (or (next-single-property-change
21396 b 'invisible s) (length s)))))))
21397 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21398 (setq s (concat (substring s 0 b)
21399 (substring s (or (next-single-property-change
21400 b 'org-cwidth s) (length s))))))
21401 (setq l (string-width s) b -1)
21402 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21403 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21406 (defun org-shorten-string (s maxlength)
21407 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21408 If the string is shorter or has length MAXLENGTH, just return the
21409 original string. If it is longer, the functions finds a space in the
21410 string, breaks this string off at that locations and adds three dots
21411 as ellipsis. Including the ellipsis, the string will not be longer
21412 than MAXLENGTH. If finding a good breaking point in the string does
21413 not work, the string is just chopped off in the middle of a word
21414 if necessary."
21415 (if (<= (length s) maxlength)
21417 (let* ((n (max (- maxlength 4) 1))
21418 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21419 (if (string-match re s)
21420 (concat (match-string 1 s) "...")
21421 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21423 (defun org-get-indentation (&optional line)
21424 "Get the indentation of the current line, interpreting tabs.
21425 When LINE is given, assume it represents a line and compute its indentation."
21426 (if line
21427 (if (string-match "^ *" (org-remove-tabs line))
21428 (match-end 0))
21429 (save-excursion
21430 (beginning-of-line 1)
21431 (skip-chars-forward " \t")
21432 (current-column))))
21434 (defun org-get-string-indentation (s)
21435 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21436 (let ((n -1) (i 0) (w tab-width) c)
21437 (catch 'exit
21438 (while (< (setq n (1+ n)) (length s))
21439 (setq c (aref s n))
21440 (cond ((= c ?\ ) (setq i (1+ i)))
21441 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21442 (t (throw 'exit t)))))
21445 (defun org-remove-tabs (s &optional width)
21446 "Replace tabulators in S with spaces.
21447 Assumes that s is a single line, starting in column 0."
21448 (setq width (or width tab-width))
21449 (while (string-match "\t" s)
21450 (setq s (replace-match
21451 (make-string
21452 (- (* width (/ (+ (match-beginning 0) width) width))
21453 (match-beginning 0)) ?\ )
21454 t t s)))
21457 (defun org-fix-indentation (line ind)
21458 "Fix indentation in LINE.
21459 IND is a cons cell with target and minimum indentation.
21460 If the current indentation in LINE is smaller than the minimum,
21461 leave it alone. If it is larger than ind, set it to the target."
21462 (let* ((l (org-remove-tabs line))
21463 (i (org-get-indentation l))
21464 (i1 (car ind)) (i2 (cdr ind)))
21465 (if (>= i i2) (setq l (substring line i2)))
21466 (if (> i1 0)
21467 (concat (make-string i1 ?\ ) l)
21468 l)))
21470 (defun org-remove-indentation (code &optional n)
21471 "Remove the maximum common indentation from the lines in CODE.
21472 N may optionally be the number of spaces to remove."
21473 (with-temp-buffer
21474 (insert code)
21475 (org-do-remove-indentation n)
21476 (buffer-string)))
21478 (defun org-do-remove-indentation (&optional n)
21479 "Remove the maximum common indentation from the buffer."
21480 (untabify (point-min) (point-max))
21481 (let ((min 10000) re)
21482 (if n
21483 (setq min n)
21484 (goto-char (point-min))
21485 (while (re-search-forward "^ *[^ \n]" nil t)
21486 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21487 (unless (or (= min 0) (= min 10000))
21488 (setq re (format "^ \\{%d\\}" min))
21489 (goto-char (point-min))
21490 (while (re-search-forward re nil t)
21491 (replace-match "")
21492 (end-of-line 1))
21493 min)))
21495 (defun org-fill-template (template alist)
21496 "Find each %key of ALIST in TEMPLATE and replace it."
21497 (let ((case-fold-search nil)
21498 entry key value)
21499 (setq alist (sort (copy-sequence alist)
21500 (lambda (a b) (< (length (car a)) (length (car b))))))
21501 (while (setq entry (pop alist))
21502 (setq template
21503 (replace-regexp-in-string
21504 (concat "%" (regexp-quote (car entry)))
21505 (or (cdr entry) "") template t t)))
21506 template))
21508 (defun org-base-buffer (buffer)
21509 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21510 (if (not buffer)
21511 buffer
21512 (or (buffer-base-buffer buffer)
21513 buffer)))
21515 (defun org-trim (s)
21516 "Remove whitespace at beginning and end of string."
21517 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21518 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21521 (defun org-wrap (string &optional width lines)
21522 "Wrap string to either a number of lines, or a width in characters.
21523 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21524 that costs. If there is a word longer than WIDTH, the text is actually
21525 wrapped to the length of that word.
21526 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21527 many lines, whatever width that takes.
21528 The return value is a list of lines, without newlines at the end."
21529 (let* ((words (org-split-string string "[ \t\n]+"))
21530 (maxword (apply 'max (mapcar 'org-string-width words)))
21531 w ll)
21532 (cond (width
21533 (org-do-wrap words (max maxword width)))
21534 (lines
21535 (setq w maxword)
21536 (setq ll (org-do-wrap words maxword))
21537 (if (<= (length ll) lines)
21539 (setq ll words)
21540 (while (> (length ll) lines)
21541 (setq w (1+ w))
21542 (setq ll (org-do-wrap words w)))
21543 ll))
21544 (t (error "Cannot wrap this")))))
21546 (defun org-do-wrap (words width)
21547 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21548 (let (lines line)
21549 (while words
21550 (setq line (pop words))
21551 (while (and words (< (+ (length line) (length (car words))) width))
21552 (setq line (concat line " " (pop words))))
21553 (setq lines (push line lines)))
21554 (nreverse lines)))
21556 (defun org-split-string (string &optional separators)
21557 "Splits STRING into substrings at SEPARATORS.
21558 No empty strings are returned if there are matches at the beginning
21559 and end of string."
21560 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21561 (start 0)
21562 notfirst
21563 (list nil))
21564 (while (and (string-match rexp string
21565 (if (and notfirst
21566 (= start (match-beginning 0))
21567 (< start (length string)))
21568 (1+ start) start))
21569 (< (match-beginning 0) (length string)))
21570 (setq notfirst t)
21571 (or (eq (match-beginning 0) 0)
21572 (and (eq (match-beginning 0) (match-end 0))
21573 (eq (match-beginning 0) start))
21574 (setq list
21575 (cons (substring string start (match-beginning 0))
21576 list)))
21577 (setq start (match-end 0)))
21578 (or (eq start (length string))
21579 (setq list
21580 (cons (substring string start)
21581 list)))
21582 (nreverse list)))
21584 (defun org-quote-vert (s)
21585 "Replace \"|\" with \"\\vert\"."
21586 (while (string-match "|" s)
21587 (setq s (replace-match "\\vert" t t s)))
21590 (defun org-uuidgen-p (s)
21591 "Is S an ID created by UUIDGEN?"
21592 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21594 (defun org-in-src-block-p (&optional inside)
21595 "Whether point is in a code source block.
21596 When INSIDE is non-nil, don't consider we are within a src block
21597 when point is at #+BEGIN_SRC or #+END_SRC."
21598 (let ((case-fold-search t) ov)
21599 (or (and (setq ov (overlays-at (point)))
21600 (memq 'org-block-background
21601 (overlay-properties (car ov))))
21602 (and (not inside)
21603 (save-match-data
21604 (save-excursion
21605 (beginning-of-line)
21606 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21608 (defun org-context ()
21609 "Return a list of contexts of the current cursor position.
21610 If several contexts apply, all are returned.
21611 Each context entry is a list with a symbol naming the context, and
21612 two positions indicating start and end of the context. Possible
21613 contexts are:
21615 :headline anywhere in a headline
21616 :headline-stars on the leading stars in a headline
21617 :todo-keyword on a TODO keyword (including DONE) in a headline
21618 :tags on the TAGS in a headline
21619 :priority on the priority cookie in a headline
21620 :item on the first line of a plain list item
21621 :item-bullet on the bullet/number of a plain list item
21622 :checkbox on the checkbox in a plain list item
21623 :table in an org-mode table
21624 :table-special on a special filed in a table
21625 :table-table in a table.el table
21626 :clocktable in a clocktable
21627 :src-block in a source block
21628 :link on a hyperlink
21629 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21630 :target on a <<target>>
21631 :radio-target on a <<<radio-target>>>
21632 :latex-fragment on a LaTeX fragment
21633 :latex-preview on a LaTeX fragment with overlaid preview image
21635 This function expects the position to be visible because it uses font-lock
21636 faces as a help to recognize the following contexts: :table-special, :link,
21637 and :keyword."
21638 (let* ((f (get-text-property (point) 'face))
21639 (faces (if (listp f) f (list f)))
21640 (case-fold-search t)
21641 (p (point)) clist o)
21642 ;; First the large context
21643 (cond
21644 ((org-at-heading-p t)
21645 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21646 (when (progn
21647 (beginning-of-line 1)
21648 (looking-at org-todo-line-tags-regexp))
21649 (push (org-point-in-group p 1 :headline-stars) clist)
21650 (push (org-point-in-group p 2 :todo-keyword) clist)
21651 (push (org-point-in-group p 4 :tags) clist))
21652 (goto-char p)
21653 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21654 (if (looking-at "\\[#[A-Z0-9]\\]")
21655 (push (org-point-in-group p 0 :priority) clist)))
21657 ((org-at-item-p)
21658 (push (org-point-in-group p 2 :item-bullet) clist)
21659 (push (list :item (point-at-bol)
21660 (save-excursion (org-end-of-item) (point)))
21661 clist)
21662 (and (org-at-item-checkbox-p)
21663 (push (org-point-in-group p 0 :checkbox) clist)))
21665 ((org-at-table-p)
21666 (push (list :table (org-table-begin) (org-table-end)) clist)
21667 (if (memq 'org-formula faces)
21668 (push (list :table-special
21669 (previous-single-property-change p 'face)
21670 (next-single-property-change p 'face)) clist)))
21671 ((org-at-table-p 'any)
21672 (push (list :table-table) clist)))
21673 (goto-char p)
21675 (let ((case-fold-search t))
21676 ;; New the "medium" contexts: clocktables, source blocks
21677 (cond ((org-in-clocktable-p)
21678 (push (list :clocktable
21679 (and (or (looking-at "#\\+BEGIN: clocktable")
21680 (search-backward "#+BEGIN: clocktable" nil t))
21681 (match-beginning 0))
21682 (and (re-search-forward "#\\+END:?" nil t)
21683 (match-end 0))) clist))
21684 ((org-in-src-block-p)
21685 (push (list :src-block
21686 (and (or (looking-at "#\\+BEGIN_SRC")
21687 (search-backward "#+BEGIN_SRC" nil t))
21688 (match-beginning 0))
21689 (and (search-forward "#+END_SRC" nil t)
21690 (match-beginning 0))) clist))))
21691 (goto-char p)
21693 ;; Now the small context
21694 (cond
21695 ((org-at-timestamp-p)
21696 (push (org-point-in-group p 0 :timestamp) clist))
21697 ((memq 'org-link faces)
21698 (push (list :link
21699 (previous-single-property-change p 'face)
21700 (next-single-property-change p 'face)) clist))
21701 ((memq 'org-special-keyword faces)
21702 (push (list :keyword
21703 (previous-single-property-change p 'face)
21704 (next-single-property-change p 'face)) clist))
21705 ((org-at-target-p)
21706 (push (org-point-in-group p 0 :target) clist)
21707 (goto-char (1- (match-beginning 0)))
21708 (if (looking-at org-radio-target-regexp)
21709 (push (org-point-in-group p 0 :radio-target) clist))
21710 (goto-char p))
21711 ((setq o (car (delq nil
21712 (mapcar
21713 (lambda (x)
21714 (if (memq x org-latex-fragment-image-overlays) x))
21715 (overlays-at (point))))))
21716 (push (list :latex-fragment
21717 (overlay-start o) (overlay-end o)) clist)
21718 (push (list :latex-preview
21719 (overlay-start o) (overlay-end o)) clist))
21720 ((org-inside-LaTeX-fragment-p)
21721 ;; FIXME: positions wrong.
21722 (push (list :latex-fragment (point) (point)) clist)))
21724 (setq clist (nreverse (delq nil clist)))
21725 clist))
21727 ;; FIXME: Compare with at-regexp-p Do we need both?
21728 (defun org-in-regexp (re &optional nlines visually)
21729 "Check if point is inside a match of regexp.
21730 Normally only the current line is checked, but you can include NLINES extra
21731 lines both before and after point into the search.
21732 If VISUALLY is set, require that the cursor is not after the match but
21733 really on, so that the block visually is on the match."
21734 (catch 'exit
21735 (let ((pos (point))
21736 (eol (point-at-eol (+ 1 (or nlines 0))))
21737 (inc (if visually 1 0)))
21738 (save-excursion
21739 (beginning-of-line (- 1 (or nlines 0)))
21740 (while (re-search-forward re eol t)
21741 (if (and (<= (match-beginning 0) pos)
21742 (>= (+ inc (match-end 0)) pos))
21743 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21745 (defun org-at-regexp-p (regexp)
21746 "Is point inside a match of REGEXP in the current line?"
21747 (catch 'exit
21748 (save-excursion
21749 (let ((pos (point)) (end (point-at-eol)))
21750 (beginning-of-line 1)
21751 (while (re-search-forward regexp end t)
21752 (if (and (<= (match-beginning 0) pos)
21753 (>= (match-end 0) pos))
21754 (throw 'exit t)))
21755 nil))))
21757 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21758 "Non-nil when point is between matches of START-RE and END-RE.
21760 Also return a non-nil value when point is on one of the matches.
21762 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21763 buffer positions. Default values are the positions of headlines
21764 surrounding the point.
21766 The functions returns a cons cell whose car (resp. cdr) is the
21767 position before START-RE (resp. after END-RE)."
21768 (save-match-data
21769 (let ((pos (point))
21770 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21771 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21772 beg end)
21773 (save-excursion
21774 ;; Point is on a block when on START-RE or if START-RE can be
21775 ;; found before it...
21776 (and (or (org-at-regexp-p start-re)
21777 (re-search-backward start-re limit-up t))
21778 (setq beg (match-beginning 0))
21779 ;; ... and END-RE after it...
21780 (goto-char (match-end 0))
21781 (re-search-forward end-re limit-down t)
21782 (> (setq end (match-end 0)) pos)
21783 ;; ... without another START-RE in-between.
21784 (goto-char (match-beginning 0))
21785 (not (re-search-backward start-re (1+ beg) t))
21786 ;; Return value.
21787 (cons beg end))))))
21789 (defun org-in-block-p (names)
21790 "Non-nil when point belongs to a block whose name belongs to NAMES.
21792 NAMES is a list of strings containing names of blocks.
21794 Return first block name matched, or nil. Beware that in case of
21795 nested blocks, the returned name may not belong to the closest
21796 block from point."
21797 (save-match-data
21798 (catch 'exit
21799 (let ((case-fold-search t)
21800 (lim-up (save-excursion (outline-previous-heading)))
21801 (lim-down (save-excursion (outline-next-heading))))
21802 (mapc (lambda (name)
21803 (let ((n (regexp-quote name)))
21804 (when (org-between-regexps-p
21805 (concat "^[ \t]*#\\+begin_" n)
21806 (concat "^[ \t]*#\\+end_" n)
21807 lim-up lim-down)
21808 (throw 'exit n))))
21809 names))
21810 nil)))
21812 (defun org-in-drawer-p ()
21813 "Non-nil if point is within a drawer.
21814 If point is within a drawer, return it, as parsed data."
21815 (let ((element (save-match-data (org-element-at-point))))
21816 (while (and element (not (memq (org-element-type element)
21817 '(drawer property-drawer))))
21818 (setq element (org-element-property :parent element)))
21819 element))
21821 (defun org-occur-in-agenda-files (regexp &optional nlines)
21822 "Call `multi-occur' with buffers for all agenda files."
21823 (interactive "sOrg-files matching: \np")
21824 (let* ((files (org-agenda-files))
21825 (tnames (mapcar 'file-truename files))
21826 (extra org-agenda-text-search-extra-files)
21828 (when (eq (car extra) 'agenda-archives)
21829 (setq extra (cdr extra))
21830 (setq files (org-add-archive-files files)))
21831 (while (setq f (pop extra))
21832 (unless (member (file-truename f) tnames)
21833 (add-to-list 'files f 'append)
21834 (add-to-list 'tnames (file-truename f) 'append)))
21835 (multi-occur
21836 (mapcar (lambda (x)
21837 (with-current-buffer
21838 (or (get-file-buffer x) (find-file-noselect x))
21839 (widen)
21840 (current-buffer)))
21841 files)
21842 regexp)))
21844 (if (boundp 'occur-mode-find-occurrence-hook)
21845 ;; Emacs 23
21846 (add-hook 'occur-mode-find-occurrence-hook
21847 (lambda ()
21848 (when (derived-mode-p 'org-mode)
21849 (org-reveal))))
21850 ;; Emacs 22
21851 (defadvice occur-mode-goto-occurrence
21852 (after org-occur-reveal activate)
21853 (and (derived-mode-p 'org-mode) (org-reveal)))
21854 (defadvice occur-mode-goto-occurrence-other-window
21855 (after org-occur-reveal activate)
21856 (and (derived-mode-p 'org-mode) (org-reveal)))
21857 (defadvice occur-mode-display-occurrence
21858 (after org-occur-reveal activate)
21859 (when (derived-mode-p 'org-mode)
21860 (let ((pos (occur-mode-find-occurrence)))
21861 (with-current-buffer (marker-buffer pos)
21862 (save-excursion
21863 (goto-char pos)
21864 (org-reveal)))))))
21866 (defun org-occur-link-in-agenda-files ()
21867 "Create a link and search for it in the agendas.
21868 The link is not stored in `org-stored-links', it is just created
21869 for the search purpose."
21870 (interactive)
21871 (let ((link (condition-case nil
21872 (org-store-link nil)
21873 (error "Unable to create a link to here"))))
21874 (org-occur-in-agenda-files (regexp-quote link))))
21876 (defun org-reverse-string (string)
21877 "Return the reverse of STRING."
21878 (apply 'string (reverse (string-to-list string))))
21880 (defun org-uniquify-alist (alist)
21881 "Merge elements of ALIST with the same key.
21883 For example, in this alist:
21885 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21886 => '((a 1 3) (b 2))
21888 merge (a 1) and (a 3) into (a 1 3).
21890 The function returns the new ALIST."
21891 (let (rtn)
21892 (mapc
21893 (lambda (e)
21894 (let (n)
21895 (if (not (assoc (car e) rtn))
21896 (push e rtn)
21897 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21898 (setq rtn (assq-delete-all (car e) rtn))
21899 (push n rtn))))
21900 alist)
21901 rtn))
21903 (defun org-delete-all (elts list)
21904 "Remove all elements in ELTS from LIST."
21905 (while elts
21906 (setq list (delete (pop elts) list)))
21907 list)
21909 (defun org-count (cl-item cl-seq)
21910 "Count the number of occurrences of ITEM in SEQ.
21911 Taken from `count' in cl-seq.el with all keyword arguments removed."
21912 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21913 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21914 (while (< cl-start cl-end)
21915 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21916 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21917 (setq cl-start (1+ cl-start)))
21918 cl-count))
21920 (defun org-remove-if (predicate seq)
21921 "Remove everything from SEQ that fulfills PREDICATE."
21922 (let (res e)
21923 (while seq
21924 (setq e (pop seq))
21925 (if (not (funcall predicate e)) (push e res)))
21926 (nreverse res)))
21928 (defun org-remove-if-not (predicate seq)
21929 "Remove everything from SEQ that does not fulfill PREDICATE."
21930 (let (res e)
21931 (while seq
21932 (setq e (pop seq))
21933 (if (funcall predicate e) (push e res)))
21934 (nreverse res)))
21936 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21937 "Reduce two-argument FUNCTION across SEQ.
21938 Taken from `reduce' in cl-seq.el with all keyword arguments but
21939 \":initial-value\" removed."
21940 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21941 (cadr (memq :initial-value cl-keys)))
21942 (cl-seq (pop cl-seq))
21943 (t (funcall cl-func)))))
21944 (while cl-seq
21945 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21946 cl-accum))
21948 (defun org-every (pred seq)
21949 "Return true if PREDICATE is true of every element of SEQ.
21950 Adapted from `every' in cl.el."
21951 (catch 'org-every
21952 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21955 (defun org-some (pred seq)
21956 "Return true if PREDICATE is true of any element of SEQ.
21957 Adapted from `some' in cl.el."
21958 (catch 'org-some
21959 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21960 nil))
21962 (defun org-back-over-empty-lines ()
21963 "Move backwards over whitespace, to the beginning of the first empty line.
21964 Returns the number of empty lines passed."
21965 (let ((pos (point)))
21966 (if (cdr (assoc 'heading org-blank-before-new-entry))
21967 (skip-chars-backward " \t\n\r")
21968 (unless (eobp)
21969 (forward-line -1)))
21970 (beginning-of-line 2)
21971 (goto-char (min (point) pos))
21972 (count-lines (point) pos)))
21974 (defun org-skip-whitespace ()
21975 (skip-chars-forward " \t\n\r"))
21977 (defun org-point-in-group (point group &optional context)
21978 "Check if POINT is in match-group GROUP.
21979 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21980 match. If the match group does not exist or point is not inside it,
21981 return nil."
21982 (and (match-beginning group)
21983 (>= point (match-beginning group))
21984 (<= point (match-end group))
21985 (if context
21986 (list context (match-beginning group) (match-end group))
21987 t)))
21989 (defun org-switch-to-buffer-other-window (&rest args)
21990 "Switch to buffer in a second window on the current frame.
21991 In particular, do not allow pop-up frames.
21992 Returns the newly created buffer."
21993 (org-no-popups
21994 (apply 'switch-to-buffer-other-window args)))
21996 (defun org-combine-plists (&rest plists)
21997 "Create a single property list from all plists in PLISTS.
21998 The process starts by copying the first list, and then setting properties
21999 from the other lists. Settings in the last list are the most significant
22000 ones and overrule settings in the other lists."
22001 (let ((rtn (copy-sequence (pop plists)))
22002 p v ls)
22003 (while plists
22004 (setq ls (pop plists))
22005 (while ls
22006 (setq p (pop ls) v (pop ls))
22007 (setq rtn (plist-put rtn p v))))
22008 rtn))
22010 (defun org-replace-escapes (string table)
22011 "Replace %-escapes in STRING with values in TABLE.
22012 TABLE is an association list with keys like \"%a\" and string values.
22013 The sequences in STRING may contain normal field width and padding information,
22014 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22015 so values can contain further %-escapes if they are define later in TABLE."
22016 (let ((tbl (copy-alist table))
22017 (case-fold-search nil)
22018 (pchg 0)
22019 e re rpl)
22020 (while (setq e (pop tbl))
22021 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22022 (when (and (cdr e) (string-match re (cdr e)))
22023 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22024 (safe "SREF"))
22025 (add-text-properties 0 3 (list 'sref sref) safe)
22026 (setcdr e (replace-match safe t t (cdr e)))))
22027 (while (string-match re string)
22028 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22029 (cdr e)))
22030 (setq string (replace-match rpl t t string))))
22031 (while (setq pchg (next-property-change pchg string))
22032 (let ((sref (get-text-property pchg 'sref string)))
22033 (when (and sref (string-match "SREF" string pchg))
22034 (setq string (replace-match sref t t string)))))
22035 string))
22037 (defun org-sublist (list start end)
22038 "Return a section of LIST, from START to END.
22039 Counting starts at 1."
22040 (let (rtn (c start))
22041 (setq list (nthcdr (1- start) list))
22042 (while (and list (<= c end))
22043 (push (pop list) rtn)
22044 (setq c (1+ c)))
22045 (nreverse rtn)))
22047 (defun org-find-base-buffer-visiting (file)
22048 "Like `find-buffer-visiting' but always return the base buffer and
22049 not an indirect buffer."
22050 (let ((buf (or (get-file-buffer file)
22051 (find-buffer-visiting file))))
22052 (if buf
22053 (or (buffer-base-buffer buf) buf)
22054 nil)))
22056 (defun org-image-file-name-regexp (&optional extensions)
22057 "Return regexp matching the file names of images.
22058 If EXTENSIONS is given, only match these."
22059 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22060 (image-file-name-regexp)
22061 (let ((image-file-name-extensions
22062 (or extensions
22063 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22064 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22065 (concat "\\."
22066 (regexp-opt (nconc (mapcar 'upcase
22067 image-file-name-extensions)
22068 image-file-name-extensions)
22070 "\\'"))))
22072 (defun org-file-image-p (file &optional extensions)
22073 "Return non-nil if FILE is an image."
22074 (save-match-data
22075 (string-match (org-image-file-name-regexp extensions) file)))
22077 (defun org-get-cursor-date (&optional with-time)
22078 "Return the date at cursor in as a time.
22079 This works in the calendar and in the agenda, anywhere else it just
22080 returns the current time.
22081 If WITH-TIME is non-nil, returns the time of the event at point (in
22082 the agenda) or the current time of the day."
22083 (let (date day defd tp tm hod mod)
22084 (when with-time
22085 (setq tp (get-text-property (point) 'time))
22086 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22087 (setq hod (string-to-number (match-string 1 tp))
22088 mod (string-to-number (match-string 2 tp))))
22089 (or tp (setq hod (nth 2 (decode-time (current-time)))
22090 mod (nth 1 (decode-time (current-time))))))
22091 (cond
22092 ((eq major-mode 'calendar-mode)
22093 (setq date (calendar-cursor-to-date)
22094 defd (encode-time 0 (or mod 0) (or hod 0)
22095 (nth 1 date) (nth 0 date) (nth 2 date))))
22096 ((eq major-mode 'org-agenda-mode)
22097 (setq day (get-text-property (point) 'day))
22098 (if day
22099 (setq date (calendar-gregorian-from-absolute day)
22100 defd (encode-time 0 (or mod 0) (or hod 0)
22101 (nth 1 date) (nth 0 date) (nth 2 date))))))
22102 (or defd (current-time))))
22104 (defun org-mark-subtree (&optional up)
22105 "Mark the current subtree.
22106 This puts point at the start of the current subtree, and mark at
22107 the end. If a numeric prefix UP is given, move up into the
22108 hierarchy of headlines by UP levels before marking the subtree."
22109 (interactive "P")
22110 (org-with-limited-levels
22111 (cond ((org-at-heading-p) (beginning-of-line))
22112 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22113 (t (outline-previous-visible-heading 1))))
22114 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22115 (if (org-called-interactively-p 'any)
22116 (call-interactively 'org-mark-element)
22117 (org-mark-element)))
22120 ;;; Indentation
22122 (defun org-indent-line ()
22123 "Indent line depending on context."
22124 (interactive)
22125 (let* ((pos (point))
22126 (itemp (org-at-item-p))
22127 (case-fold-search t)
22128 (org-drawer-regexp (or org-drawer-regexp "\000"))
22129 (inline-task-p (and (featurep 'org-inlinetask)
22130 (org-inlinetask-in-task-p)))
22131 (inline-re (and inline-task-p
22132 (org-inlinetask-outline-regexp)))
22133 column)
22134 (if (and orgstruct-is-++ (eq pos (point)))
22135 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22136 (indent-according-to-mode))
22137 (beginning-of-line 1)
22138 (cond
22139 ;; Headings
22140 ((looking-at org-outline-regexp) (setq column 0))
22141 ;; Footnote definition
22142 ((looking-at org-footnote-definition-re) (setq column 0))
22143 ;; Literal examples
22144 ((looking-at "[ \t]*:\\( \\|$\\)")
22145 (setq column (org-get-indentation))) ; do nothing
22146 ;; Lists
22147 ((ignore-errors (goto-char (org-in-item-p)))
22148 (setq column (if itemp
22149 (org-get-indentation)
22150 (org-list-item-body-column (point))))
22151 (goto-char pos))
22152 ;; Drawers
22153 ((and (looking-at "[ \t]*:END:")
22154 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22155 (save-excursion
22156 (goto-char (1- (match-beginning 1)))
22157 (setq column (current-column))))
22158 ;; Special blocks
22159 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22160 (save-excursion
22161 (re-search-backward
22162 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22163 (setq column (org-get-indentation (match-string 0))))
22164 ((and (not (looking-at "[ \t]*#\\+begin_"))
22165 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22166 (save-excursion
22167 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22168 (setq column
22169 (cond ((equal (downcase (match-string 1)) "src")
22170 ;; src blocks: let `org-edit-src-exit' handle them
22171 (org-get-indentation))
22172 ((equal (downcase (match-string 1)) "example")
22173 (max (org-get-indentation)
22174 (org-get-indentation (match-string 0))))
22176 (org-get-indentation (match-string 0))))))
22177 ;; This line has nothing special, look at the previous relevant
22178 ;; line to compute indentation
22180 (beginning-of-line 0)
22181 (while (and (not (bobp))
22182 (not (looking-at org-table-line-regexp))
22183 (not (looking-at org-drawer-regexp))
22184 ;; When point started in an inline task, do not move
22185 ;; above task starting line.
22186 (not (and inline-task-p (looking-at inline-re)))
22187 ;; Skip drawers, blocks, empty lines, verbatim,
22188 ;; comments, tables, footnotes definitions, lists,
22189 ;; inline tasks.
22190 (or (and (looking-at "[ \t]*:END:")
22191 (re-search-backward org-drawer-regexp nil t))
22192 (and (looking-at "[ \t]*#\\+end_")
22193 (re-search-backward "[ \t]*#\\+begin_"nil t))
22194 (looking-at "[ \t]*[\n:#|]")
22195 (looking-at org-footnote-definition-re)
22196 (and (not inline-task-p)
22197 (featurep 'org-inlinetask)
22198 (org-inlinetask-in-task-p)
22199 (or (org-inlinetask-goto-beginning) t))))
22200 (beginning-of-line 0))
22201 (cond
22202 ;; There was a list item above.
22203 ((ignore-errors (goto-char (org-in-item-p)))
22204 (goto-char (org-list-get-top-point (org-list-struct)))
22205 (setq column (org-get-indentation)))
22206 ;; There was an heading above.
22207 ((looking-at "\\*+[ \t]+")
22208 (if (not org-adapt-indentation)
22209 (setq column 0)
22210 (goto-char (match-end 0))
22211 (setq column (current-column))))
22212 ;; A drawer had started and is unfinished
22213 ((looking-at org-drawer-regexp)
22214 (goto-char (1- (match-beginning 1)))
22215 (setq column (current-column)))
22216 ;; Else, nothing noticeable found: get indentation and go on.
22217 (t (setq column (org-get-indentation))))))
22218 ;; Now apply indentation and move cursor accordingly
22219 (goto-char pos)
22220 (if (<= (current-column) (current-indentation))
22221 (org-indent-line-to column)
22222 (save-excursion (org-indent-line-to column)))
22223 ;; Special polishing for properties, see `org-property-format'
22224 (setq column (current-column))
22225 (beginning-of-line 1)
22226 (if (looking-at org-property-re)
22227 (replace-match (concat (match-string 4)
22228 (format org-property-format
22229 (match-string 1) (match-string 3)))
22230 t t))
22231 (org-move-to-column column))))
22233 (defun org-indent-drawer ()
22234 "Indent the drawer at point."
22235 (interactive)
22236 (let ((p (point))
22237 (e (and (save-excursion (re-search-forward ":END:" nil t))
22238 (match-end 0)))
22239 (folded
22240 (save-excursion
22241 (end-of-line)
22242 (when (overlays-at (point))
22243 (member 'invisible (overlay-properties
22244 (car (overlays-at (point)))))))))
22245 (when folded (org-cycle))
22246 (indent-for-tab-command)
22247 (while (and (move-beginning-of-line 2) (< (point) e))
22248 (indent-for-tab-command))
22249 (goto-char p)
22250 (when folded (org-cycle)))
22251 (message "Drawer at point indented"))
22253 (defun org-indent-block ()
22254 "Indent the block at point."
22255 (interactive)
22256 (let ((p (point))
22257 (case-fold-search t)
22258 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22259 (match-end 0)))
22260 (folded
22261 (save-excursion
22262 (end-of-line)
22263 (when (overlays-at (point))
22264 (member 'invisible (overlay-properties
22265 (car (overlays-at (point)))))))))
22266 (when folded (org-cycle))
22267 (indent-for-tab-command)
22268 (while (and (move-beginning-of-line 2) (< (point) e))
22269 (indent-for-tab-command))
22270 (goto-char p)
22271 (when folded (org-cycle)))
22272 (message "Block at point indented"))
22274 (defun org-indent-region (start end)
22275 "Indent region."
22276 (interactive "r")
22277 (save-excursion
22278 (let ((line-end (org-current-line end)))
22279 (goto-char start)
22280 (while (< (org-current-line) line-end)
22281 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22282 (t (call-interactively 'org-indent-line)))
22283 (move-beginning-of-line 2)))))
22286 ;;; Filling
22288 ;; We use our own fill-paragraph and auto-fill functions.
22290 ;; `org-fill-paragraph' relies on adaptive filling and context
22291 ;; checking. Appropriate `fill-prefix' is computed with
22292 ;; `org-adaptive-fill-function'.
22294 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22295 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22296 ;; `org-adaptive-fill-function' value. Internally,
22297 ;; `org-comment-line-break-function' breaks the line.
22299 ;; `org-setup-filling' installs filling and auto-filling related
22300 ;; variables during `org-mode' initialization.
22302 (defvar org-element-paragraph-separate) ; org-element.el
22303 (defun org-setup-filling ()
22304 (require 'org-element)
22305 ;; Prevent auto-fill from inserting unwanted new items.
22306 (when (boundp 'fill-nobreak-predicate)
22307 (org-set-local
22308 'fill-nobreak-predicate
22309 (org-uniquify
22310 (append fill-nobreak-predicate
22311 '(org-fill-line-break-nobreak-p
22312 org-fill-paragraph-with-timestamp-nobreak-p)))))
22313 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22314 (org-set-local 'paragraph-start paragraph-ending)
22315 (org-set-local 'paragraph-separate paragraph-ending))
22316 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22317 (org-set-local 'auto-fill-inhibit-regexp nil)
22318 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22319 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22320 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22322 (defun org-fill-line-break-nobreak-p ()
22323 "Non-nil when a new line at point would create an Org line break."
22324 (save-excursion
22325 (skip-chars-backward "[ \t]")
22326 (skip-chars-backward "\\\\")
22327 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22329 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22330 "Non-nil when a new line at point would split a timestamp."
22331 (and (org-at-timestamp-p t)
22332 (not (looking-at org-ts-regexp-both))))
22334 (declare-function message-in-body-p "message" ())
22335 (defvar orgtbl-line-start-regexp) ; From org-table.el
22336 (defun org-adaptive-fill-function ()
22337 "Compute a fill prefix for the current line.
22338 Return fill prefix, as a string, or nil if current line isn't
22339 meant to be filled. For convenience, if `adaptive-fill-regexp'
22340 matches in paragraphs or comments, use it."
22341 (catch 'exit
22342 (when (derived-mode-p 'message-mode)
22343 (save-excursion
22344 (beginning-of-line)
22345 (cond ((or (not (message-in-body-p))
22346 (looking-at orgtbl-line-start-regexp))
22347 (throw 'exit nil))
22348 ((looking-at message-cite-prefix-regexp)
22349 (throw 'exit (match-string-no-properties 0)))
22350 ((looking-at org-outline-regexp)
22351 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22352 (org-with-wide-buffer
22353 (let* ((p (line-beginning-position))
22354 (element (save-excursion
22355 (beginning-of-line)
22356 (or (ignore-errors (org-element-at-point))
22357 (user-error "An element cannot be parsed line %d"
22358 (line-number-at-pos (point))))))
22359 (type (org-element-type element))
22360 (post-affiliated (org-element-property :post-affiliated element)))
22361 (unless (and post-affiliated (< p post-affiliated))
22362 (case type
22363 (comment
22364 (save-excursion
22365 (beginning-of-line)
22366 (looking-at "[ \t]*")
22367 (concat (match-string 0) "# ")))
22368 (footnote-definition "")
22369 ((item plain-list)
22370 (make-string (org-list-item-body-column
22371 (or post-affiliated
22372 (org-element-property :begin element)))
22373 ? ))
22374 (paragraph
22375 ;; Fill prefix is usually the same as the current line,
22376 ;; unless the paragraph is at the beginning of an item.
22377 (let ((parent (org-element-property :parent element)))
22378 (save-excursion
22379 (beginning-of-line)
22380 (cond ((eq (org-element-type parent) 'item)
22381 (make-string (org-list-item-body-column
22382 (org-element-property :begin parent))
22383 ? ))
22384 ((and adaptive-fill-regexp
22385 ;; Locally disable
22386 ;; `adaptive-fill-function' to let
22387 ;; `fill-context-prefix' handle
22388 ;; `adaptive-fill-regexp' variable.
22389 (let (adaptive-fill-function)
22390 (fill-context-prefix
22391 post-affiliated
22392 (org-element-property :end element)))))
22393 ((looking-at "[ \t]+") (match-string 0))
22394 (t "")))))
22395 (comment-block
22396 ;; Only fill contents if P is within block boundaries.
22397 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22398 (forward-line)
22399 (point)))
22400 (cend (save-excursion
22401 (goto-char (org-element-property :end element))
22402 (skip-chars-backward " \r\t\n")
22403 (line-beginning-position))))
22404 (when (and (>= p cbeg) (< p cend))
22405 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22406 (match-string 0)
22407 ""))))))))))
22409 (declare-function message-goto-body "message" ())
22410 (defvar message-cite-prefix-regexp) ; From message.el
22411 (defun org-fill-paragraph (&optional justify)
22412 "Fill element at point, when applicable.
22414 This function only applies to comment blocks, comments, example
22415 blocks and paragraphs. Also, as a special case, re-align table
22416 when point is at one.
22418 If JUSTIFY is non-nil (interactively, with prefix argument),
22419 justify as well. If `sentence-end-double-space' is non-nil, then
22420 period followed by one space does not end a sentence, so don't
22421 break a line there. The variable `fill-column' controls the
22422 width for filling.
22424 For convenience, when point is at a plain list, an item or
22425 a footnote definition, try to fill the first paragraph within."
22426 (interactive)
22427 (if (and (derived-mode-p 'message-mode)
22428 (or (not (message-in-body-p))
22429 (save-excursion (move-beginning-of-line 1)
22430 (looking-at message-cite-prefix-regexp))))
22431 ;; First ensure filling is correct in message-mode.
22432 (let ((fill-paragraph-function
22433 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22434 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22435 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22436 (paragraph-separate
22437 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22438 (fill-paragraph nil))
22439 (with-syntax-table org-mode-transpose-word-syntax-table
22440 ;; Move to end of line in order to get the first paragraph
22441 ;; within a plain list or a footnote definition.
22442 (let ((element (save-excursion
22443 (end-of-line)
22444 (or (ignore-errors (org-element-at-point))
22445 (user-error "An element cannot be parsed line %d"
22446 (line-number-at-pos (point)))))))
22447 ;; First check if point is in a blank line at the beginning of
22448 ;; the buffer. In that case, ignore filling.
22449 (case (org-element-type element)
22450 ;; Use major mode filling function is src blocks.
22451 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22452 ;; Align Org tables, leave table.el tables as-is.
22453 (table-row (org-table-align) t)
22454 (table
22455 (when (eq (org-element-property :type element) 'org)
22456 (save-excursion
22457 (goto-char (org-element-property :post-affiliated element))
22458 (org-table-align)))
22460 (paragraph
22461 ;; Paragraphs may contain `line-break' type objects.
22462 (let ((beg (max (point-min)
22463 (org-element-property :contents-begin element)))
22464 (end (min (point-max)
22465 (org-element-property :contents-end element))))
22466 ;; Do nothing if point is at an affiliated keyword.
22467 (if (< (line-end-position) beg) t
22468 (when (derived-mode-p 'message-mode)
22469 ;; In `message-mode', do not fill following citation
22470 ;; in current paragraph nor text before message body.
22471 (let ((body-start (save-excursion (message-goto-body))))
22472 (when body-start (setq beg (max body-start beg))))
22473 (when (save-excursion
22474 (re-search-forward
22475 (concat "^" message-cite-prefix-regexp) end t))
22476 (setq end (match-beginning 0))))
22477 ;; Fill paragraph, taking line breaks into account.
22478 ;; For that, slice the paragraph using line breaks as
22479 ;; separators, and fill the parts in reverse order to
22480 ;; avoid messing with markers.
22481 (save-excursion
22482 (goto-char end)
22483 (mapc
22484 (lambda (pos)
22485 (fill-region-as-paragraph pos (point) justify)
22486 (goto-char pos))
22487 ;; Find the list of ending positions for line breaks
22488 ;; in the current paragraph. Add paragraph
22489 ;; beginning to include first slice.
22490 (nreverse
22491 (cons beg
22492 (org-element-map
22493 (org-element--parse-objects
22494 beg end nil (org-element-restriction 'paragraph))
22495 'line-break
22496 (lambda (lb) (org-element-property :end lb)))))))
22497 t)))
22498 ;; Contents of `comment-block' type elements should be
22499 ;; filled as plain text, but only if point is within block
22500 ;; markers.
22501 (comment-block
22502 (let* ((case-fold-search t)
22503 (beg (save-excursion
22504 (goto-char (org-element-property :begin element))
22505 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22506 (forward-line)
22507 (point)))
22508 (end (save-excursion
22509 (goto-char (org-element-property :end element))
22510 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22511 (line-beginning-position))))
22512 (if (or (< (point) beg) (> (point) end)) t
22513 (fill-region-as-paragraph
22514 (save-excursion (end-of-line)
22515 (re-search-backward "^[ \t]*$" beg 'move)
22516 (line-beginning-position))
22517 (save-excursion (beginning-of-line)
22518 (re-search-forward "^[ \t]*$" end 'move)
22519 (line-beginning-position))
22520 justify))))
22521 ;; Fill comments.
22522 (comment
22523 (let ((begin (org-element-property :post-affiliated element))
22524 (end (org-element-property :end element)))
22525 (when (and (>= (point) begin) (<= (point) end))
22526 (let ((begin (save-excursion
22527 (end-of-line)
22528 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22529 (progn (forward-line) (point))
22530 begin)))
22531 (end (save-excursion
22532 (end-of-line)
22533 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22534 (1- (line-beginning-position))
22535 (skip-chars-backward " \r\t\n")
22536 (line-end-position)))))
22537 ;; Do not fill comments when at a blank line.
22538 (when (> end begin)
22539 (let ((fill-prefix
22540 (save-excursion
22541 (beginning-of-line)
22542 (looking-at "[ \t]*#")
22543 (let ((comment-prefix (match-string 0)))
22544 (goto-char (match-end 0))
22545 (if (looking-at adaptive-fill-regexp)
22546 (concat comment-prefix (match-string 0))
22547 (concat comment-prefix " "))))))
22548 (save-excursion
22549 (fill-region-as-paragraph begin end justify))))))
22551 ;; Ignore every other element.
22552 (otherwise t))))))
22554 (defun org-auto-fill-function ()
22555 "Auto-fill function."
22556 ;; Check if auto-filling is meaningful.
22557 (let ((fc (current-fill-column)))
22558 (when (and fc (> (current-column) fc))
22559 (let* ((fill-prefix (org-adaptive-fill-function))
22560 ;; Enforce empty fill prefix, if required. Otherwise, it
22561 ;; will be computed again.
22562 (adaptive-fill-mode (not (equal fill-prefix ""))))
22563 (when fill-prefix (do-auto-fill))))))
22565 (defun org-comment-line-break-function (&optional soft)
22566 "Break line at point and indent, continuing comment if within one.
22567 The inserted newline is marked hard if variable
22568 `use-hard-newlines' is true, unless optional argument SOFT is
22569 non-nil."
22570 (if soft (insert-and-inherit ?\n) (newline 1))
22571 (save-excursion (forward-char -1) (delete-horizontal-space))
22572 (delete-horizontal-space)
22573 (indent-to-left-margin)
22574 (insert-before-markers-and-inherit fill-prefix))
22577 ;;; Comments
22579 ;; Org comments syntax is quite complex. It requires the entire line
22580 ;; to be just a comment. Also, even with the right syntax at the
22581 ;; beginning of line, some some elements (i.e. verse-block or
22582 ;; example-block) don't accept comments. Usual Emacs comment commands
22583 ;; cannot cope with those requirements. Therefore, Org replaces them.
22585 ;; Org still relies on `comment-dwim', but cannot trust
22586 ;; `comment-only-p'. So, `comment-region-function' and
22587 ;; `uncomment-region-function' both point
22588 ;; to`org-comment-or-uncomment-region'. Eventually,
22589 ;; `org-insert-comment' takes care of insertion of comments at the
22590 ;; beginning of line.
22592 ;; `org-setup-comments-handling' install comments related variables
22593 ;; during `org-mode' initialization.
22595 (defun org-setup-comments-handling ()
22596 (interactive)
22597 (org-set-local 'comment-use-syntax nil)
22598 (org-set-local 'comment-start "# ")
22599 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22600 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22601 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22602 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22604 (defun org-insert-comment ()
22605 "Insert an empty comment above current line.
22606 If the line is empty, insert comment at its beginning. When
22607 point is within a source block, comment according to the related
22608 major mode."
22609 (if (let ((element (org-element-at-point)))
22610 (and (eq (org-element-type element) 'src-block)
22611 (< (save-excursion
22612 (goto-char (org-element-property :post-affiliated element))
22613 (line-end-position))
22614 (point))
22615 (> (save-excursion
22616 (goto-char (org-element-property :end element))
22617 (skip-chars-backward " \r\t\n")
22618 (line-beginning-position))
22619 (point))))
22620 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22621 (beginning-of-line)
22622 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22623 (open-line 1))
22624 (org-indent-line)
22625 (insert "# ")))
22627 (defvar comment-empty-lines) ; From newcomment.el.
22628 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22629 "Comment or uncomment each non-blank line in the region.
22630 Uncomment each non-blank line between BEG and END if it only
22631 contains commented lines. Otherwise, comment them. If region is
22632 strictly within a source block, use appropriate comment syntax."
22633 (if (let ((element (org-element-at-point)))
22634 (and (eq (org-element-type element) 'src-block)
22635 (< (save-excursion
22636 (goto-char (org-element-property :post-affiliated element))
22637 (line-end-position))
22638 beg)
22639 (>= (save-excursion
22640 (goto-char (org-element-property :end element))
22641 (skip-chars-backward " \r\t\n")
22642 (line-beginning-position))
22643 end)))
22644 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22645 (save-restriction
22646 ;; Restrict region
22647 (narrow-to-region (save-excursion (goto-char beg)
22648 (skip-chars-forward " \r\t\n" end)
22649 (line-beginning-position))
22650 (save-excursion (goto-char end)
22651 (skip-chars-backward " \r\t\n" beg)
22652 (line-end-position)))
22653 (let ((uncommentp
22654 ;; UNCOMMENTP is non-nil when every non blank line between
22655 ;; BEG and END is a comment.
22656 (save-excursion
22657 (goto-char (point-min))
22658 (while (and (not (eobp))
22659 (let ((element (org-element-at-point)))
22660 (and (eq (org-element-type element) 'comment)
22661 (goto-char (min (point-max)
22662 (org-element-property
22663 :end element)))))))
22664 (eobp))))
22665 (if uncommentp
22666 ;; Only blank lines and comments in region: uncomment it.
22667 (save-excursion
22668 (goto-char (point-min))
22669 (while (not (eobp))
22670 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22671 (replace-match "" nil nil nil 1))
22672 (forward-line)))
22673 ;; Comment each line in region.
22674 (let ((min-indent (point-max)))
22675 ;; First find the minimum indentation across all lines.
22676 (save-excursion
22677 (goto-char (point-min))
22678 (while (and (not (eobp)) (not (zerop min-indent)))
22679 (unless (looking-at "[ \t]*$")
22680 (setq min-indent (min min-indent (current-indentation))))
22681 (forward-line)))
22682 ;; Then loop over all lines.
22683 (save-excursion
22684 (goto-char (point-min))
22685 (while (not (eobp))
22686 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22687 ;; Don't get fooled by invisible text (e.g. link path)
22688 ;; when moving to column MIN-INDENT.
22689 (let ((buffer-invisibility-spec nil))
22690 (org-move-to-column min-indent t))
22691 (insert comment-start))
22692 (forward-line)))))))))
22694 (defun org-comment-dwim (arg)
22695 (interactive "*P")
22696 "Call `comment-dwim' within a source edit buffer if needed."
22697 (if (org-in-src-block-p)
22698 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22699 (call-interactively #'comment-dwim)))
22702 ;;; Planning
22704 ;; This section contains tools to operate on timestamp objects, as
22705 ;; returned by, e.g. `org-element-context'.
22707 (defun org-timestamp-has-time-p (timestamp)
22708 "Non-nil when TIMESTAMP has a time specified."
22709 (org-element-property :hour-start timestamp))
22711 (defun org-timestamp-format (timestamp format &optional end utc)
22712 "Format a TIMESTAMP element into a string.
22714 FORMAT is a format specifier to be passed to
22715 `format-time-string'.
22717 When optional argument END is non-nil, use end of date-range or
22718 time-range, if possible.
22720 When optional argument UTC is non-nil, time will be expressed as
22721 Universal Time."
22722 (format-time-string
22723 format
22724 (apply 'encode-time
22725 (cons 0
22726 (mapcar
22727 (lambda (prop) (or (org-element-property prop timestamp) 0))
22728 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22729 '(:minute-start :hour-start :day-start :month-start
22730 :year-start)))))
22731 utc))
22733 (defun org-timestamp-split-range (timestamp &optional end)
22734 "Extract a timestamp object from a date or time range.
22736 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22737 the end of the range. Otherwise, extract its start.
22739 Return a new timestamp object sharing the same parent as
22740 TIMESTAMP."
22741 (let ((type (org-element-property :type timestamp)))
22742 (if (memq type '(active inactive diary)) timestamp
22743 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22744 ;; Set new type.
22745 (org-element-put-property
22746 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22747 ;; Copy start properties over end properties if END is
22748 ;; non-nil. Otherwise, copy end properties over `start' ones.
22749 (let ((p-alist '((:minute-start . :minute-end)
22750 (:hour-start . :hour-end)
22751 (:day-start . :day-end)
22752 (:month-start . :month-end)
22753 (:year-start . :year-end))))
22754 (dolist (p-cell p-alist)
22755 (org-element-put-property
22756 split-ts
22757 (funcall (if end 'car 'cdr) p-cell)
22758 (org-element-property
22759 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22760 ;; Eventually refresh `:raw-value'.
22761 (org-element-put-property split-ts :raw-value nil)
22762 (org-element-put-property
22763 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22765 (defun org-timestamp-translate (timestamp &optional boundary)
22766 "Apply `org-translate-time' on a TIMESTAMP object.
22767 When optional argument BOUNDARY is non-nil, it is either the
22768 symbol `start' or `end'. In this case, only translate the
22769 starting or ending part of TIMESTAMP if it is a date or time
22770 range. Otherwise, translate both parts."
22771 (if (and (not boundary)
22772 (memq (org-element-property :type timestamp)
22773 '(active-range inactive-range)))
22774 (concat
22775 (org-translate-time
22776 (org-element-property :raw-value
22777 (org-timestamp-split-range timestamp)))
22778 "--"
22779 (org-translate-time
22780 (org-element-property :raw-value
22781 (org-timestamp-split-range timestamp t))))
22782 (org-translate-time
22783 (org-element-property
22784 :raw-value
22785 (if (not boundary) timestamp
22786 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22790 ;;; Other stuff.
22792 (defun org-toggle-fixed-width-section (arg)
22793 "Toggle the fixed-width export.
22794 If there is no active region, the QUOTE keyword at the current headline is
22795 inserted or removed. When present, it causes the text between this headline
22796 and the next to be exported as fixed-width text, and unmodified.
22797 If there is an active region, this command adds or removes a colon as the
22798 first character of this line. If the first character of a line is a colon,
22799 this line is also exported in fixed-width font."
22800 (interactive "P")
22801 (let* ((cc 0)
22802 (regionp (org-region-active-p))
22803 (beg (if regionp (region-beginning) (point)))
22804 (end (if regionp (region-end)))
22805 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22806 (case-fold-search nil)
22807 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22808 off)
22809 (if regionp
22810 (save-excursion
22811 (goto-char beg)
22812 (setq cc (current-column))
22813 (beginning-of-line 1)
22814 (setq off (looking-at re))
22815 (while (> nlines 0)
22816 (setq nlines (1- nlines))
22817 (beginning-of-line 1)
22818 (cond
22819 (arg
22820 (org-move-to-column cc t)
22821 (insert ": \n")
22822 (forward-line -1))
22823 ((and off (looking-at re))
22824 (replace-match "" t t nil 1))
22825 ((not off) (org-move-to-column cc t) (insert ": ")))
22826 (forward-line 1)))
22827 (save-excursion
22828 (org-back-to-heading)
22829 (cond
22830 ((looking-at (format org-heading-keyword-regexp-format
22831 org-quote-string))
22832 (goto-char (match-end 1))
22833 (looking-at (concat " +" org-quote-string))
22834 (replace-match "" t t)
22835 (when (eolp) (insert " ")))
22836 ((looking-at org-outline-regexp)
22837 (goto-char (match-end 0))
22838 (insert org-quote-string " ")))))))
22840 (defun org-reftex-citation ()
22841 "Use reftex-citation to insert a citation into the buffer.
22842 This looks for a line like
22844 #+BIBLIOGRAPHY: foo plain option:-d
22846 and derives from it that foo.bib is the bibliography file relevant
22847 for this document. It then installs the necessary environment for RefTeX
22848 to work in this buffer and calls `reftex-citation' to insert a citation
22849 into the buffer.
22851 Export of such citations to both LaTeX and HTML is handled by the contributed
22852 package ox-bibtex by Taru Karttunen."
22853 (interactive)
22854 (let ((reftex-docstruct-symbol 'rds)
22855 (reftex-cite-format "\\cite{%l}")
22856 rds bib)
22857 (save-excursion
22858 (save-restriction
22859 (widen)
22860 (let ((case-fold-search t)
22861 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22862 (if (not (save-excursion
22863 (or (re-search-forward re nil t)
22864 (re-search-backward re nil t))))
22865 (error "No bibliography defined in file")
22866 (setq bib (concat (match-string 1) ".bib")
22867 rds (list (list 'bib bib)))))))
22868 (call-interactively 'reftex-citation)))
22870 ;;;; Functions extending outline functionality
22872 (defun org-beginning-of-line (&optional arg)
22873 "Go to the beginning of the current line. If that is invisible, continue
22874 to a visible line beginning. This makes the function of C-a more intuitive.
22875 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22876 first attempt, and only move to after the tags when the cursor is already
22877 beyond the end of the headline."
22878 (interactive "P")
22879 (let ((pos (point))
22880 (special (if (consp org-special-ctrl-a/e)
22881 (car org-special-ctrl-a/e)
22882 org-special-ctrl-a/e))
22883 deactivate-mark refpos)
22884 (if (org-bound-and-true-p visual-line-mode)
22885 (beginning-of-visual-line 1)
22886 (beginning-of-line 1))
22887 (if (and arg (fboundp 'move-beginning-of-line))
22888 (call-interactively 'move-beginning-of-line)
22889 (if (bobp)
22891 (backward-char 1)
22892 (if (org-truely-invisible-p)
22893 (while (and (not (bobp)) (org-truely-invisible-p))
22894 (backward-char 1)
22895 (beginning-of-line 1))
22896 (forward-char 1))))
22897 (when special
22898 (cond
22899 ((and (looking-at org-complex-heading-regexp)
22900 (= (char-after (match-end 1)) ?\ ))
22901 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22902 (point-at-eol)))
22903 (goto-char
22904 (if (eq special t)
22905 (cond ((> pos refpos) refpos)
22906 ((= pos (point)) refpos)
22907 (t (point)))
22908 (cond ((> pos (point)) (point))
22909 ((not (eq last-command this-command)) (point))
22910 (t refpos)))))
22911 ((org-at-item-p)
22912 ;; Being at an item and not looking at an the item means point
22913 ;; was previously moved to beginning of a visual line, which
22914 ;; doesn't contain the item. Therefore, do nothing special,
22915 ;; just stay here.
22916 (when (looking-at org-list-full-item-re)
22917 ;; Set special position at first white space character after
22918 ;; bullet, and check-box, if any.
22919 (let ((after-bullet
22920 (let ((box (match-end 3)))
22921 (if (not box) (match-end 1)
22922 (let ((after (char-after box)))
22923 (if (and after (= after ? )) (1+ box) box))))))
22924 ;; Special case: Move point to special position when
22925 ;; currently after it or at beginning of line.
22926 (if (eq special t)
22927 (when (or (> pos after-bullet) (= (point) pos))
22928 (goto-char after-bullet))
22929 ;; Reversed case: Move point to special position when
22930 ;; point was already at beginning of line and command is
22931 ;; repeated.
22932 (when (and (= (point) pos) (eq last-command this-command))
22933 (goto-char after-bullet))))))))
22934 (org-no-warnings
22935 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22936 (setq disable-point-adjustment
22937 (or (not (invisible-p (point)))
22938 (not (invisible-p (max (point-min) (1- (point))))))))
22940 (defun org-end-of-line (&optional arg)
22941 "Go to the end of the line.
22942 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22943 tags on the first attempt, and only move to after the tags when
22944 the cursor is already beyond the end of the headline."
22945 (interactive "P")
22946 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22947 org-special-ctrl-a/e))
22948 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22949 'end-of-visual-line)
22950 ((fboundp 'move-end-of-line) 'move-end-of-line)
22951 (t 'end-of-line)))
22952 deactivate-mark)
22953 (if (or (not special) arg) (call-interactively move-fun)
22954 (let* ((element (save-excursion (beginning-of-line)
22955 (org-element-at-point)))
22956 (type (org-element-type element)))
22957 (cond
22958 ((memq type '(headline inlinetask))
22959 (let ((pos (point)))
22960 (beginning-of-line 1)
22961 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22962 (if (eq special t)
22963 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22964 (goto-char (match-beginning 1))
22965 (goto-char (match-end 0)))
22966 (if (or (< pos (match-end 0))
22967 (not (eq this-command last-command)))
22968 (goto-char (match-end 0))
22969 (goto-char (match-beginning 1))))
22970 (call-interactively move-fun))))
22971 ((outline-invisible-p (line-end-position))
22972 ;; If element is hidden, `move-end-of-line' would put point
22973 ;; after it. Use `end-of-line' to stay on current line.
22974 (call-interactively 'end-of-line))
22975 (t (call-interactively move-fun)))))
22976 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22977 (setq disable-point-adjustment
22978 (or (not (invisible-p (point)))
22979 (not (invisible-p (max (point-min) (1- (point))))))))
22981 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22982 (define-key org-mode-map "\C-e" 'org-end-of-line)
22984 (defun org-backward-sentence (&optional arg)
22985 "Go to beginning of sentence, or beginning of table field.
22986 This will call `backward-sentence' or `org-table-beginning-of-field',
22987 depending on context."
22988 (interactive "P")
22989 (cond
22990 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22991 (t (call-interactively 'backward-sentence))))
22993 (defun org-forward-sentence (&optional arg)
22994 "Go to end of sentence, or end of table field.
22995 This will call `forward-sentence' or `org-table-end-of-field',
22996 depending on context."
22997 (interactive "P")
22998 (cond
22999 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23000 (t (call-interactively 'forward-sentence))))
23002 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23003 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23005 (defun org-kill-line (&optional arg)
23006 "Kill line, to tags or end of line."
23007 (interactive "P")
23008 (cond
23009 ((or (not org-special-ctrl-k)
23010 (bolp)
23011 (not (org-at-heading-p)))
23012 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23013 org-ctrl-k-protect-subtree)
23014 (if (or (eq org-ctrl-k-protect-subtree 'error)
23015 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23016 (user-error "C-k aborted as it would kill a hidden subtree")))
23017 (call-interactively
23018 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23019 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23020 (kill-region (point) (match-beginning 1))
23021 (org-set-tags nil t))
23022 (t (kill-region (point) (point-at-eol)))))
23024 (define-key org-mode-map "\C-k" 'org-kill-line)
23026 (defun org-yank (&optional arg)
23027 "Yank. If the kill is a subtree, treat it specially.
23028 This command will look at the current kill and check if is a single
23029 subtree, or a series of subtrees[1]. If it passes the test, and if the
23030 cursor is at the beginning of a line or after the stars of a currently
23031 empty headline, then the yank is handled specially. How exactly depends
23032 on the value of the following variables, both set by default.
23034 org-yank-folded-subtrees
23035 When set, the subtree(s) will be folded after insertion, but only
23036 if doing so would now swallow text after the yanked text.
23038 org-yank-adjusted-subtrees
23039 When set, the subtree will be promoted or demoted in order to
23040 fit into the local outline tree structure, which means that the level
23041 will be adjusted so that it becomes the smaller one of the two
23042 *visible* surrounding headings.
23044 Any prefix to this command will cause `yank' to be called directly with
23045 no special treatment. In particular, a simple \\[universal-argument] prefix \
23046 will just
23047 plainly yank the text as it is.
23049 \[1] The test checks if the first non-white line is a heading
23050 and if there are no other headings with fewer stars."
23051 (interactive "P")
23052 (org-yank-generic 'yank arg))
23054 (defun org-yank-generic (command arg)
23055 "Perform some yank-like command.
23057 This function implements the behavior described in the `org-yank'
23058 documentation. However, it has been generalized to work for any
23059 interactive command with similar behavior."
23061 ;; pretend to be command COMMAND
23062 (setq this-command command)
23064 (if arg
23065 (call-interactively command)
23067 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23068 (and (org-kill-is-subtree-p)
23069 (or (bolp)
23070 (and (looking-at "[ \t]*$")
23071 (string-match
23072 "\\`\\*+\\'"
23073 (buffer-substring (point-at-bol) (point)))))))
23074 swallowp)
23075 (cond
23076 ((and subtreep org-yank-folded-subtrees)
23077 (let ((beg (point))
23078 end)
23079 (if (and subtreep org-yank-adjusted-subtrees)
23080 (org-paste-subtree nil nil 'for-yank)
23081 (call-interactively command))
23083 (setq end (point))
23084 (goto-char beg)
23085 (when (and (bolp) subtreep
23086 (not (setq swallowp
23087 (org-yank-folding-would-swallow-text beg end))))
23088 (org-with-limited-levels
23089 (or (looking-at org-outline-regexp)
23090 (re-search-forward org-outline-regexp-bol end t))
23091 (while (and (< (point) end) (looking-at org-outline-regexp))
23092 (hide-subtree)
23093 (org-cycle-show-empty-lines 'folded)
23094 (condition-case nil
23095 (outline-forward-same-level 1)
23096 (error (goto-char end))))))
23097 (when swallowp
23098 (message
23099 "Inserted text not folded because that would swallow text"))
23101 (goto-char end)
23102 (skip-chars-forward " \t\n\r")
23103 (beginning-of-line 1)
23104 (push-mark beg 'nomsg)))
23105 ((and subtreep org-yank-adjusted-subtrees)
23106 (let ((beg (point-at-bol)))
23107 (org-paste-subtree nil nil 'for-yank)
23108 (push-mark beg 'nomsg)))
23110 (call-interactively command))))))
23112 (defun org-yank-folding-would-swallow-text (beg end)
23113 "Would hide-subtree at BEG swallow any text after END?"
23114 (let (level)
23115 (org-with-limited-levels
23116 (save-excursion
23117 (goto-char beg)
23118 (when (or (looking-at org-outline-regexp)
23119 (re-search-forward org-outline-regexp-bol end t))
23120 (setq level (org-outline-level)))
23121 (goto-char end)
23122 (skip-chars-forward " \t\r\n\v\f")
23123 (if (or (eobp)
23124 (and (bolp) (looking-at org-outline-regexp)
23125 (<= (org-outline-level) level)))
23126 nil ; Nothing would be swallowed
23127 t))))) ; something would swallow
23129 (define-key org-mode-map "\C-y" 'org-yank)
23131 (defun org-truely-invisible-p ()
23132 "Check if point is at a character currently not visible.
23133 This version does not only check the character property, but also
23134 `visible-mode'."
23135 ;; Early versions of noutline don't have `outline-invisible-p'.
23136 (if (org-bound-and-true-p visible-mode)
23138 (outline-invisible-p)))
23140 (defun org-invisible-p2 ()
23141 "Check if point is at a character currently not visible."
23142 (save-excursion
23143 (if (and (eolp) (not (bobp))) (backward-char 1))
23144 ;; Early versions of noutline don't have `outline-invisible-p'.
23145 (outline-invisible-p)))
23147 (defun org-back-to-heading (&optional invisible-ok)
23148 "Call `outline-back-to-heading', but provide a better error message."
23149 (condition-case nil
23150 (outline-back-to-heading invisible-ok)
23151 (error (error "Before first headline at position %d in buffer %s"
23152 (point) (current-buffer)))))
23154 (defun org-before-first-heading-p ()
23155 "Before first heading?"
23156 (save-excursion
23157 (end-of-line)
23158 (null (re-search-backward org-outline-regexp-bol nil t))))
23160 (defun org-at-heading-p (&optional ignored)
23161 (outline-on-heading-p t))
23162 ;; Compatibility alias with Org versions < 7.8.03
23163 (defalias 'org-on-heading-p 'org-at-heading-p)
23165 (defun org-at-comment-p nil
23166 "Is cursor in a line starting with a # character?"
23167 (save-excursion
23168 (beginning-of-line)
23169 (looking-at "^#")))
23171 (defun org-at-drawer-p nil
23172 "Is cursor at a drawer keyword?"
23173 (save-excursion
23174 (move-beginning-of-line 1)
23175 (looking-at org-drawer-regexp)))
23177 (defun org-at-block-p nil
23178 "Is cursor at a block keyword?"
23179 (save-excursion
23180 (move-beginning-of-line 1)
23181 (looking-at org-block-regexp)))
23183 (defun org-point-at-end-of-empty-headline ()
23184 "If point is at the end of an empty headline, return t, else nil.
23185 If the heading only contains a TODO keyword, it is still still considered
23186 empty."
23187 (and (looking-at "[ \t]*$")
23188 (when org-todo-line-regexp
23189 (save-excursion
23190 (beginning-of-line 1)
23191 (let ((case-fold-search nil))
23192 (looking-at org-todo-line-regexp)
23193 (string= (match-string 3) ""))))))
23195 (defun org-at-heading-or-item-p ()
23196 (or (org-at-heading-p) (org-at-item-p)))
23198 (defun org-at-target-p ()
23199 (or (org-in-regexp org-radio-target-regexp)
23200 (org-in-regexp org-target-regexp)))
23201 ;; Compatibility alias with Org versions < 7.8.03
23202 (defalias 'org-on-target-p 'org-at-target-p)
23204 (defun org-up-heading-all (arg)
23205 "Move to the heading line of which the present line is a subheading.
23206 This function considers both visible and invisible heading lines.
23207 With argument, move up ARG levels."
23208 (if (fboundp 'outline-up-heading-all)
23209 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23210 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23212 (defun org-up-heading-safe ()
23213 "Move to the heading line of which the present line is a subheading.
23214 This version will not throw an error. It will return the level of the
23215 headline found, or nil if no higher level is found.
23217 Also, this function will be a lot faster than `outline-up-heading',
23218 because it relies on stars being the outline starters. This can really
23219 make a significant difference in outlines with very many siblings."
23220 (let (start-level re)
23221 (org-back-to-heading t)
23222 (setq start-level (funcall outline-level))
23223 (if (equal start-level 1)
23225 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23226 (if (re-search-backward re nil t)
23227 (funcall outline-level)))))
23229 (defun org-first-sibling-p ()
23230 "Is this heading the first child of its parents?"
23231 (interactive)
23232 (let ((re org-outline-regexp-bol)
23233 level l)
23234 (unless (org-at-heading-p t)
23235 (user-error "Not at a heading"))
23236 (setq level (funcall outline-level))
23237 (save-excursion
23238 (if (not (re-search-backward re nil t))
23240 (setq l (funcall outline-level))
23241 (< l level)))))
23243 (defun org-goto-sibling (&optional previous)
23244 "Goto the next sibling, even if it is invisible.
23245 When PREVIOUS is set, go to the previous sibling instead. Returns t
23246 when a sibling was found. When none is found, return nil and don't
23247 move point."
23248 (let ((fun (if previous 're-search-backward 're-search-forward))
23249 (pos (point))
23250 (re org-outline-regexp-bol)
23251 level l)
23252 (when (condition-case nil (org-back-to-heading t) (error nil))
23253 (setq level (funcall outline-level))
23254 (catch 'exit
23255 (or previous (forward-char 1))
23256 (while (funcall fun re nil t)
23257 (setq l (funcall outline-level))
23258 (when (< l level) (goto-char pos) (throw 'exit nil))
23259 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23260 (goto-char pos)
23261 nil))))
23263 (defun org-show-siblings ()
23264 "Show all siblings of the current headline."
23265 (save-excursion
23266 (while (org-goto-sibling) (org-flag-heading nil)))
23267 (save-excursion
23268 (while (org-goto-sibling 'previous)
23269 (org-flag-heading nil))))
23271 (defun org-goto-first-child ()
23272 "Goto the first child, even if it is invisible.
23273 Return t when a child was found. Otherwise don't move point and
23274 return nil."
23275 (let (level (pos (point)) (re org-outline-regexp-bol))
23276 (when (condition-case nil (org-back-to-heading t) (error nil))
23277 (setq level (outline-level))
23278 (forward-char 1)
23279 (if (and (re-search-forward re nil t) (> (outline-level) level))
23280 (progn (goto-char (match-beginning 0)) t)
23281 (goto-char pos) nil))))
23283 (defun org-show-hidden-entry ()
23284 "Show an entry where even the heading is hidden."
23285 (save-excursion
23286 (org-show-entry)))
23288 (defun org-flag-heading (flag &optional entry)
23289 "Flag the current heading. FLAG non-nil means make invisible.
23290 When ENTRY is non-nil, show the entire entry."
23291 (save-excursion
23292 (org-back-to-heading t)
23293 ;; Check if we should show the entire entry
23294 (if entry
23295 (progn
23296 (org-show-entry)
23297 (save-excursion
23298 (and (outline-next-heading)
23299 (org-flag-heading nil))))
23300 (outline-flag-region (max (point-min) (1- (point)))
23301 (save-excursion (outline-end-of-heading) (point))
23302 flag))))
23304 (defun org-get-next-sibling ()
23305 "Move to next heading of the same level, and return point.
23306 If there is no such heading, return nil.
23307 This is like outline-next-sibling, but invisible headings are ok."
23308 (let ((level (funcall outline-level)))
23309 (outline-next-heading)
23310 (while (and (not (eobp)) (> (funcall outline-level) level))
23311 (outline-next-heading))
23312 (if (or (eobp) (< (funcall outline-level) level))
23314 (point))))
23316 (defun org-get-last-sibling ()
23317 "Move to previous heading of the same level, and return point.
23318 If there is no such heading, return nil."
23319 (let ((opoint (point))
23320 (level (funcall outline-level)))
23321 (outline-previous-heading)
23322 (when (and (/= (point) opoint) (outline-on-heading-p t))
23323 (while (and (> (funcall outline-level) level)
23324 (not (bobp)))
23325 (outline-previous-heading))
23326 (if (< (funcall outline-level) level)
23328 (point)))))
23330 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23331 "Goto to the end of a subtree."
23332 ;; This contains an exact copy of the original function, but it uses
23333 ;; `org-back-to-heading', to make it work also in invisible
23334 ;; trees. And is uses an invisible-ok argument.
23335 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23336 ;; Furthermore, when used inside Org, finding the end of a large subtree
23337 ;; with many children and grandchildren etc, this can be much faster
23338 ;; than the outline version.
23339 (org-back-to-heading invisible-ok)
23340 (let ((first t)
23341 (level (funcall outline-level)))
23342 (if (and (derived-mode-p 'org-mode) (< level 1000))
23343 ;; A true heading (not a plain list item), in Org-mode
23344 ;; This means we can easily find the end by looking
23345 ;; only for the right number of stars. Using a regexp to do
23346 ;; this is so much faster than using a Lisp loop.
23347 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23348 (forward-char 1)
23349 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23350 ;; something else, do it the slow way
23351 (while (and (not (eobp))
23352 (or first (> (funcall outline-level) level)))
23353 (setq first nil)
23354 (outline-next-heading)))
23355 (unless to-heading
23356 (if (memq (preceding-char) '(?\n ?\^M))
23357 (progn
23358 ;; Go to end of line before heading
23359 (forward-char -1)
23360 (if (memq (preceding-char) '(?\n ?\^M))
23361 ;; leave blank line before heading
23362 (forward-char -1))))))
23363 (point))
23365 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23366 "Use Org version in org-mode, for dramatic speed-up."
23367 (if (derived-mode-p 'org-mode)
23368 (progn
23369 (org-end-of-subtree nil t)
23370 (unless (eobp) (backward-char 1)))
23371 ad-do-it))
23373 (defun org-end-of-meta-data-and-drawers ()
23374 "Jump to the first text after meta data and drawers in the current entry.
23375 This will move over empty lines, lines with planning time stamps,
23376 clocking lines, and drawers."
23377 (org-back-to-heading t)
23378 (let ((end (save-excursion (outline-next-heading) (point)))
23379 (re (concat "\\(" org-drawer-regexp "\\)"
23380 "\\|" "[ \t]*" org-keyword-time-regexp)))
23381 (forward-line 1)
23382 (while (re-search-forward re end t)
23383 (if (not (match-end 1))
23384 ;; empty or planning line
23385 (forward-line 1)
23386 ;; a drawer, find the end
23387 (re-search-forward "^[ \t]*:END:" end 'move)
23388 (forward-line 1)))
23389 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23390 (point)))
23392 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23393 "Move forward to the ARG'th subheading at same level as this one.
23394 Stop at the first and last subheadings of a superior heading.
23395 Normally this only looks at visible headings, but when INVISIBLE-OK is
23396 non-nil it will also look at invisible ones."
23397 (interactive "p")
23398 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23399 (if (and arg (< arg 0))
23400 (goto-char (point-min))
23401 (outline-next-heading))
23402 (org-at-heading-p)
23403 (let ((level (- (match-end 0) (match-beginning 0) 1))
23404 (f (if (and arg (< arg 0))
23405 're-search-backward
23406 're-search-forward))
23407 (count (if arg (abs arg) 1))
23408 (result (point)))
23409 (while (and (prog1 (> count 0)
23410 (forward-char (if (and arg (< arg 0)) -1 1)))
23411 (funcall f org-outline-regexp-bol nil 'move))
23412 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23413 (cond ((< l level) (setq count 0))
23414 ((and (= l level)
23415 (or invisible-ok
23416 (progn
23417 (goto-char (line-beginning-position))
23418 (not (outline-invisible-p)))))
23419 (setq count (1- count))
23420 (when (eq l level)
23421 (setq result (point)))))))
23422 (goto-char result))
23423 (beginning-of-line 1)))
23425 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23426 "Move backward to the ARG'th subheading at same level as this one.
23427 Stop at the first and last subheadings of a superior heading."
23428 (interactive "p")
23429 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23431 (defun org-next-block (arg &optional backward block-regexp)
23432 "Jump to the next block.
23433 With a prefix argument ARG, jump forward ARG many source blocks.
23434 When BACKWARD is non-nil, jump to the previous block.
23435 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23436 (interactive "p")
23437 (let ((re (or block-regexp org-block-regexp))
23438 (re-search-fn (or (and backward 're-search-backward)
23439 're-search-forward)))
23440 (if (looking-at re) (forward-char 1))
23441 (condition-case nil
23442 (funcall re-search-fn re nil nil arg)
23443 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23444 (goto-char (match-beginning 0)) (org-show-context)))
23446 (defun org-previous-block (arg &optional block-regexp)
23447 "Jump to the previous block.
23448 With a prefix argument ARG, jump backward ARG many source blocks.
23449 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23450 (interactive "p")
23451 (org-next-block arg t block-regexp))
23453 (defun org-forward-paragraph ()
23454 "Move forward to beginning of next paragraph or equivalent.
23456 The function moves point to the beginning of the next visible
23457 structural element, which can be a paragraph, a table, a list
23458 item, etc. It also provides some special moves for convenience:
23460 - On an affiliated keyword, jump to the beginning of the
23461 relative element.
23462 - On an item or a footnote definition, move to the second
23463 element inside, if any.
23464 - On a table or a property drawer, jump after it.
23465 - On a verse or source block, stop after blank lines."
23466 (interactive)
23467 (when (eobp) (user-error "Cannot move further down"))
23468 (let* ((deactivate-mark nil)
23469 (element (org-element-at-point))
23470 (type (org-element-type element))
23471 (post-affiliated (org-element-property :post-affiliated element))
23472 (contents-begin (org-element-property :contents-begin element))
23473 (contents-end (org-element-property :contents-end element))
23474 (end (let ((end (org-element-property :end element)) (parent element))
23475 (while (and (setq parent (org-element-property :parent parent))
23476 (= (org-element-property :contents-end parent) end))
23477 (setq end (org-element-property :end parent)))
23478 end)))
23479 (cond ((not element)
23480 (skip-chars-forward " \r\t\n")
23481 (or (eobp) (beginning-of-line)))
23482 ;; On affiliated keywords, move to element's beginning.
23483 ((and post-affiliated (< (point) post-affiliated))
23484 (goto-char post-affiliated))
23485 ;; At a table row, move to the end of the table. Similarly,
23486 ;; at a node property, move to the end of the property
23487 ;; drawer.
23488 ((memq type '(node-property table-row))
23489 (goto-char (org-element-property
23490 :end (org-element-property :parent element))))
23491 ((memq type '(property-drawer table)) (goto-char end))
23492 ;; Consider blank lines as separators in verse and source
23493 ;; blocks to ease editing.
23494 ((memq type '(src-block verse-block))
23495 (when (eq type 'src-block)
23496 (setq contents-end
23497 (save-excursion (goto-char end)
23498 (skip-chars-backward " \r\t\n")
23499 (line-beginning-position))))
23500 (beginning-of-line)
23501 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23502 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23503 (goto-char end)
23504 (skip-chars-forward " \r\t\n")
23505 (if (= (point) contents-end) (goto-char end)
23506 (beginning-of-line))))
23507 ;; With no contents, just skip element.
23508 ((not contents-begin) (goto-char end))
23509 ;; If contents are invisible, skip the element altogether.
23510 ((outline-invisible-p (line-end-position))
23511 (case type
23512 (headline
23513 (org-with-limited-levels (outline-next-visible-heading 1)))
23514 ;; At a plain list, make sure we move to the next item
23515 ;; instead of skipping the whole list.
23516 (plain-list (forward-char)
23517 (org-forward-paragraph))
23518 (otherwise (goto-char end))))
23519 ((>= (point) contents-end) (goto-char end))
23520 ((>= (point) contents-begin)
23521 ;; This can only happen on paragraphs and plain lists.
23522 (case type
23523 (paragraph (goto-char end))
23524 ;; At a plain list, try to move to second element in
23525 ;; first item, if possible.
23526 (plain-list (end-of-line)
23527 (org-forward-paragraph))))
23528 ;; When contents start on the middle of a line (e.g. in
23529 ;; items and footnote definitions), try to reach first
23530 ;; element starting after current line.
23531 ((> (line-end-position) contents-begin)
23532 (end-of-line)
23533 (org-forward-paragraph))
23534 (t (goto-char contents-begin)))))
23536 (defun org-backward-paragraph ()
23537 "Move backward to start of previous paragraph or equivalent.
23539 The function moves point to the beginning of the current
23540 structural element, which can be a paragraph, a table, a list
23541 item, etc., or to the beginning of the previous visible one if
23542 point is already there. It also provides some special moves for
23543 convenience:
23545 - On an affiliated keyword, jump to the first one.
23546 - On a table or a property drawer, move to its beginning.
23547 - On a verse or source block, stop before blank lines."
23548 (interactive)
23549 (when (bobp) (user-error "Cannot move further up"))
23550 (let* ((deactivate-mark nil)
23551 (element (org-element-at-point))
23552 (type (org-element-type element))
23553 (contents-begin (org-element-property :contents-begin element))
23554 (contents-end (org-element-property :contents-end element))
23555 (post-affiliated (org-element-property :post-affiliated element))
23556 (begin (org-element-property :begin element)))
23557 (cond
23558 ((not element) (goto-char (point-min)))
23559 ((= (point) begin)
23560 (backward-char)
23561 (org-backward-paragraph))
23562 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23563 ((memq type '(node-property table-row))
23564 (goto-char (org-element-property
23565 :post-affiliated (org-element-property :parent element))))
23566 ((memq type '(property-drawer table)) (goto-char begin))
23567 ((memq type '(src-block verse-block))
23568 (when (eq type 'src-block)
23569 (setq contents-begin
23570 (save-excursion (goto-char begin) (forward-line) (point))))
23571 (if (= (point) contents-begin) (goto-char post-affiliated)
23572 ;; Inside a verse block, see blank lines as paragraph
23573 ;; separators.
23574 (let ((origin (point)))
23575 (skip-chars-backward " \r\t\n" contents-begin)
23576 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23577 (skip-chars-forward " \r\t\n" origin)
23578 (if (= (point) origin) (goto-char contents-begin)
23579 (beginning-of-line))))))
23580 ((not contents-begin) (goto-char (or post-affiliated begin)))
23581 ((eq type 'paragraph)
23582 (goto-char contents-begin)
23583 ;; When at first paragraph in an item or a footnote definition,
23584 ;; move directly to beginning of line.
23585 (let ((parent-contents
23586 (org-element-property
23587 :contents-begin (org-element-property :parent element))))
23588 (when (and parent-contents (= parent-contents contents-begin))
23589 (beginning-of-line))))
23590 ;; At the end of a greater element, move to the beginning of the
23591 ;; last element within.
23592 ((>= (point) contents-end)
23593 (goto-char (1- contents-end))
23594 (org-backward-paragraph))
23595 (t (goto-char (or post-affiliated begin))))
23596 ;; Ensure we never leave point invisible.
23597 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23599 (defun org-forward-element ()
23600 "Move forward by one element.
23601 Move to the next element at the same level, when possible."
23602 (interactive)
23603 (cond ((eobp) (user-error "Cannot move further down"))
23604 ((org-with-limited-levels (org-at-heading-p))
23605 (let ((origin (point)))
23606 (goto-char (org-end-of-subtree nil t))
23607 (unless (org-with-limited-levels (org-at-heading-p))
23608 (goto-char origin)
23609 (user-error "Cannot move further down"))))
23611 (let* ((elem (org-element-at-point))
23612 (end (org-element-property :end elem))
23613 (parent (org-element-property :parent elem)))
23614 (cond ((and parent (= (org-element-property :contents-end parent) end))
23615 (goto-char (org-element-property :end parent)))
23616 ((integer-or-marker-p end) (goto-char end))
23617 (t (message "No element at point")))))))
23619 (defun org-backward-element ()
23620 "Move backward by one element.
23621 Move to the previous element at the same level, when possible."
23622 (interactive)
23623 (cond ((bobp) (user-error "Cannot move further up"))
23624 ((org-with-limited-levels (org-at-heading-p))
23625 ;; At a headline, move to the previous one, if any, or stay
23626 ;; here.
23627 (let ((origin (point)))
23628 (org-with-limited-levels (org-backward-heading-same-level 1))
23629 ;; When current headline has no sibling above, move to its
23630 ;; parent.
23631 (when (= (point) origin)
23632 (or (org-with-limited-levels (org-up-heading-safe))
23633 (progn (goto-char origin)
23634 (user-error "Cannot move further up"))))))
23636 (let* ((elem (org-element-at-point))
23637 (beg (org-element-property :begin elem)))
23638 (cond
23639 ;; Move to beginning of current element if point isn't
23640 ;; there already.
23641 ((null beg) (message "No element at point"))
23642 ((/= (point) beg) (goto-char beg))
23643 (t (goto-char beg)
23644 (skip-chars-backward " \r\t\n")
23645 (unless (bobp)
23646 (let ((prev (org-element-at-point)))
23647 (goto-char (org-element-property :begin prev))
23648 (while (and (setq prev (org-element-property :parent prev))
23649 (<= (org-element-property :end prev) beg))
23650 (goto-char (org-element-property :begin prev)))))))))))
23652 (defun org-up-element ()
23653 "Move to upper element."
23654 (interactive)
23655 (if (org-with-limited-levels (org-at-heading-p))
23656 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23657 (let* ((elem (org-element-at-point))
23658 (parent (org-element-property :parent elem)))
23659 (if parent (goto-char (org-element-property :begin parent))
23660 (if (org-with-limited-levels (org-before-first-heading-p))
23661 (user-error "No surrounding element")
23662 (org-with-limited-levels (org-back-to-heading)))))))
23664 (defvar org-element-greater-elements)
23665 (defun org-down-element ()
23666 "Move to inner element."
23667 (interactive)
23668 (let ((element (org-element-at-point)))
23669 (cond
23670 ((memq (org-element-type element) '(plain-list table))
23671 (goto-char (org-element-property :contents-begin element))
23672 (forward-char))
23673 ((memq (org-element-type element) org-element-greater-elements)
23674 ;; If contents are hidden, first disclose them.
23675 (when (outline-invisible-p (line-end-position)) (org-cycle))
23676 (goto-char (or (org-element-property :contents-begin element)
23677 (user-error "No content for this element"))))
23678 (t (user-error "No inner element")))))
23680 (defun org-drag-element-backward ()
23681 "Move backward element at point."
23682 (interactive)
23683 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23684 (let* ((elem (org-element-at-point))
23685 (prev-elem
23686 (save-excursion
23687 (goto-char (org-element-property :begin elem))
23688 (skip-chars-backward " \r\t\n")
23689 (unless (bobp)
23690 (let* ((beg (org-element-property :begin elem))
23691 (prev (org-element-at-point))
23692 (up prev))
23693 (while (and (setq up (org-element-property :parent up))
23694 (<= (org-element-property :end prev) beg))
23695 (setq prev up))
23696 prev)))))
23697 ;; Error out if no previous element or previous element is
23698 ;; a parent of the current one.
23699 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23700 (user-error "Cannot drag element backward")
23701 (let ((pos (point)))
23702 (org-element-swap-A-B prev-elem elem)
23703 (goto-char (+ (org-element-property :begin prev-elem)
23704 (- pos (org-element-property :begin elem)))))))))
23706 (defun org-drag-element-forward ()
23707 "Move forward element at point."
23708 (interactive)
23709 (let* ((pos (point))
23710 (elem (org-element-at-point)))
23711 (when (= (point-max) (org-element-property :end elem))
23712 (user-error "Cannot drag element forward"))
23713 (goto-char (org-element-property :end elem))
23714 (let ((next-elem (org-element-at-point)))
23715 (when (or (org-element-nested-p elem next-elem)
23716 (and (eq (org-element-type next-elem) 'headline)
23717 (not (eq (org-element-type elem) 'headline))))
23718 (goto-char pos)
23719 (user-error "Cannot drag element forward"))
23720 ;; Compute new position of point: it's shifted by NEXT-ELEM
23721 ;; body's length (without final blanks) and by the length of
23722 ;; blanks between ELEM and NEXT-ELEM.
23723 (let ((size-next (- (save-excursion
23724 (goto-char (org-element-property :end next-elem))
23725 (skip-chars-backward " \r\t\n")
23726 (forward-line)
23727 ;; Small correction if buffer doesn't end
23728 ;; with a newline character.
23729 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23730 (org-element-property :begin next-elem)))
23731 (size-blank (- (org-element-property :end elem)
23732 (save-excursion
23733 (goto-char (org-element-property :end elem))
23734 (skip-chars-backward " \r\t\n")
23735 (forward-line)
23736 (point)))))
23737 (org-element-swap-A-B elem next-elem)
23738 (goto-char (+ pos size-next size-blank))))))
23740 (defun org-drag-line-forward (arg)
23741 "Drag the line at point ARG lines forward."
23742 (interactive "p")
23743 (dotimes (n (abs arg))
23744 (let ((c (current-column)))
23745 (if (< 0 arg)
23746 (progn
23747 (beginning-of-line 2)
23748 (transpose-lines 1)
23749 (beginning-of-line 0))
23750 (transpose-lines 1)
23751 (beginning-of-line -1))
23752 (org-move-to-column c))))
23754 (defun org-drag-line-backward (arg)
23755 "Drag the line at point ARG lines backward."
23756 (interactive "p")
23757 (org-drag-line-forward (- arg)))
23759 (defun org-mark-element ()
23760 "Put point at beginning of this element, mark at end.
23762 Interactively, if this command is repeated or (in Transient Mark
23763 mode) if the mark is active, it marks the next element after the
23764 ones already marked."
23765 (interactive)
23766 (let (deactivate-mark)
23767 (if (and (org-called-interactively-p 'any)
23768 (or (and (eq last-command this-command) (mark t))
23769 (and transient-mark-mode mark-active)))
23770 (set-mark
23771 (save-excursion
23772 (goto-char (mark))
23773 (goto-char (org-element-property :end (org-element-at-point)))))
23774 (let ((element (org-element-at-point)))
23775 (end-of-line)
23776 (push-mark (org-element-property :end element) t t)
23777 (goto-char (org-element-property :begin element))))))
23779 (defun org-narrow-to-element ()
23780 "Narrow buffer to current element."
23781 (interactive)
23782 (let ((elem (org-element-at-point)))
23783 (cond
23784 ((eq (car elem) 'headline)
23785 (narrow-to-region
23786 (org-element-property :begin elem)
23787 (org-element-property :end elem)))
23788 ((memq (car elem) org-element-greater-elements)
23789 (narrow-to-region
23790 (org-element-property :contents-begin elem)
23791 (org-element-property :contents-end elem)))
23793 (narrow-to-region
23794 (org-element-property :begin elem)
23795 (org-element-property :end elem))))))
23797 (defun org-transpose-element ()
23798 "Transpose current and previous elements, keeping blank lines between.
23799 Point is moved after both elements."
23800 (interactive)
23801 (org-skip-whitespace)
23802 (let ((end (org-element-property :end (org-element-at-point))))
23803 (org-drag-element-backward)
23804 (goto-char end)))
23806 (defun org-unindent-buffer ()
23807 "Un-indent the visible part of the buffer.
23808 Relative indentation (between items, inside blocks, etc.) isn't
23809 modified."
23810 (interactive)
23811 (unless (eq major-mode 'org-mode)
23812 (user-error "Cannot un-indent a buffer not in Org mode"))
23813 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23814 unindent-tree ; For byte-compiler.
23815 (unindent-tree
23816 (function
23817 (lambda (contents)
23818 (mapc
23819 (lambda (element)
23820 (if (memq (org-element-type element) '(headline section))
23821 (funcall unindent-tree (org-element-contents element))
23822 (save-excursion
23823 (save-restriction
23824 (narrow-to-region
23825 (org-element-property :begin element)
23826 (org-element-property :end element))
23827 (org-do-remove-indentation)))))
23828 (reverse contents))))))
23829 (funcall unindent-tree (org-element-contents parse-tree))))
23831 (defun org-show-subtree ()
23832 "Show everything after this heading at deeper levels."
23833 (interactive)
23834 (outline-flag-region
23835 (point)
23836 (save-excursion
23837 (org-end-of-subtree t t))
23838 nil))
23840 (defun org-show-entry ()
23841 "Show the body directly following this heading.
23842 Show the heading too, if it is currently invisible."
23843 (interactive)
23844 (save-excursion
23845 (condition-case nil
23846 (progn
23847 (org-back-to-heading t)
23848 (outline-flag-region
23849 (max (point-min) (1- (point)))
23850 (save-excursion
23851 (if (re-search-forward
23852 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23853 (match-beginning 1)
23854 (point-max)))
23855 nil)
23856 (org-cycle-hide-drawers 'children))
23857 (error nil))))
23859 (defun org-make-options-regexp (kwds &optional extra)
23860 "Make a regular expression for keyword lines."
23861 (concat
23862 "^#\\+\\("
23863 (mapconcat 'regexp-quote kwds "\\|")
23864 (if extra (concat "\\|" extra))
23865 "\\):[ \t]*\\(.*\\)"))
23867 ;; Make isearch reveal the necessary context
23868 (defun org-isearch-end ()
23869 "Reveal context after isearch exits."
23870 (when isearch-success ; only if search was successful
23871 (if (featurep 'xemacs)
23872 ;; Under XEmacs, the hook is run in the correct place,
23873 ;; we directly show the context.
23874 (org-show-context 'isearch)
23875 ;; In Emacs the hook runs *before* restoring the overlays.
23876 ;; So we have to use a one-time post-command-hook to do this.
23877 ;; (Emacs 22 has a special variable, see function `org-mode')
23878 (unless (and (boundp 'isearch-mode-end-hook-quit)
23879 isearch-mode-end-hook-quit)
23880 ;; Only when the isearch was not quitted.
23881 (org-add-hook 'post-command-hook 'org-isearch-post-command
23882 'append 'local)))
23883 (org-fix-ellipsis-at-bol)))
23885 (defun org-isearch-post-command ()
23886 "Remove self from hook, and show context."
23887 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23888 (org-show-context 'isearch))
23891 ;;;; Integration with and fixes for other packages
23893 ;;; Imenu support
23895 (defvar org-imenu-markers nil
23896 "All markers currently used by Imenu.")
23897 (make-variable-buffer-local 'org-imenu-markers)
23899 (defun org-imenu-new-marker (&optional pos)
23900 "Return a new marker for use by Imenu, and remember the marker."
23901 (let ((m (make-marker)))
23902 (move-marker m (or pos (point)))
23903 (push m org-imenu-markers)
23906 (defun org-imenu-get-tree ()
23907 "Produce the index for Imenu."
23908 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23909 (setq org-imenu-markers nil)
23910 (let* ((n org-imenu-depth)
23911 (re (concat "^" (org-get-limited-outline-regexp)))
23912 (subs (make-vector (1+ n) nil))
23913 (last-level 0)
23914 m level head0 head)
23915 (save-excursion
23916 (save-restriction
23917 (widen)
23918 (goto-char (point-max))
23919 (while (re-search-backward re nil t)
23920 (setq level (org-reduced-level (funcall outline-level)))
23921 (when (and (<= level n)
23922 (looking-at org-complex-heading-regexp)
23923 (setq head0 (org-match-string-no-properties 4)))
23924 (setq head (org-link-display-format head0)
23925 m (org-imenu-new-marker))
23926 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23927 (if (>= level last-level)
23928 (push (cons head m) (aref subs level))
23929 (push (cons head (aref subs (1+ level))) (aref subs level))
23930 (loop for i from (1+ level) to n do (aset subs i nil)))
23931 (setq last-level level)))))
23932 (aref subs 1)))
23934 (eval-after-load "imenu"
23935 '(progn
23936 (add-hook 'imenu-after-jump-hook
23937 (lambda ()
23938 (if (derived-mode-p 'org-mode)
23939 (org-show-context 'org-goto))))))
23941 (defun org-link-display-format (link)
23942 "Replace a link with its the description.
23943 If there is no description, use the link target."
23944 (save-match-data
23945 (if (string-match org-bracket-link-analytic-regexp link)
23946 (replace-match (if (match-end 5)
23947 (match-string 5 link)
23948 (concat (match-string 1 link)
23949 (match-string 3 link)))
23950 nil t link)
23951 link)))
23953 (defun org-toggle-link-display ()
23954 "Toggle the literal or descriptive display of links."
23955 (interactive)
23956 (if org-descriptive-links
23957 (progn (org-remove-from-invisibility-spec '(org-link))
23958 (org-restart-font-lock)
23959 (setq org-descriptive-links nil))
23960 (progn (add-to-invisibility-spec '(org-link))
23961 (org-restart-font-lock)
23962 (setq org-descriptive-links t))))
23964 ;; Speedbar support
23966 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23967 "Overlay marking the agenda restriction line in speedbar.")
23968 (overlay-put org-speedbar-restriction-lock-overlay
23969 'face 'org-agenda-restriction-lock)
23970 (overlay-put org-speedbar-restriction-lock-overlay
23971 'help-echo "Agendas are currently limited to this item.")
23972 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23974 (defun org-speedbar-set-agenda-restriction ()
23975 "Restrict future agenda commands to the location at point in speedbar.
23976 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23977 (interactive)
23978 (require 'org-agenda)
23979 (let (p m tp np dir txt)
23980 (cond
23981 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23982 'org-imenu t))
23983 (setq m (get-text-property p 'org-imenu-marker))
23984 (with-current-buffer (marker-buffer m)
23985 (goto-char m)
23986 (org-agenda-set-restriction-lock 'subtree)))
23987 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23988 'speedbar-function 'speedbar-find-file))
23989 (setq tp (previous-single-property-change
23990 (1+ p) 'speedbar-function)
23991 np (next-single-property-change
23992 tp 'speedbar-function)
23993 dir (speedbar-line-directory)
23994 txt (buffer-substring-no-properties (or tp (point-min))
23995 (or np (point-max))))
23996 (with-current-buffer (find-file-noselect
23997 (let ((default-directory dir))
23998 (expand-file-name txt)))
23999 (unless (derived-mode-p 'org-mode)
24000 (user-error "Cannot restrict to non-Org-mode file"))
24001 (org-agenda-set-restriction-lock 'file)))
24002 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24003 (move-overlay org-speedbar-restriction-lock-overlay
24004 (point-at-bol) (point-at-eol))
24005 (setq current-prefix-arg nil)
24006 (org-agenda-maybe-redo)))
24008 (defvar speedbar-file-key-map)
24009 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24010 (eval-after-load "speedbar"
24011 '(progn
24012 (speedbar-add-supported-extension ".org")
24013 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24014 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24015 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24016 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24017 (add-hook 'speedbar-visiting-tag-hook
24018 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24020 ;;; Fixes and Hacks for problems with other packages
24022 (defun org-mode-flyspell-verify ()
24023 "Function used for `flyspell-generic-check-word-predicate'."
24024 (if (org-at-heading-p)
24025 ;; At a headline or an inlinetask, check title only. This is
24026 ;; faster than relying on `org-element-at-point'.
24027 (and (save-excursion (beginning-of-line)
24028 (and (let ((case-fold-search t))
24029 (not (looking-at "\\*+ END[ \t]*$")))
24030 (looking-at org-complex-heading-regexp)))
24031 (match-beginning 4)
24032 (>= (point) (match-beginning 4))
24033 (or (not (match-beginning 5))
24034 (< (point) (match-beginning 5))))
24035 (let* ((element (org-element-at-point))
24036 (post-affiliated (org-element-property :post-affiliated element))
24037 (object-check
24038 (function
24039 ;; Non-nil if checks can be done for object at point.
24040 (lambda ()
24041 (let ((object (save-excursion
24042 (when (org-looking-at-p "\\>") (backward-char))
24043 (org-element-context element))))
24044 (case (org-element-type object)
24045 ;; Prevent checks in links due to keybinding conflict
24046 ;; with Flyspell.
24047 ((code entity export-snippet inline-babel-call
24048 inline-src-block line-break latex-fragment link macro
24049 statistics-cookie target timestamp verbatim)
24050 nil)
24051 (footnote-reference
24052 ;; Only in inline footnotes, within the definition.
24053 (and (eq (org-element-property :type object) 'inline)
24054 (< (save-excursion
24055 (goto-char (org-element-property :begin object))
24056 (search-forward ":" nil t 2))
24057 (point))))
24058 (otherwise t)))))))
24059 (cond
24060 ;; Ignore checks in all affiliated keywords but captions.
24061 ((and post-affiliated (< (point) post-affiliated))
24062 (and (save-excursion
24063 (beginning-of-line)
24064 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24065 (> (point) (match-end 0))
24066 (funcall object-check)))
24067 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24068 ((and org-log-into-drawer
24069 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24070 (parent element))
24071 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24072 (setq parent (org-element-property :parent parent)))
24073 (and parent
24074 (eq (compare-strings
24075 log nil nil
24076 (org-element-property :drawer-name parent) nil nil t)
24077 t))))
24078 nil)
24080 (case (org-element-type element)
24081 ((comment quote-section) t)
24082 (comment-block
24083 ;; Allow checks between block markers, not on them.
24084 (and (> (line-beginning-position)
24085 (org-element-property :post-affiliated element))
24086 (save-excursion
24087 (end-of-line)
24088 (skip-chars-forward " \r\t\n")
24089 (< (point) (org-element-property :end element)))))
24090 ;; Arbitrary list of keywords where checks are meaningful.
24091 ;; Make sure point is on the value part of the element.
24092 (keyword
24093 (and (member (org-element-property :key element)
24094 '("DESCRIPTION" "TITLE"))
24095 (< (save-excursion
24096 (beginning-of-line) (search-forward ":") (point))
24097 (point))))
24098 ;; Check is globally allowed in paragraphs verse blocks and
24099 ;; table rows (after affiliated keywords) but some objects
24100 ;; must not be affected.
24101 ((paragraph table-row verse-block)
24102 (and (>= (point) (org-element-property :contents-begin element))
24103 (< (point) (org-element-property :contents-end element))
24104 (funcall object-check)))))))))
24105 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24107 (defun org-remove-flyspell-overlays-in (beg end)
24108 "Remove flyspell overlays in region."
24109 (and (org-bound-and-true-p flyspell-mode)
24110 (fboundp 'flyspell-delete-region-overlays)
24111 (flyspell-delete-region-overlays beg end)))
24113 (eval-after-load "flyspell"
24114 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24116 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24117 (eval-after-load "bookmark"
24118 '(if (boundp 'bookmark-after-jump-hook)
24119 ;; We can use the hook
24120 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24121 ;; Hook not available, use advice
24122 (defadvice bookmark-jump (after org-make-visible activate)
24123 "Make the position visible."
24124 (org-bookmark-jump-unhide))))
24126 ;; Make sure saveplace shows the location if it was hidden
24127 (eval-after-load "saveplace"
24128 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24129 "Make the position visible."
24130 (org-bookmark-jump-unhide)))
24132 ;; Make sure ecb shows the location if it was hidden
24133 (eval-after-load "ecb"
24134 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24135 "Make hierarchy visible when jumping into location from ECB tree buffer."
24136 (if (derived-mode-p 'org-mode)
24137 (org-show-context))))
24139 (defun org-bookmark-jump-unhide ()
24140 "Unhide the current position, to show the bookmark location."
24141 (and (derived-mode-p 'org-mode)
24142 (or (outline-invisible-p)
24143 (save-excursion (goto-char (max (point-min) (1- (point))))
24144 (outline-invisible-p)))
24145 (org-show-context 'bookmark-jump)))
24147 ;; Make session.el ignore our circular variable
24148 (defvar session-globals-exclude)
24149 (eval-after-load "session"
24150 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24152 ;;;; Finish up
24154 (provide 'org)
24156 (run-hooks 'org-load-hook)
24158 ;;; org.el ends here