Make org-store-link point to directory in a dired buffer
[rgr-org-mode.git] / lisp / org.el
blob9488bf6f35693b81d0b824cfc3f6c4db5adc3c1d
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.34trans
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/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum)
76 (require 'calendar))
77 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
78 ;; the file noutline.el being loaded.
79 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
80 ;; We require noutline, which might be provided in outline.el
81 (require 'outline) (require 'noutline)
82 ;; Other stuff we need.
83 (require 'time-date)
84 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
85 (require 'easymenu)
87 (require 'org-macs)
88 (require 'org-compat)
89 (require 'org-faces)
90 (require 'org-list)
91 (require 'org-src)
92 (require 'org-footnote)
94 ;;;; Customization variables
96 ;;; Version
98 (defconst org-version "6.34trans"
99 "The version number of the file org.el.")
101 (defun org-version (&optional here)
102 "Show the org-mode version in the echo area.
103 With prefix arg HERE, insert it at point."
104 (interactive "P")
105 (let* ((origin default-directory)
106 (version org-version)
107 (git-version)
108 (dir (concat (file-name-directory (locate-library "org")) "../" )))
109 (when (and (file-exists-p (expand-file-name ".git" dir))
110 (executable-find "git"))
111 (unwind-protect
112 (progn
113 (cd dir)
114 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
115 (with-current-buffer "*Shell Command Output*"
116 (goto-char (point-min))
117 (setq git-version (buffer-substring (point) (point-at-eol))))
118 (subst-char-in-string ?- ?. git-version t)
119 (when (string-match "\\S-"
120 (shell-command-to-string
121 "git diff-index --name-only HEAD --"))
122 (setq git-version (concat git-version ".dirty")))
123 (setq version (concat version " (" git-version ")"))))
124 (cd origin)))
125 (setq version (format "Org-mode version %s" version))
126 (if here (insert version))
127 (message version)))
129 ;;; Compatibility constants
131 ;;; The custom variables
133 (defgroup org nil
134 "Outline-based notes management and organizer."
135 :tag "Org"
136 :group 'outlines
137 :group 'hypermedia
138 :group 'calendar)
140 (defcustom org-mode-hook nil
141 "Mode hook for Org-mode, run after the mode was turned on."
142 :group 'org
143 :type 'hook)
145 (defcustom org-load-hook nil
146 "Hook that is run after org.el has been loaded."
147 :group 'org
148 :type 'hook)
150 (defvar org-modules) ; defined below
151 (defvar org-modules-loaded nil
152 "Have the modules been loaded already?")
154 (defun org-load-modules-maybe (&optional force)
155 "Load all extensions listed in `org-modules'."
156 (when (or force (not org-modules-loaded))
157 (mapc (lambda (ext)
158 (condition-case nil (require ext)
159 (error (message "Problems while trying to load feature `%s'" ext))))
160 org-modules)
161 (setq org-modules-loaded t)))
163 (defun org-set-modules (var value)
164 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
165 (set var value)
166 (when (featurep 'org)
167 (org-load-modules-maybe 'force)))
169 (when (org-bound-and-true-p org-modules)
170 (let ((a (member 'org-infojs org-modules)))
171 (and a (setcar a 'org-jsinfo))))
173 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
174 "Modules that should always be loaded together with org.el.
175 If a description starts with <C>, the file is not part of Emacs
176 and loading it will require that you have downloaded and properly installed
177 the org-mode distribution.
179 You can also use this system to load external packages (i.e. neither Org
180 core modules, nor modules from the CONTRIB directory). Just add symbols
181 to the end of the list. If the package is called org-xyz.el, then you need
182 to add the symbol `xyz', and the package must have a call to
184 (provide 'org-xyz)"
185 :group 'org
186 :set 'org-set-modules
187 :type
188 '(set :greedy t
189 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
190 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
191 (const :tag " crypt: Encryption of subtrees" org-crypt)
192 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
193 (const :tag " docview: Links to doc-view buffers" org-docview)
194 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
195 (const :tag " id: Global IDs for identifying entries" org-id)
196 (const :tag " info: Links to Info nodes" org-info)
197 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
198 (const :tag " habit: Track your consistency with habits" org-habit)
199 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
200 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
201 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
202 (const :tag " mew Links to Mew folders/messages" org-mew)
203 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
204 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
205 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
206 (const :tag " vm: Links to VM folders/messages" org-vm)
207 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
208 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
209 (const :tag " mouse: Additional mouse support" org-mouse)
211 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
212 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
213 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
214 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
215 (const :tag "C collector: Collect properties into tables" org-collector)
216 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
217 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
218 (const :tag "C eval: Include command output as text" org-eval)
219 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
220 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
221 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
222 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
223 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
225 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
227 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
228 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
229 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
230 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
231 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
232 (const :tag "C mtags: Support for muse-like tags" org-mtags)
233 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
234 (const :tag "C R: Computation using the R language" org-R)
235 (const :tag "C registry: A registry for Org-mode links" org-registry)
236 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
237 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
238 (const :tag "C secretary: Team management with org-mode" org-secretary)
239 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
240 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
241 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
242 (const :tag "C track: Keep up with Org-mode development" org-track)
243 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
245 (defcustom org-support-shift-select nil
246 "Non-nil means make shift-cursor commands select text when possible.
248 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
249 selecting a region, or enlarge thusly regions started in this way.
250 In Org-mode, in special contexts, these same keys are used for other
251 purposes, important enough to compete with shift selection. Org tries
252 to balance these needs by supporting `shift-select-mode' outside these
253 special contexts, under control of this variable.
255 The default of this variable is nil, to avoid confusing behavior. Shifted
256 cursor keys will then execute Org commands in the following contexts:
257 - on a headline, changing TODO state (left/right) and priority (up/down)
258 - on a time stamp, changing the time
259 - in a plain list item, changing the bullet type
260 - in a property definition line, switching between allowed values
261 - in the BEGIN line of a clock table (changing the time block).
262 Outside these contexts, the commands will throw an error.
264 When this variable is t and the cursor is not in a special context,
265 Org-mode will support shift-selection for making and enlarging regions.
266 To make this more effective, the bullet cycling will no longer happen
267 anywhere in an item line, but only if the cursor is exactly on the bullet.
269 If you set this variable to the symbol `always', then the keys
270 will not be special in headlines, property lines, and item lines, to make
271 shift selection work there as well. If this is what you want, you can
272 use the following alternative commands: `C-c C-t' and `C-c ,' to
273 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
274 TODO sets, `C-c -' to cycle item bullet types, and properties can be
275 edited by hand or in column view.
277 However, when the cursor is on a timestamp, shift-cursor commands
278 will still edit the time stamp - this is just too good to give up.
280 XEmacs user should have this variable set to nil, because shift-select-mode
281 is Emacs 23 only."
282 :group 'org
283 :type '(choice
284 (const :tag "Never" nil)
285 (const :tag "When outside special context" t)
286 (const :tag "Everywhere except timestamps" always)))
288 (defgroup org-startup nil
289 "Options concerning startup of Org-mode."
290 :tag "Org Startup"
291 :group 'org)
293 (defcustom org-startup-folded t
294 "Non-nil means entering Org-mode will switch to OVERVIEW.
295 This can also be configured on a per-file basis by adding one of
296 the following lines anywhere in the buffer:
298 #+STARTUP: fold (or `overview', this is equivalent)
299 #+STARTUP: nofold (or `showall', this is equivalent)
300 #+STARTUP: content
301 #+STARTUP: showeverything"
302 :group 'org-startup
303 :type '(choice
304 (const :tag "nofold: show all" nil)
305 (const :tag "fold: overview" t)
306 (const :tag "content: all headlines" content)
307 (const :tag "show everything, even drawers" showeverything)))
309 (defcustom org-startup-truncated t
310 "Non-nil means entering Org-mode will set `truncate-lines'.
311 This is useful since some lines containing links can be very long and
312 uninteresting. Also tables look terrible when wrapped."
313 :group 'org-startup
314 :type 'boolean)
316 (defcustom org-startup-indented nil
317 "Non-nil means turn on `org-indent-mode' on startup.
318 This can also be configured on a per-file basis by adding one of
319 the following lines anywhere in the buffer:
321 #+STARTUP: indent
322 #+STARTUP: noindent"
323 :group 'org-structure
324 :type '(choice
325 (const :tag "Not" nil)
326 (const :tag "Globally (slow on startup in large files)" t)))
328 (defcustom org-startup-with-beamer-mode nil
329 "Non-nil means turn on `org-beamer-mode' on startup.
330 This can also be configured on a per-file basis by adding one of
331 the following lines anywhere in the buffer:
333 #+STARTUP: beamer"
334 :group 'org-startup
335 :type 'boolean)
337 (defcustom org-startup-align-all-tables nil
338 "Non-nil means align all tables when visiting a file.
339 This is useful when the column width in tables is forced with <N> cookies
340 in table fields. Such tables will look correct only after the first re-align.
341 This can also be configured on a per-file basis by adding one of
342 the following lines anywhere in the buffer:
343 #+STARTUP: align
344 #+STARTUP: noalign"
345 :group 'org-startup
346 :type 'boolean)
348 (defcustom org-insert-mode-line-in-empty-file nil
349 "Non-nil means insert the first line setting Org-mode in empty files.
350 When the function `org-mode' is called interactively in an empty file, this
351 normally means that the file name does not automatically trigger Org-mode.
352 To ensure that the file will always be in Org-mode in the future, a
353 line enforcing Org-mode will be inserted into the buffer, if this option
354 has been set."
355 :group 'org-startup
356 :type 'boolean)
358 (defcustom org-replace-disputed-keys nil
359 "Non-nil means use alternative key bindings for some keys.
360 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
361 These keys are also used by other packages like shift-selection-mode'
362 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
363 If you want to use Org-mode together with one of these other modes,
364 or more generally if you would like to move some Org-mode commands to
365 other keys, set this variable and configure the keys with the variable
366 `org-disputed-keys'.
368 This option is only relevant at load-time of Org-mode, and must be set
369 *before* org.el is loaded. Changing it requires a restart of Emacs to
370 become effective."
371 :group 'org-startup
372 :type 'boolean)
374 (defcustom org-use-extra-keys nil
375 "Non-nil means use extra key sequence definitions for certain
376 commands. This happens automatically if you run XEmacs or if
377 window-system is nil. This variable lets you do the same
378 manually. You must set it before loading org.
380 Example: on Carbon Emacs 22 running graphically, with an external
381 keyboard on a Powerbook, the default way of setting M-left might
382 not work for either Alt or ESC. Setting this variable will make
383 it work for ESC."
384 :group 'org-startup
385 :type 'boolean)
387 (if (fboundp 'defvaralias)
388 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
390 (defcustom org-disputed-keys
391 '(([(shift up)] . [(meta p)])
392 ([(shift down)] . [(meta n)])
393 ([(shift left)] . [(meta -)])
394 ([(shift right)] . [(meta +)])
395 ([(control shift right)] . [(meta shift +)])
396 ([(control shift left)] . [(meta shift -)]))
397 "Keys for which Org-mode and other modes compete.
398 This is an alist, cars are the default keys, second element specifies
399 the alternative to use when `org-replace-disputed-keys' is t.
401 Keys can be specified in any syntax supported by `define-key'.
402 The value of this option takes effect only at Org-mode's startup,
403 therefore you'll have to restart Emacs to apply it after changing."
404 :group 'org-startup
405 :type 'alist)
407 (defun org-key (key)
408 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
409 Or return the original if not disputed."
410 (if org-replace-disputed-keys
411 (let* ((nkey (key-description key))
412 (x (org-find-if (lambda (x)
413 (equal (key-description (car x)) nkey))
414 org-disputed-keys)))
415 (if x (cdr x) key))
416 key))
418 (defun org-find-if (predicate seq)
419 (catch 'exit
420 (while seq
421 (if (funcall predicate (car seq))
422 (throw 'exit (car seq))
423 (pop seq)))))
425 (defun org-defkey (keymap key def)
426 "Define a key, possibly translated, as returned by `org-key'."
427 (define-key keymap (org-key key) def))
429 (defcustom org-ellipsis nil
430 "The ellipsis to use in the Org-mode outline.
431 When nil, just use the standard three dots. When a string, use that instead,
432 When a face, use the standard 3 dots, but with the specified face.
433 The change affects only Org-mode (which will then use its own display table).
434 Changing this requires executing `M-x org-mode' in a buffer to become
435 effective."
436 :group 'org-startup
437 :type '(choice (const :tag "Default" nil)
438 (face :tag "Face" :value org-warning)
439 (string :tag "String" :value "...#")))
441 (defvar org-display-table nil
442 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
444 (defgroup org-keywords nil
445 "Keywords in Org-mode."
446 :tag "Org Keywords"
447 :group 'org)
449 (defcustom org-deadline-string "DEADLINE:"
450 "String to mark deadline entries.
451 A deadline is this string, followed by a time stamp. Should be a word,
452 terminated by a colon. You can insert a schedule keyword and
453 a timestamp with \\[org-deadline].
454 Changes become only effective after restarting Emacs."
455 :group 'org-keywords
456 :type 'string)
458 (defcustom org-scheduled-string "SCHEDULED:"
459 "String to mark scheduled TODO entries.
460 A schedule is this string, followed by a time stamp. Should be a word,
461 terminated by a colon. You can insert a schedule keyword and
462 a timestamp with \\[org-schedule].
463 Changes become only effective after restarting Emacs."
464 :group 'org-keywords
465 :type 'string)
467 (defcustom org-closed-string "CLOSED:"
468 "String used as the prefix for timestamps logging closing a TODO entry."
469 :group 'org-keywords
470 :type 'string)
472 (defcustom org-clock-string "CLOCK:"
473 "String used as prefix for timestamps clocking work hours on an item."
474 :group 'org-keywords
475 :type 'string)
477 (defcustom org-comment-string "COMMENT"
478 "Entries starting with this keyword will never be exported.
479 An entry can be toggled between COMMENT and normal with
480 \\[org-toggle-comment].
481 Changes become only effective after restarting Emacs."
482 :group 'org-keywords
483 :type 'string)
485 (defcustom org-quote-string "QUOTE"
486 "Entries starting with this keyword will be exported in fixed-width font.
487 Quoting applies only to the text in the entry following the headline, and does
488 not extend beyond the next headline, even if that is lower level.
489 An entry can be toggled between QUOTE and normal with
490 \\[org-toggle-fixed-width-section]."
491 :group 'org-keywords
492 :type 'string)
494 (defconst org-repeat-re
495 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
496 "Regular expression for specifying repeated events.
497 After a match, group 1 contains the repeat expression.")
499 (defgroup org-structure nil
500 "Options concerning the general structure of Org-mode files."
501 :tag "Org Structure"
502 :group 'org)
504 (defgroup org-reveal-location nil
505 "Options about how to make context of a location visible."
506 :tag "Org Reveal Location"
507 :group 'org-structure)
509 (defconst org-context-choice
510 '(choice
511 (const :tag "Always" t)
512 (const :tag "Never" nil)
513 (repeat :greedy t :tag "Individual contexts"
514 (cons
515 (choice :tag "Context"
516 (const agenda)
517 (const org-goto)
518 (const occur-tree)
519 (const tags-tree)
520 (const link-search)
521 (const mark-goto)
522 (const bookmark-jump)
523 (const isearch)
524 (const default))
525 (boolean))))
526 "Contexts for the reveal options.")
528 (defcustom org-show-hierarchy-above '((default . t))
529 "Non-nil means show full hierarchy when revealing a location.
530 Org-mode often shows locations in an org-mode file which might have
531 been invisible before. When this is set, the hierarchy of headings
532 above the exposed location is shown.
533 Turning this off for example for sparse trees makes them very compact.
534 Instead of t, this can also be an alist specifying this option for different
535 contexts. Valid contexts are
536 agenda when exposing an entry from the agenda
537 org-goto when using the command `org-goto' on key C-c C-j
538 occur-tree when using the command `org-occur' on key C-c /
539 tags-tree when constructing a sparse tree based on tags matches
540 link-search when exposing search matches associated with a link
541 mark-goto when exposing the jump goal of a mark
542 bookmark-jump when exposing a bookmark location
543 isearch when exiting from an incremental search
544 default default for all contexts not set explicitly"
545 :group 'org-reveal-location
546 :type org-context-choice)
548 (defcustom org-show-following-heading '((default . nil))
549 "Non-nil means show following heading when revealing a location.
550 Org-mode often shows locations in an org-mode file which might have
551 been invisible before. When this is set, the heading following the
552 match is shown.
553 Turning this off for example for sparse trees makes them very compact,
554 but makes it harder to edit the location of the match. In such a case,
555 use the command \\[org-reveal] to show more context.
556 Instead of t, this can also be an alist specifying this option for different
557 contexts. See `org-show-hierarchy-above' for valid contexts."
558 :group 'org-reveal-location
559 :type org-context-choice)
561 (defcustom org-show-siblings '((default . nil) (isearch t))
562 "Non-nil means show all sibling heading when revealing a location.
563 Org-mode often shows locations in an org-mode file which might have
564 been invisible before. When this is set, the sibling of the current entry
565 heading are all made visible. If `org-show-hierarchy-above' is t,
566 the same happens on each level of the hierarchy above the current entry.
568 By default this is on for the isearch context, off for all other contexts.
569 Turning this off for example for sparse trees makes them very compact,
570 but makes it harder to edit the location of the match. In such a case,
571 use the command \\[org-reveal] to show more context.
572 Instead of t, this can also be an alist specifying this option for different
573 contexts. See `org-show-hierarchy-above' for valid contexts."
574 :group 'org-reveal-location
575 :type org-context-choice)
577 (defcustom org-show-entry-below '((default . nil))
578 "Non-nil means show the entry below a headline when revealing a location.
579 Org-mode often shows locations in an org-mode file which might have
580 been invisible before. When this is set, the text below the headline that is
581 exposed is also shown.
583 By default this is off for all contexts.
584 Instead of t, this can also be an alist specifying this option for different
585 contexts. See `org-show-hierarchy-above' for valid contexts."
586 :group 'org-reveal-location
587 :type org-context-choice)
589 (defcustom org-indirect-buffer-display 'other-window
590 "How should indirect tree buffers be displayed?
591 This applies to indirect buffers created with the commands
592 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
593 Valid values are:
594 current-window Display in the current window
595 other-window Just display in another window.
596 dedicated-frame Create one new frame, and re-use it each time.
597 new-frame Make a new frame each time. Note that in this case
598 previously-made indirect buffers are kept, and you need to
599 kill these buffers yourself."
600 :group 'org-structure
601 :group 'org-agenda-windows
602 :type '(choice
603 (const :tag "In current window" current-window)
604 (const :tag "In current frame, other window" other-window)
605 (const :tag "Each time a new frame" new-frame)
606 (const :tag "One dedicated frame" dedicated-frame)))
608 (defcustom org-use-speed-commands nil
609 "Non-nil means activate single letter commands at beginning of a headline.
610 This may also be a function to test for appropriate locations where speed
611 commands should be active."
612 :group 'org-structure
613 :type '(choice
614 (const :tag "Never" nil)
615 (const :tag "At beginning of headline stars" t)
616 (function)))
618 (defcustom org-speed-commands-user nil
619 "Alist of additional speed commands.
620 This list will be checked before `org-speed-commands-default'
621 when the variable `org-use-speed-commands' is non-nil
622 and when the cursor is at the beginning of a headline.
623 The car if each entry is a string with a single letter, which must
624 be assigned to `self-insert-command' in the global map.
625 The cdr is either a command to be called interactively, a function
626 to be called, or a form to be evaluated.
627 An entry that is just a list with a single string will be interpreted
628 as a descriptive headline that will be added when listing the speed
629 copmmands in the Help buffer using the `?' speed command."
630 :group 'org-structure
631 :type '(repeat :value ("k" . ignore)
632 (choice :value ("k" . ignore)
633 (list :tag "Descriptive Headline" (string :tag "Headline"))
634 (cons :tag "Letter and Command"
635 (string :tag "Command letter")
636 (choice
637 (function)
638 (sexp))))))
640 (defgroup org-cycle nil
641 "Options concerning visibility cycling in Org-mode."
642 :tag "Org Cycle"
643 :group 'org-structure)
645 (defcustom org-cycle-skip-children-state-if-no-children t
646 "Non-nil means skip CHILDREN state in entries that don't have any."
647 :group 'org-cycle
648 :type 'boolean)
650 (defcustom org-cycle-max-level nil
651 "Maximum level which should still be subject to visibility cycling.
652 Levels higher than this will, for cycling, be treated as text, not a headline.
653 When `org-odd-levels-only' is set, a value of N in this variable actually
654 means 2N-1 stars as the limiting headline.
655 When nil, cycle all levels.
656 Note that the limiting level of cycling is also influenced by
657 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
658 `org-inlinetask-min-level' is, cycling will be limited to levels one less
659 than its value."
660 :group 'org-cycle
661 :type '(choice
662 (const :tag "No limit" nil)
663 (integer :tag "Maximum level")))
665 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
666 "Names of drawers. Drawers are not opened by cycling on the headline above.
667 Drawers only open with a TAB on the drawer line itself. A drawer looks like
668 this:
669 :DRAWERNAME:
670 .....
671 :END:
672 The drawer \"PROPERTIES\" is special for capturing properties through
673 the property API.
675 Drawers can be defined on the per-file basis with a line like:
677 #+DRAWERS: HIDDEN STATE PROPERTIES"
678 :group 'org-structure
679 :group 'org-cycle
680 :type '(repeat (string :tag "Drawer Name")))
682 (defcustom org-hide-block-startup nil
683 "Non-nil means entering Org-mode will fold all blocks.
684 This can also be set in on a per-file basis with
686 #+STARTUP: hideblocks
687 #+STARTUP: showblocks"
688 :group 'org-startup
689 :group 'org-cycle
690 :type 'boolean)
692 (defcustom org-cycle-global-at-bob nil
693 "Cycle globally if cursor is at beginning of buffer and not at a headline.
694 This makes it possible to do global cycling without having to use S-TAB or
695 C-u TAB. For this special case to work, the first line of the buffer
696 must not be a headline - it may be empty or some other text. When used in
697 this way, `org-cycle-hook' is disables temporarily, to make sure the
698 cursor stays at the beginning of the buffer.
699 When this option is nil, don't do anything special at the beginning
700 of the buffer."
701 :group 'org-cycle
702 :type 'boolean)
704 (defcustom org-cycle-level-after-item/entry-creation t
705 "Non-nil means cycle entry level or item indentation in new empty entries.
707 When the cursor is at the end of an empty headline, i.e with only stars
708 and maybe a TODO keyword, TAB will then switch the entry to become a child,
709 and then all possible anchestor states, before returning to the original state.
710 This makes data entry extremely fast: M-RET to create a new headline,
711 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
713 When the cursor is at the end of an empty plain list item, one TAB will
714 make it a subitem, two or more tabs will back up to make this an item
715 higher up in the item hierarchy."
716 :group 'org-cycle
717 :type 'boolean)
719 (defcustom org-cycle-emulate-tab t
720 "Where should `org-cycle' emulate TAB.
721 nil Never
722 white Only in completely white lines
723 whitestart Only at the beginning of lines, before the first non-white char
724 t Everywhere except in headlines
725 exc-hl-bol Everywhere except at the start of a headline
726 If TAB is used in a place where it does not emulate TAB, the current subtree
727 visibility is cycled."
728 :group 'org-cycle
729 :type '(choice (const :tag "Never" nil)
730 (const :tag "Only in completely white lines" white)
731 (const :tag "Before first char in a line" whitestart)
732 (const :tag "Everywhere except in headlines" t)
733 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
736 (defcustom org-cycle-separator-lines 2
737 "Number of empty lines needed to keep an empty line between collapsed trees.
738 If you leave an empty line between the end of a subtree and the following
739 headline, this empty line is hidden when the subtree is folded.
740 Org-mode will leave (exactly) one empty line visible if the number of
741 empty lines is equal or larger to the number given in this variable.
742 So the default 2 means at least 2 empty lines after the end of a subtree
743 are needed to produce free space between a collapsed subtree and the
744 following headline.
746 If the number is negative, and the number of empty lines is at least -N,
747 all empty lines are shown.
749 Special case: when 0, never leave empty lines in collapsed view."
750 :group 'org-cycle
751 :type 'integer)
752 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
754 (defcustom org-pre-cycle-hook nil
755 "Hook that is run before visibility cycling is happening.
756 The function(s) in this hook must accept a single argument which indicates
757 the new state that will be set right after running this hook. The
758 argument is a symbol. Before a global state change, it can have the values
759 `overview', `content', or `all'. Before a local state change, it can have
760 the values `folded', `children', or `subtree'."
761 :group 'org-cycle
762 :type 'hook)
764 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
765 org-cycle-hide-drawers
766 org-cycle-show-empty-lines
767 org-optimize-window-after-visibility-change)
768 "Hook that is run after `org-cycle' has changed the buffer visibility.
769 The function(s) in this hook must accept a single argument which indicates
770 the new state that was set by the most recent `org-cycle' command. The
771 argument is a symbol. After a global state change, it can have the values
772 `overview', `content', or `all'. After a local state change, it can have
773 the values `folded', `children', or `subtree'."
774 :group 'org-cycle
775 :type 'hook)
777 (defgroup org-edit-structure nil
778 "Options concerning structure editing in Org-mode."
779 :tag "Org Edit Structure"
780 :group 'org-structure)
782 (defcustom org-odd-levels-only nil
783 "Non-nil means skip even levels and only use odd levels for the outline.
784 This has the effect that two stars are being added/taken away in
785 promotion/demotion commands. It also influences how levels are
786 handled by the exporters.
787 Changing it requires restart of `font-lock-mode' to become effective
788 for fontification also in regions already fontified.
789 You may also set this on a per-file basis by adding one of the following
790 lines to the buffer:
792 #+STARTUP: odd
793 #+STARTUP: oddeven"
794 :group 'org-edit-structure
795 :group 'org-font-lock
796 :type 'boolean)
798 (defcustom org-adapt-indentation t
799 "Non-nil means adapt indentation to outline node level.
801 When this variable is set, Org assumes that you write outlines by
802 indenting text in each node to align with the headline (after the stars).
803 The following issues are influenced by this variable:
805 - When this is set and the *entire* text in an entry is indented, the
806 indentation is increased by one space in a demotion command, and
807 decreased by one in a promotion command. If any line in the entry
808 body starts with text at column 0, indentation is not changed at all.
810 - Property drawers and planning information is inserted indented when
811 this variable s set. When nil, they will not be indented.
813 - TAB indents a line relative to context. The lines below a headline
814 will be indented when this variable is set.
816 Note that this is all about true indentation, by adding and removing
817 space characters. See also `org-indent.el' which does level-dependent
818 indentation in a virtual way, i.e. at display time in Emacs."
819 :group 'org-edit-structure
820 :type 'boolean)
822 (defcustom org-special-ctrl-a/e nil
823 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
825 When t, `C-a' will bring back the cursor to the beginning of the
826 headline text, i.e. after the stars and after a possible TODO keyword.
827 In an item, this will be the position after the bullet.
828 When the cursor is already at that position, another `C-a' will bring
829 it to the beginning of the line.
831 `C-e' will jump to the end of the headline, ignoring the presence of tags
832 in the headline. A second `C-e' will then jump to the true end of the
833 line, after any tags. This also means that, when this variable is
834 non-nil, `C-e' also will never jump beyond the end of the heading of a
835 folded section, i.e. not after the ellipses.
837 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
838 going to the true line boundary first. Only a directly following, identical
839 keypress will bring the cursor to the special positions.
841 This may also be a cons cell where the behavior for `C-a' and `C-e' is
842 set separately."
843 :group 'org-edit-structure
844 :type '(choice
845 (const :tag "off" nil)
846 (const :tag "on: after stars/bullet and before tags first" t)
847 (const :tag "reversed: true line boundary first" reversed)
848 (cons :tag "Set C-a and C-e separately"
849 (choice :tag "Special C-a"
850 (const :tag "off" nil)
851 (const :tag "on: after stars/bullet first" t)
852 (const :tag "reversed: before stars/bullet first" reversed))
853 (choice :tag "Special C-e"
854 (const :tag "off" nil)
855 (const :tag "on: before tags first" t)
856 (const :tag "reversed: after tags first" reversed)))))
857 (if (fboundp 'defvaralias)
858 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
860 (defcustom org-special-ctrl-k nil
861 "Non-nil means `C-k' will behave specially in headlines.
862 When nil, `C-k' will call the default `kill-line' command.
863 When t, the following will happen while the cursor is in the headline:
865 - When the cursor is at the beginning of a headline, kill the entire
866 line and possible the folded subtree below the line.
867 - When in the middle of the headline text, kill the headline up to the tags.
868 - When after the headline text, kill the tags."
869 :group 'org-edit-structure
870 :type 'boolean)
872 (defcustom org-yank-folded-subtrees t
873 "Non-nil means when yanking subtrees, fold them.
874 If the kill is a single subtree, or a sequence of subtrees, i.e. if
875 it starts with a heading and all other headings in it are either children
876 or siblings, then fold all the subtrees. However, do this only if no
877 text after the yank would be swallowed into a folded tree by this action."
878 :group 'org-edit-structure
879 :type 'boolean)
881 (defcustom org-yank-adjusted-subtrees nil
882 "Non-nil means when yanking subtrees, adjust the level.
883 With this setting, `org-paste-subtree' is used to insert the subtree, see
884 this function for details."
885 :group 'org-edit-structure
886 :type 'boolean)
888 (defcustom org-M-RET-may-split-line '((default . t))
889 "Non-nil means M-RET will split the line at the cursor position.
890 When nil, it will go to the end of the line before making a
891 new line.
892 You may also set this option in a different way for different
893 contexts. Valid contexts are:
895 headline when creating a new headline
896 item when creating a new item
897 table in a table field
898 default the value to be used for all contexts not explicitly
899 customized"
900 :group 'org-structure
901 :group 'org-table
902 :type '(choice
903 (const :tag "Always" t)
904 (const :tag "Never" nil)
905 (repeat :greedy t :tag "Individual contexts"
906 (cons
907 (choice :tag "Context"
908 (const headline)
909 (const item)
910 (const table)
911 (const default))
912 (boolean)))))
915 (defcustom org-insert-heading-respect-content nil
916 "Non-nil means insert new headings after the current subtree.
917 When nil, the new heading is created directly after the current line.
918 The commands \\[org-insert-heading-respect-content] and
919 \\[org-insert-todo-heading-respect-content] turn this variable on
920 for the duration of the command."
921 :group 'org-structure
922 :type 'boolean)
924 (defcustom org-blank-before-new-entry '((heading . auto)
925 (plain-list-item . auto))
926 "Should `org-insert-heading' leave a blank line before new heading/item?
927 The value is an alist, with `heading' and `plain-list-item' as car,
928 and a boolean flag as cdr. For plain lists, if the variable
929 `org-empty-line-terminates-plain-lists' is set, the setting here
930 is ignored and no empty line is inserted, to keep the list in tact."
931 :group 'org-edit-structure
932 :type '(list
933 (cons (const heading)
934 (choice (const :tag "Never" nil)
935 (const :tag "Always" t)
936 (const :tag "Auto" auto)))
937 (cons (const plain-list-item)
938 (choice (const :tag "Never" nil)
939 (const :tag "Always" t)
940 (const :tag "Auto" auto)))))
942 (defcustom org-insert-heading-hook nil
943 "Hook being run after inserting a new heading."
944 :group 'org-edit-structure
945 :type 'hook)
947 (defcustom org-enable-fixed-width-editor t
948 "Non-nil means lines starting with \":\" are treated as fixed-width.
949 This currently only means they are never auto-wrapped.
950 When nil, such lines will be treated like ordinary lines.
951 See also the QUOTE keyword."
952 :group 'org-edit-structure
953 :type 'boolean)
956 (defcustom org-goto-auto-isearch t
957 "Non-nil means typing characters in org-goto starts incremental search."
958 :group 'org-edit-structure
959 :type 'boolean)
961 (defgroup org-sparse-trees nil
962 "Options concerning sparse trees in Org-mode."
963 :tag "Org Sparse Trees"
964 :group 'org-structure)
966 (defcustom org-highlight-sparse-tree-matches t
967 "Non-nil means highlight all matches that define a sparse tree.
968 The highlights will automatically disappear the next time the buffer is
969 changed by an edit command."
970 :group 'org-sparse-trees
971 :type 'boolean)
973 (defcustom org-remove-highlights-with-change t
974 "Non-nil means any change to the buffer will remove temporary highlights.
975 Such highlights are created by `org-occur' and `org-clock-display'.
976 When nil, `C-c C-c needs to be used to get rid of the highlights.
977 The highlights created by `org-preview-latex-fragment' always need
978 `C-c C-c' to be removed."
979 :group 'org-sparse-trees
980 :group 'org-time
981 :type 'boolean)
984 (defcustom org-occur-hook '(org-first-headline-recenter)
985 "Hook that is run after `org-occur' has constructed a sparse tree.
986 This can be used to recenter the window to show as much of the structure
987 as possible."
988 :group 'org-sparse-trees
989 :type 'hook)
991 (defgroup org-imenu-and-speedbar nil
992 "Options concerning imenu and speedbar in Org-mode."
993 :tag "Org Imenu and Speedbar"
994 :group 'org-structure)
996 (defcustom org-imenu-depth 2
997 "The maximum level for Imenu access to Org-mode headlines.
998 This also applied for speedbar access."
999 :group 'org-imenu-and-speedbar
1000 :type 'integer)
1002 (defgroup org-table nil
1003 "Options concerning tables in Org-mode."
1004 :tag "Org Table"
1005 :group 'org)
1007 (defcustom org-enable-table-editor 'optimized
1008 "Non-nil means lines starting with \"|\" are handled by the table editor.
1009 When nil, such lines will be treated like ordinary lines.
1011 When equal to the symbol `optimized', the table editor will be optimized to
1012 do the following:
1013 - Automatic overwrite mode in front of whitespace in table fields.
1014 This makes the structure of the table stay in tact as long as the edited
1015 field does not exceed the column width.
1016 - Minimize the number of realigns. Normally, the table is aligned each time
1017 TAB or RET are pressed to move to another field. With optimization this
1018 happens only if changes to a field might have changed the column width.
1019 Optimization requires replacing the functions `self-insert-command',
1020 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1021 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1022 very good at guessing when a re-align will be necessary, but you can always
1023 force one with \\[org-ctrl-c-ctrl-c].
1025 If you would like to use the optimized version in Org-mode, but the
1026 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1028 This variable can be used to turn on and off the table editor during a session,
1029 but in order to toggle optimization, a restart is required.
1031 See also the variable `org-table-auto-blank-field'."
1032 :group 'org-table
1033 :type '(choice
1034 (const :tag "off" nil)
1035 (const :tag "on" t)
1036 (const :tag "on, optimized" optimized)))
1038 (defcustom org-self-insert-cluster-for-undo t
1039 "Non-nil means cluster self-insert commands for undo when possible.
1040 If this is set, then, like in the Emacs command loop, 20 consecutive
1041 characters will be undone together.
1042 This is configurable, because there is some impact on typing performance."
1043 :group 'org-table
1044 :type 'boolean)
1046 (defcustom org-table-tab-recognizes-table.el t
1047 "Non-nil means TAB will automatically notice a table.el table.
1048 When it sees such a table, it moves point into it and - if necessary -
1049 calls `table-recognize-table'."
1050 :group 'org-table-editing
1051 :type 'boolean)
1053 (defgroup org-link nil
1054 "Options concerning links in Org-mode."
1055 :tag "Org Link"
1056 :group 'org)
1058 (defvar org-link-abbrev-alist-local nil
1059 "Buffer-local version of `org-link-abbrev-alist', which see.
1060 The value of this is taken from the #+LINK lines.")
1061 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1063 (defcustom org-link-abbrev-alist nil
1064 "Alist of link abbreviations.
1065 The car of each element is a string, to be replaced at the start of a link.
1066 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1067 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1069 [[linkkey:tag][description]]
1071 The 'linkkey' must be a word word, starting with a letter, followed
1072 by letters, numbers, '-' or '_'.
1074 If REPLACE is a string, the tag will simply be appended to create the link.
1075 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1076 the placeholder \"%h\" will cause a url-encoded version of the tag to
1077 be inserted at that point (see the function `url-hexify-string').
1079 REPLACE may also be a function that will be called with the tag as the
1080 only argument to create the link, which should be returned as a string.
1082 See the manual for examples."
1083 :group 'org-link
1084 :type '(repeat
1085 (cons
1086 (string :tag "Protocol")
1087 (choice
1088 (string :tag "Format")
1089 (function)))))
1091 (defcustom org-descriptive-links t
1092 "Non-nil means hide link part and only show description of bracket links.
1093 Bracket links are like [[link][description]]. This variable sets the initial
1094 state in new org-mode buffers. The setting can then be toggled on a
1095 per-buffer basis from the Org->Hyperlinks menu."
1096 :group 'org-link
1097 :type 'boolean)
1099 (defcustom org-link-file-path-type 'adaptive
1100 "How the path name in file links should be stored.
1101 Valid values are:
1103 relative Relative to the current directory, i.e. the directory of the file
1104 into which the link is being inserted.
1105 absolute Absolute path, if possible with ~ for home directory.
1106 noabbrev Absolute path, no abbreviation of home directory.
1107 adaptive Use relative path for files in the current directory and sub-
1108 directories of it. For other files, use an absolute path."
1109 :group 'org-link
1110 :type '(choice
1111 (const relative)
1112 (const absolute)
1113 (const noabbrev)
1114 (const adaptive)))
1116 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1117 "Types of links that should be activated in Org-mode files.
1118 This is a list of symbols, each leading to the activation of a certain link
1119 type. In principle, it does not hurt to turn on most link types - there may
1120 be a small gain when turning off unused link types. The types are:
1122 bracket The recommended [[link][description]] or [[link]] links with hiding.
1123 angular Links in angular brackets that may contain whitespace like
1124 <bbdb:Carsten Dominik>.
1125 plain Plain links in normal text, no whitespace, like http://google.com.
1126 radio Text that is matched by a radio target, see manual for details.
1127 tag Tag settings in a headline (link to tag search).
1128 date Time stamps (link to calendar).
1129 footnote Footnote labels.
1131 Changing this variable requires a restart of Emacs to become effective."
1132 :group 'org-link
1133 :type '(set :greedy t
1134 (const :tag "Double bracket links (new style)" bracket)
1135 (const :tag "Angular bracket links (old style)" angular)
1136 (const :tag "Plain text links" plain)
1137 (const :tag "Radio target matches" radio)
1138 (const :tag "Tags" tag)
1139 (const :tag "Timestamps" date)
1140 (const :tag "Footnotes" footnote)))
1142 (defcustom org-make-link-description-function nil
1143 "Function to use to generate link descriptions from links. If
1144 nil the link location will be used. This function must take two
1145 parameters; the first is the link and the second the description
1146 org-insert-link has generated, and should return the description
1147 to use."
1148 :group 'org-link
1149 :type 'function)
1151 (defgroup org-link-store nil
1152 "Options concerning storing links in Org-mode."
1153 :tag "Org Store Link"
1154 :group 'org-link)
1156 (defcustom org-email-link-description-format "Email %c: %.30s"
1157 "Format of the description part of a link to an email or usenet message.
1158 The following %-escapes will be replaced by corresponding information:
1160 %F full \"From\" field
1161 %f name, taken from \"From\" field, address if no name
1162 %T full \"To\" field
1163 %t first name in \"To\" field, address if no name
1164 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1165 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1166 %s subject
1167 %m message-id.
1169 You may use normal field width specification between the % and the letter.
1170 This is for example useful to limit the length of the subject.
1172 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1173 :group 'org-link-store
1174 :type 'string)
1176 (defcustom org-from-is-user-regexp
1177 (let (r1 r2)
1178 (when (and user-mail-address (not (string= user-mail-address "")))
1179 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1180 (when (and user-full-name (not (string= user-full-name "")))
1181 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1182 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1183 "Regexp matched against the \"From:\" header of an email or usenet message.
1184 It should match if the message is from the user him/herself."
1185 :group 'org-link-store
1186 :type 'regexp)
1188 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1189 "Non-nil means storing a link to an Org file will use entry IDs.
1191 Note that before this variable is even considered, org-id must be loaded,
1192 so please customize `org-modules' and turn it on.
1194 The variable can have the following values:
1196 t Create an ID if needed to make a link to the current entry.
1198 create-if-interactive
1199 If `org-store-link' is called directly (interactively, as a user
1200 command), do create an ID to support the link. But when doing the
1201 job for remember, only use the ID if it already exists. The
1202 purpose of this setting is to avoid proliferation of unwanted
1203 IDs, just because you happen to be in an Org file when you
1204 call `org-remember' that automatically and preemptively
1205 creates a link. If you do want to get an ID link in a remember
1206 template to an entry not having an ID, create it first by
1207 explicitly creating a link to it, using `C-c C-l' first.
1209 create-if-interactive-and-no-custom-id
1210 Like create-if-interactive, but do not create an ID if there is
1211 a CUSTOM_ID property defined in the entry. This is the default.
1213 use-existing
1214 Use existing ID, do not create one.
1216 nil Never use an ID to make a link, instead link using a text search for
1217 the headline text."
1218 :group 'org-link-store
1219 :type '(choice
1220 (const :tag "Create ID to make link" t)
1221 (const :tag "Create if storing link interactively"
1222 create-if-interactive)
1223 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1224 create-if-interactive-and-no-custom-id)
1225 (const :tag "Only use existing" use-existing)
1226 (const :tag "Do not use ID to create link" nil)))
1228 (defcustom org-context-in-file-links t
1229 "Non-nil means file links from `org-store-link' contain context.
1230 A search string will be added to the file name with :: as separator and
1231 used to find the context when the link is activated by the command
1232 `org-open-at-point'.
1233 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1234 negates this setting for the duration of the command."
1235 :group 'org-link-store
1236 :type 'boolean)
1238 (defcustom org-keep-stored-link-after-insertion nil
1239 "Non-nil means keep link in list for entire session.
1241 The command `org-store-link' adds a link pointing to the current
1242 location to an internal list. These links accumulate during a session.
1243 The command `org-insert-link' can be used to insert links into any
1244 Org-mode file (offering completion for all stored links). When this
1245 option is nil, every link which has been inserted once using \\[org-insert-link]
1246 will be removed from the list, to make completing the unused links
1247 more efficient."
1248 :group 'org-link-store
1249 :type 'boolean)
1251 (defgroup org-link-follow nil
1252 "Options concerning following links in Org-mode."
1253 :tag "Org Follow Link"
1254 :group 'org-link)
1256 (defcustom org-link-translation-function nil
1257 "Function to translate links with different syntax to Org syntax.
1258 This can be used to translate links created for example by the Planner
1259 or emacs-wiki packages to Org syntax.
1260 The function must accept two parameters, a TYPE containing the link
1261 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1262 which is everything after the link protocol. It should return a cons
1263 with possibly modified values of type and path.
1264 Org contains a function for this, so if you set this variable to
1265 `org-translate-link-from-planner', you should be able follow many
1266 links created by planner."
1267 :group 'org-link-follow
1268 :type 'function)
1270 (defcustom org-follow-link-hook nil
1271 "Hook that is run after a link has been followed."
1272 :group 'org-link-follow
1273 :type 'hook)
1275 (defcustom org-tab-follows-link nil
1276 "Non-nil means on links TAB will follow the link.
1277 Needs to be set before org.el is loaded.
1278 This really should not be used, it does not make sense, and the
1279 implementation is bad."
1280 :group 'org-link-follow
1281 :type 'boolean)
1283 (defcustom org-return-follows-link nil
1284 "Non-nil means on links RET will follow the link.
1285 Needs to be set before org.el is loaded."
1286 :group 'org-link-follow
1287 :type 'boolean)
1289 (defcustom org-mouse-1-follows-link
1290 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1291 "Non-nil means mouse-1 on a link will follow the link.
1292 A longer mouse click will still set point. Does not work on XEmacs.
1293 Needs to be set before org.el is loaded."
1294 :group 'org-link-follow
1295 :type 'boolean)
1297 (defcustom org-mark-ring-length 4
1298 "Number of different positions to be recorded in the ring
1299 Changing this requires a restart of Emacs to work correctly."
1300 :group 'org-link-follow
1301 :type 'integer)
1303 (defcustom org-link-frame-setup
1304 '((vm . vm-visit-folder-other-frame)
1305 (gnus . gnus-other-frame)
1306 (file . find-file-other-window))
1307 "Setup the frame configuration for following links.
1308 When following a link with Emacs, it may often be useful to display
1309 this link in another window or frame. This variable can be used to
1310 set this up for the different types of links.
1311 For VM, use any of
1312 `vm-visit-folder'
1313 `vm-visit-folder-other-frame'
1314 For Gnus, use any of
1315 `gnus'
1316 `gnus-other-frame'
1317 `org-gnus-no-new-news'
1318 For FILE, use any of
1319 `find-file'
1320 `find-file-other-window'
1321 `find-file-other-frame'
1322 For the calendar, use the variable `calendar-setup'.
1323 For BBDB, it is currently only possible to display the matches in
1324 another window."
1325 :group 'org-link-follow
1326 :type '(list
1327 (cons (const vm)
1328 (choice
1329 (const vm-visit-folder)
1330 (const vm-visit-folder-other-window)
1331 (const vm-visit-folder-other-frame)))
1332 (cons (const gnus)
1333 (choice
1334 (const gnus)
1335 (const gnus-other-frame)
1336 (const org-gnus-no-new-news)))
1337 (cons (const file)
1338 (choice
1339 (const find-file)
1340 (const find-file-other-window)
1341 (const find-file-other-frame)))))
1343 (defcustom org-display-internal-link-with-indirect-buffer nil
1344 "Non-nil means use indirect buffer to display infile links.
1345 Activating internal links (from one location in a file to another location
1346 in the same file) normally just jumps to the location. When the link is
1347 activated with a C-u prefix (or with mouse-3), the link is displayed in
1348 another window. When this option is set, the other window actually displays
1349 an indirect buffer clone of the current buffer, to avoid any visibility
1350 changes to the current buffer."
1351 :group 'org-link-follow
1352 :type 'boolean)
1354 (defcustom org-open-non-existing-files nil
1355 "Non-nil means `org-open-file' will open non-existing files.
1356 When nil, an error will be generated.
1357 This variable applies only to external applications because they
1358 might choke on non-existing files. If the link is to a file that
1359 will be opened in Emacs, the variable is ignored."
1360 :group 'org-link-follow
1361 :type 'boolean)
1363 (defcustom org-open-directory-means-index-dot-org nil
1364 "Non-nil means a link to a directory really means to index.org.
1365 When nil, following a directory link will run dired or open a finder/explorer
1366 window on that directory."
1367 :group 'org-link-follow
1368 :type 'boolean)
1370 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1371 "Function and arguments to call for following mailto links.
1372 This is a list with the first element being a lisp function, and the
1373 remaining elements being arguments to the function. In string arguments,
1374 %a will be replaced by the address, and %s will be replaced by the subject
1375 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1376 :group 'org-link-follow
1377 :type '(choice
1378 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1379 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1380 (const :tag "message-mail" (message-mail "%a" "%s"))
1381 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1383 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1384 "Non-nil means ask for confirmation before executing shell links.
1385 Shell links can be dangerous: just think about a link
1387 [[shell:rm -rf ~/*][Google Search]]
1389 This link would show up in your Org-mode document as \"Google Search\",
1390 but really it would remove your entire home directory.
1391 Therefore we advise against setting this variable to nil.
1392 Just change it to `y-or-n-p' if you want to confirm with a
1393 single keystroke rather than having to type \"yes\"."
1394 :group 'org-link-follow
1395 :type '(choice
1396 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1397 (const :tag "with y-or-n (faster)" y-or-n-p)
1398 (const :tag "no confirmation (dangerous)" nil)))
1400 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1401 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1402 Elisp links can be dangerous: just think about a link
1404 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1406 This link would show up in your Org-mode document as \"Google Search\",
1407 but really it would remove your entire home directory.
1408 Therefore we advise against setting this variable to nil.
1409 Just change it to `y-or-n-p' if you want to confirm with a
1410 single keystroke rather than having to type \"yes\"."
1411 :group 'org-link-follow
1412 :type '(choice
1413 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1414 (const :tag "with y-or-n (faster)" y-or-n-p)
1415 (const :tag "no confirmation (dangerous)" nil)))
1417 (defconst org-file-apps-defaults-gnu
1418 '((remote . emacs)
1419 (system . mailcap)
1420 (t . mailcap))
1421 "Default file applications on a UNIX or GNU/Linux system.
1422 See `org-file-apps'.")
1424 (defconst org-file-apps-defaults-macosx
1425 '((remote . emacs)
1426 (t . "open %s")
1427 (system . "open %s")
1428 ("ps.gz" . "gv %s")
1429 ("eps.gz" . "gv %s")
1430 ("dvi" . "xdvi %s")
1431 ("fig" . "xfig %s"))
1432 "Default file applications on a MacOS X system.
1433 The system \"open\" is known as a default, but we use X11 applications
1434 for some files for which the OS does not have a good default.
1435 See `org-file-apps'.")
1437 (defconst org-file-apps-defaults-windowsnt
1438 (list
1439 '(remote . emacs)
1440 (cons t
1441 (list (if (featurep 'xemacs)
1442 'mswindows-shell-execute
1443 'w32-shell-execute)
1444 "open" 'file))
1445 (cons 'system
1446 (list (if (featurep 'xemacs)
1447 'mswindows-shell-execute
1448 'w32-shell-execute)
1449 "open" 'file)))
1450 "Default file applications on a Windows NT system.
1451 The system \"open\" is used for most files.
1452 See `org-file-apps'.")
1454 (defcustom org-file-apps
1456 (auto-mode . emacs)
1457 ("\\.mm\\'" . default)
1458 ("\\.x?html?\\'" . default)
1459 ("\\.pdf\\'" . default)
1461 "External applications for opening `file:path' items in a document.
1462 Org-mode uses system defaults for different file types, but
1463 you can use this variable to set the application for a given file
1464 extension. The entries in this list are cons cells where the car identifies
1465 files and the cdr the corresponding command. Possible values for the
1466 file identifier are
1467 \"regex\" Regular expression matched against the file name. For backward
1468 compatibility, this can also be a string with only alphanumeric
1469 characters, which is then interpreted as an extension.
1470 `directory' Matches a directory
1471 `remote' Matches a remote file, accessible through tramp or efs.
1472 Remote files most likely should be visited through Emacs
1473 because external applications cannot handle such paths.
1474 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1475 so all files Emacs knows how to handle. Using this with
1476 command `emacs' will open most files in Emacs. Beware that this
1477 will also open html files inside Emacs, unless you add
1478 (\"html\" . default) to the list as well.
1479 t Default for files not matched by any of the other options.
1480 `system' The system command to open files, like `open' on Windows
1481 and Mac OS X, and mailcap under GNU/Linux. This is the command
1482 that will be selected if you call `C-c C-o' with a double
1483 `C-u C-u' prefix.
1485 Possible values for the command are:
1486 `emacs' The file will be visited by the current Emacs process.
1487 `default' Use the default application for this file type, which is the
1488 association for t in the list, most likely in the system-specific
1489 part.
1490 This can be used to overrule an unwanted setting in the
1491 system-specific variable.
1492 `system' Use the system command for opening files, like \"open\".
1493 This command is specified by the entry whose car is `system'.
1494 Most likely, the system-specific version of this variable
1495 does define this command, but you can overrule/replace it
1496 here.
1497 string A command to be executed by a shell; %s will be replaced
1498 by the path to the file.
1499 sexp A Lisp form which will be evaluated. The file path will
1500 be available in the Lisp variable `file'.
1501 For more examples, see the system specific constants
1502 `org-file-apps-defaults-macosx'
1503 `org-file-apps-defaults-windowsnt'
1504 `org-file-apps-defaults-gnu'."
1505 :group 'org-link-follow
1506 :type '(repeat
1507 (cons (choice :value ""
1508 (string :tag "Extension")
1509 (const :tag "System command to open files" system)
1510 (const :tag "Default for unrecognized files" t)
1511 (const :tag "Remote file" remote)
1512 (const :tag "Links to a directory" directory)
1513 (const :tag "Any files that have Emacs modes"
1514 auto-mode))
1515 (choice :value ""
1516 (const :tag "Visit with Emacs" emacs)
1517 (const :tag "Use default" default)
1518 (const :tag "Use the system command" system)
1519 (string :tag "Command")
1520 (sexp :tag "Lisp form")))))
1522 (defgroup org-refile nil
1523 "Options concerning refiling entries in Org-mode."
1524 :tag "Org Refile"
1525 :group 'org)
1527 (defcustom org-directory "~/org"
1528 "Directory with org files.
1529 This is just a default location to look for Org files. There is no need
1530 at all to put your files into this directory. It is only used in the
1531 following situations:
1533 1. When a remember template specifies a target file that is not an
1534 absolute path. The path will then be interpreted relative to
1535 `org-directory'
1536 2. When a remember note is filed away in an interactive way (when exiting the
1537 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1538 with `org-directory' as the default path."
1539 :group 'org-refile
1540 :group 'org-remember
1541 :type 'directory)
1543 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1544 "Default target for storing notes.
1545 Used by the hooks for remember.el. This can be a string, or nil to mean
1546 the value of `remember-data-file'.
1547 You can set this on a per-template basis with the variable
1548 `org-remember-templates'."
1549 :group 'org-refile
1550 :group 'org-remember
1551 :type '(choice
1552 (const :tag "Default from remember-data-file" nil)
1553 file))
1555 (defcustom org-goto-interface 'outline
1556 "The default interface to be used for `org-goto'.
1557 Allowed values are:
1558 outline The interface shows an outline of the relevant file
1559 and the correct heading is found by moving through
1560 the outline or by searching with incremental search.
1561 outline-path-completion Headlines in the current buffer are offered via
1562 completion. This is the interface also used by
1563 the refile command."
1564 :group 'org-refile
1565 :type '(choice
1566 (const :tag "Outline" outline)
1567 (const :tag "Outline-path-completion" outline-path-completion)))
1569 (defcustom org-goto-max-level 5
1570 "Maximum level to be considered when running org-goto with refile interface."
1571 :group 'org-refile
1572 :type 'integer)
1574 (defcustom org-reverse-note-order nil
1575 "Non-nil means store new notes at the beginning of a file or entry.
1576 When nil, new notes will be filed to the end of a file or entry.
1577 This can also be a list with cons cells of regular expressions that
1578 are matched against file names, and values."
1579 :group 'org-remember
1580 :group 'org-refile
1581 :type '(choice
1582 (const :tag "Reverse always" t)
1583 (const :tag "Reverse never" nil)
1584 (repeat :tag "By file name regexp"
1585 (cons regexp boolean))))
1587 (defcustom org-refile-targets nil
1588 "Targets for refiling entries with \\[org-refile].
1589 This is list of cons cells. Each cell contains:
1590 - a specification of the files to be considered, either a list of files,
1591 or a symbol whose function or variable value will be used to retrieve
1592 a file name or a list of file names. If you use `org-agenda-files' for
1593 that, all agenda files will be scanned for targets. Nil means consider
1594 headings in the current buffer.
1595 - A specification of how to find candidate refile targets. This may be
1596 any of:
1597 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1598 This tag has to be present in all target headlines, inheritance will
1599 not be considered.
1600 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1601 todo keyword.
1602 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1603 headlines that are refiling targets.
1604 - a cons cell (:level . N). Any headline of level N is considered a target.
1605 Note that, when `org-odd-levels-only' is set, level corresponds to
1606 order in hierarchy, not to the number of stars.
1607 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1608 Note that, when `org-odd-levels-only' is set, level corresponds to
1609 order in hierarchy, not to the number of stars.
1611 You can set the variable `org-refile-target-verify-function' to a function
1612 to verify each headline found by the simple critery above.
1614 When this variable is nil, all top-level headlines in the current buffer
1615 are used, equivalent to the value `((nil . (:level . 1))'."
1616 :group 'org-refile
1617 :type '(repeat
1618 (cons
1619 (choice :value org-agenda-files
1620 (const :tag "All agenda files" org-agenda-files)
1621 (const :tag "Current buffer" nil)
1622 (function) (variable) (file))
1623 (choice :tag "Identify target headline by"
1624 (cons :tag "Specific tag" (const :value :tag) (string))
1625 (cons :tag "TODO keyword" (const :value :todo) (string))
1626 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1627 (cons :tag "Level number" (const :value :level) (integer))
1628 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1630 (defcustom org-refile-target-verify-function nil
1631 "Function to verify if the headline at point should be a refile target.
1632 The function will be called without arguments, with point at the
1633 beginning of the headline. It should return t and leave point
1634 where it is if the headline is a valid target for refiling.
1636 If the target should not be selected, the function must return nil.
1637 In addition to this, it may move point to a place from where the search
1638 should be continued. For example, the function may decide that the entire
1639 subtree of the current entry should be excluded and move point to the end
1640 of the subtree."
1641 :group 'org-refile
1642 :type 'function)
1644 (defcustom org-refile-use-outline-path nil
1645 "Non-nil means provide refile targets as paths.
1646 So a level 3 headline will be available as level1/level2/level3.
1648 When the value is `file', also include the file name (without directory)
1649 into the path. In this case, you can also stop the completion after
1650 the file name, to get entries inserted as top level in the file.
1652 When `full-file-path', include the full file path."
1653 :group 'org-refile
1654 :type '(choice
1655 (const :tag "Not" nil)
1656 (const :tag "Yes" t)
1657 (const :tag "Start with file name" file)
1658 (const :tag "Start with full file path" full-file-path)))
1660 (defcustom org-outline-path-complete-in-steps t
1661 "Non-nil means complete the outline path in hierarchical steps.
1662 When Org-mode uses the refile interface to select an outline path
1663 \(see variable `org-refile-use-outline-path'), the completion of
1664 the path can be done is a single go, or if can be done in steps down
1665 the headline hierarchy. Going in steps is probably the best if you
1666 do not use a special completion package like `ido' or `icicles'.
1667 However, when using these packages, going in one step can be very
1668 fast, while still showing the whole path to the entry."
1669 :group 'org-refile
1670 :type 'boolean)
1672 (defcustom org-refile-allow-creating-parent-nodes nil
1673 "Non-nil means allow to create new nodes as refile targets.
1674 New nodes are then created by adding \"/new node name\" to the completion
1675 of an existing node. When the value of this variable is `confirm',
1676 new node creation must be confirmed by the user (recommended)
1677 When nil, the completion must match an existing entry.
1679 Note that, if the new heading is not seen by the criteria
1680 listed in `org-refile-targets', multiple instances of the same
1681 heading would be created by trying again to file under the new
1682 heading."
1683 :group 'org-refile
1684 :type '(choice
1685 (const :tag "Never" nil)
1686 (const :tag "Always" t)
1687 (const :tag "Prompt for confirmation" confirm)))
1689 (defgroup org-todo nil
1690 "Options concerning TODO items in Org-mode."
1691 :tag "Org TODO"
1692 :group 'org)
1694 (defgroup org-progress nil
1695 "Options concerning Progress logging in Org-mode."
1696 :tag "Org Progress"
1697 :group 'org-time)
1699 (defvar org-todo-interpretation-widgets
1701 (:tag "Sequence (cycling hits every state)" sequence)
1702 (:tag "Type (cycling directly to DONE)" type))
1703 "The available interpretation symbols for customizing
1704 `org-todo-keywords'.
1705 Interested libraries should add to this list.")
1707 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1708 "List of TODO entry keyword sequences and their interpretation.
1709 \\<org-mode-map>This is a list of sequences.
1711 Each sequence starts with a symbol, either `sequence' or `type',
1712 indicating if the keywords should be interpreted as a sequence of
1713 action steps, or as different types of TODO items. The first
1714 keywords are states requiring action - these states will select a headline
1715 for inclusion into the global TODO list Org-mode produces. If one of
1716 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1717 signify that no further action is necessary. If \"|\" is not found,
1718 the last keyword is treated as the only DONE state of the sequence.
1720 The command \\[org-todo] cycles an entry through these states, and one
1721 additional state where no keyword is present. For details about this
1722 cycling, see the manual.
1724 TODO keywords and interpretation can also be set on a per-file basis with
1725 the special #+SEQ_TODO and #+TYP_TODO lines.
1727 Each keyword can optionally specify a character for fast state selection
1728 \(in combination with the variable `org-use-fast-todo-selection')
1729 and specifiers for state change logging, using the same syntax
1730 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1731 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1732 indicates to record a time stamp each time this state is selected.
1734 Each keyword may also specify if a timestamp or a note should be
1735 recorded when entering or leaving the state, by adding additional
1736 characters in the parenthesis after the keyword. This looks like this:
1737 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1738 record only the time of the state change. With X and Y being either
1739 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1740 Y when leaving the state if and only if the *target* state does not
1741 define X. You may omit any of the fast-selection key or X or /Y,
1742 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1744 For backward compatibility, this variable may also be just a list
1745 of keywords - in this case the interpretation (sequence or type) will be
1746 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1747 :group 'org-todo
1748 :group 'org-keywords
1749 :type '(choice
1750 (repeat :tag "Old syntax, just keywords"
1751 (string :tag "Keyword"))
1752 (repeat :tag "New syntax"
1753 (cons
1754 (choice
1755 :tag "Interpretation"
1756 ;;Quick and dirty way to see
1757 ;;`org-todo-interpretations'. This takes the
1758 ;;place of item arguments
1759 :convert-widget
1760 (lambda (widget)
1761 (widget-put widget
1762 :args (mapcar
1763 #'(lambda (x)
1764 (widget-convert
1765 (cons 'const x)))
1766 org-todo-interpretation-widgets))
1767 widget))
1768 (repeat
1769 (string :tag "Keyword"))))))
1771 (defvar org-todo-keywords-1 nil
1772 "All TODO and DONE keywords active in a buffer.")
1773 (make-variable-buffer-local 'org-todo-keywords-1)
1774 (defvar org-todo-keywords-for-agenda nil)
1775 (defvar org-done-keywords-for-agenda nil)
1776 (defvar org-drawers-for-agenda nil)
1777 (defvar org-todo-keyword-alist-for-agenda nil)
1778 (defvar org-tag-alist-for-agenda nil)
1779 (defvar org-agenda-contributing-files nil)
1780 (defvar org-not-done-keywords nil)
1781 (make-variable-buffer-local 'org-not-done-keywords)
1782 (defvar org-done-keywords nil)
1783 (make-variable-buffer-local 'org-done-keywords)
1784 (defvar org-todo-heads nil)
1785 (make-variable-buffer-local 'org-todo-heads)
1786 (defvar org-todo-sets nil)
1787 (make-variable-buffer-local 'org-todo-sets)
1788 (defvar org-todo-log-states nil)
1789 (make-variable-buffer-local 'org-todo-log-states)
1790 (defvar org-todo-kwd-alist nil)
1791 (make-variable-buffer-local 'org-todo-kwd-alist)
1792 (defvar org-todo-key-alist nil)
1793 (make-variable-buffer-local 'org-todo-key-alist)
1794 (defvar org-todo-key-trigger nil)
1795 (make-variable-buffer-local 'org-todo-key-trigger)
1797 (defcustom org-todo-interpretation 'sequence
1798 "Controls how TODO keywords are interpreted.
1799 This variable is in principle obsolete and is only used for
1800 backward compatibility, if the interpretation of todo keywords is
1801 not given already in `org-todo-keywords'. See that variable for
1802 more information."
1803 :group 'org-todo
1804 :group 'org-keywords
1805 :type '(choice (const sequence)
1806 (const type)))
1808 (defcustom org-use-fast-todo-selection t
1809 "Non-nil means use the fast todo selection scheme with C-c C-t.
1810 This variable describes if and under what circumstances the cycling
1811 mechanism for TODO keywords will be replaced by a single-key, direct
1812 selection scheme.
1814 When nil, fast selection is never used.
1816 When the symbol `prefix', it will be used when `org-todo' is called with
1817 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1818 in an agenda buffer.
1820 When t, fast selection is used by default. In this case, the prefix
1821 argument forces cycling instead.
1823 In all cases, the special interface is only used if access keys have actually
1824 been assigned by the user, i.e. if keywords in the configuration are followed
1825 by a letter in parenthesis, like TODO(t)."
1826 :group 'org-todo
1827 :type '(choice
1828 (const :tag "Never" nil)
1829 (const :tag "By default" t)
1830 (const :tag "Only with C-u C-c C-t" prefix)))
1832 (defcustom org-provide-todo-statistics t
1833 "Non-nil means update todo statistics after insert and toggle.
1834 ALL-HEADLINES means update todo statistics by including headlines
1835 with no TODO keyword as well, counting them as not done.
1836 A list of TODO keywords means the same, but skip keywords that are
1837 not in this list.
1839 When this is set, todo statistics is updated in the parent of the
1840 current entry each time a todo state is changed."
1841 :group 'org-todo
1842 :type '(choice
1843 (const :tag "Yes, only for TODO entries" t)
1844 (const :tag "Yes, including all entries" 'all-headlines)
1845 (repeat :tag "Yes, for TODOs in this list"
1846 (string :tag "TODO keyword"))
1847 (other :tag "No TODO statistics" nil)))
1849 (defcustom org-hierarchical-todo-statistics t
1850 "Non-nil means TODO statistics covers just direct children.
1851 When nil, all entries in the subtree are considered.
1852 This has only an effect if `org-provide-todo-statistics' is set.
1853 To set this to nil for only a single subtree, use a COOKIE_DATA
1854 property and include the word \"recursive\" into the value."
1855 :group 'org-todo
1856 :type 'boolean)
1858 (defcustom org-after-todo-state-change-hook nil
1859 "Hook which is run after the state of a TODO item was changed.
1860 The new state (a string with a TODO keyword, or nil) is available in the
1861 Lisp variable `state'."
1862 :group 'org-todo
1863 :type 'hook)
1865 (defvar org-blocker-hook nil
1866 "Hook for functions that are allowed to block a state change.
1868 Each function gets as its single argument a property list, see
1869 `org-trigger-hook' for more information about this list.
1871 If any of the functions in this hook returns nil, the state change
1872 is blocked.")
1874 (defvar org-trigger-hook nil
1875 "Hook for functions that are triggered by a state change.
1877 Each function gets as its single argument a property list with at least
1878 the following elements:
1880 (:type type-of-change :position pos-at-entry-start
1881 :from old-state :to new-state)
1883 Depending on the type, more properties may be present.
1885 This mechanism is currently implemented for:
1887 TODO state changes
1888 ------------------
1889 :type todo-state-change
1890 :from previous state (keyword as a string), or nil, or a symbol
1891 'todo' or 'done', to indicate the general type of state.
1892 :to new state, like in :from")
1894 (defcustom org-enforce-todo-dependencies nil
1895 "Non-nil means undone TODO entries will block switching the parent to DONE.
1896 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1897 be blocked if any prior sibling is not yet done.
1898 Finally, if the parent is blocked because of ordered siblings of its own,
1899 the child will also be blocked.
1900 This variable needs to be set before org.el is loaded, and you need to
1901 restart Emacs after a change to make the change effective. The only way
1902 to change is while Emacs is running is through the customize interface."
1903 :set (lambda (var val)
1904 (set var val)
1905 (if val
1906 (add-hook 'org-blocker-hook
1907 'org-block-todo-from-children-or-siblings-or-parent)
1908 (remove-hook 'org-blocker-hook
1909 'org-block-todo-from-children-or-siblings-or-parent)))
1910 :group 'org-todo
1911 :type 'boolean)
1913 (defcustom org-enforce-todo-checkbox-dependencies nil
1914 "Non-nil means unchecked boxes will block switching the parent to DONE.
1915 When this is nil, checkboxes have no influence on switching TODO states.
1916 When non-nil, you first need to check off all check boxes before the TODO
1917 entry can be switched to DONE.
1918 This variable needs to be set before org.el is loaded, and you need to
1919 restart Emacs after a change to make the change effective. The only way
1920 to change is while Emacs is running is through the customize interface."
1921 :set (lambda (var val)
1922 (set var val)
1923 (if val
1924 (add-hook 'org-blocker-hook
1925 'org-block-todo-from-checkboxes)
1926 (remove-hook 'org-blocker-hook
1927 'org-block-todo-from-checkboxes)))
1928 :group 'org-todo
1929 :type 'boolean)
1931 (defcustom org-treat-insert-todo-heading-as-state-change nil
1932 "Non-nil means inserting a TODO heading is treated as state change.
1933 So when the command \\[org-insert-todo-heading] is used, state change
1934 logging will apply if appropriate. When nil, the new TODO item will
1935 be inserted directly, and no logging will take place."
1936 :group 'org-todo
1937 :type 'boolean)
1939 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1940 "Non-nil means switching TODO states with S-cursor counts as state change.
1941 This is the default behavior. However, setting this to nil allows a
1942 convenient way to select a TODO state and bypass any logging associated
1943 with that."
1944 :group 'org-todo
1945 :type 'boolean)
1947 (defcustom org-todo-state-tags-triggers nil
1948 "Tag changes that should be triggered by TODO state changes.
1949 This is a list. Each entry is
1951 (state-change (tag . flag) .......)
1953 State-change can be a string with a state, and empty string to indicate the
1954 state that has no TODO keyword, or it can be one of the symbols `todo'
1955 or `done', meaning any not-done or done state, respectively."
1956 :group 'org-todo
1957 :group 'org-tags
1958 :type '(repeat
1959 (cons (choice :tag "When changing to"
1960 (const :tag "Not-done state" todo)
1961 (const :tag "Done state" done)
1962 (string :tag "State"))
1963 (repeat
1964 (cons :tag "Tag action"
1965 (string :tag "Tag")
1966 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1968 (defcustom org-log-done nil
1969 "Information to record when a task moves to the DONE state.
1971 Possible values are:
1973 nil Don't add anything, just change the keyword
1974 time Add a time stamp to the task
1975 note Prompt for a note and add it with template `org-log-note-headings'
1977 This option can also be set with on a per-file-basis with
1979 #+STARTUP: nologdone
1980 #+STARTUP: logdone
1981 #+STARTUP: lognotedone
1983 You can have local logging settings for a subtree by setting the LOGGING
1984 property to one or more of these keywords."
1985 :group 'org-todo
1986 :group 'org-progress
1987 :type '(choice
1988 (const :tag "No logging" nil)
1989 (const :tag "Record CLOSED timestamp" time)
1990 (const :tag "Record CLOSED timestamp with note." note)))
1992 ;; Normalize old uses of org-log-done.
1993 (cond
1994 ((eq org-log-done t) (setq org-log-done 'time))
1995 ((and (listp org-log-done) (memq 'done org-log-done))
1996 (setq org-log-done 'note)))
1998 (defcustom org-log-reschedule nil
1999 "Information to record when the scheduling date of a tasks is modified.
2001 Possible values are:
2003 nil Don't add anything, just change the date
2004 time Add a time stamp to the task
2005 note Prompt for a note and add it with template `org-log-note-headings'
2007 This option can also be set with on a per-file-basis with
2009 #+STARTUP: nologreschedule
2010 #+STARTUP: logreschedule
2011 #+STARTUP: lognotereschedule"
2012 :group 'org-todo
2013 :group 'org-progress
2014 :type '(choice
2015 (const :tag "No logging" nil)
2016 (const :tag "Record timestamp" time)
2017 (const :tag "Record timestamp with note." note)))
2019 (defcustom org-log-redeadline nil
2020 "Information to record when the deadline date of a tasks is modified.
2022 Possible values are:
2024 nil Don't add anything, just change the date
2025 time Add a time stamp to the task
2026 note Prompt for a note and add it with template `org-log-note-headings'
2028 This option can also be set with on a per-file-basis with
2030 #+STARTUP: nologredeadline
2031 #+STARTUP: logredeadline
2032 #+STARTUP: lognoteredeadline
2034 You can have local logging settings for a subtree by setting the LOGGING
2035 property to one or more of these keywords."
2036 :group 'org-todo
2037 :group 'org-progress
2038 :type '(choice
2039 (const :tag "No logging" nil)
2040 (const :tag "Record timestamp" time)
2041 (const :tag "Record timestamp with note." note)))
2043 (defcustom org-log-note-clock-out nil
2044 "Non-nil means record a note when clocking out of an item.
2045 This can also be configured on a per-file basis by adding one of
2046 the following lines anywhere in the buffer:
2048 #+STARTUP: lognoteclock-out
2049 #+STARTUP: nolognoteclock-out"
2050 :group 'org-todo
2051 :group 'org-progress
2052 :type 'boolean)
2054 (defcustom org-log-done-with-time t
2055 "Non-nil means the CLOSED time stamp will contain date and time.
2056 When nil, only the date will be recorded."
2057 :group 'org-progress
2058 :type 'boolean)
2060 (defcustom org-log-note-headings
2061 '((done . "CLOSING NOTE %t")
2062 (state . "State %-12s from %-12S %t")
2063 (note . "Note taken on %t")
2064 (reschedule . "Rescheduled from %S on %t")
2065 (delschedule . "Not scheduled, was %S on %t")
2066 (redeadline . "New deadline from %S on %t")
2067 (deldeadline . "Removed deadline, was %S on %t")
2068 (clock-out . ""))
2069 "Headings for notes added to entries.
2070 The value is an alist, with the car being a symbol indicating the note
2071 context, and the cdr is the heading to be used. The heading may also be the
2072 empty string.
2073 %t in the heading will be replaced by a time stamp.
2074 %s will be replaced by the new TODO state, in double quotes.
2075 %S will be replaced by the old TODO state, in double quotes.
2076 %u will be replaced by the user name.
2077 %U will be replaced by the full user name.
2079 In fact, it is not a good idea to change the `state' entry, because
2080 agenda log mode depends on the format of these entries."
2081 :group 'org-todo
2082 :group 'org-progress
2083 :type '(list :greedy t
2084 (cons (const :tag "Heading when closing an item" done) string)
2085 (cons (const :tag
2086 "Heading when changing todo state (todo sequence only)"
2087 state) string)
2088 (cons (const :tag "Heading when just taking a note" note) string)
2089 (cons (const :tag "Heading when clocking out" clock-out) string)
2090 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2091 (cons (const :tag "Heading when rescheduling" reschedule) string)
2092 (cons (const :tag "Heading when changing deadline" redeadline) string
2093 (cons (const :tag "Heading when deleting a deadline" deldeadline) string))))
2095 (unless (assq 'note org-log-note-headings)
2096 (push '(note . "%t") org-log-note-headings))
2098 (defcustom org-log-into-drawer nil
2099 "Non-nil means insert state change notes and time stamps into a drawer.
2100 When nil, state changes notes will be inserted after the headline and
2101 any scheduling and clock lines, but not inside a drawer.
2103 The value of this variable should be the name of the drawer to use.
2104 LOGBOOK is proposed at the default drawer for this purpose, you can
2105 also set this to a string to define the drawer of your choice.
2107 A value of t is also allowed, representing \"LOGBOOK\".
2109 If this variable is set, `org-log-state-notes-insert-after-drawers'
2110 will be ignored.
2112 You can set the property LOG_INTO_DRAWER to overrule this setting for
2113 a subtree."
2114 :group 'org-todo
2115 :group 'org-progress
2116 :type '(choice
2117 (const :tag "Not into a drawer" nil)
2118 (const :tag "LOGBOOK" t)
2119 (string :tag "Other")))
2121 (if (fboundp 'defvaralias)
2122 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2124 (defun org-log-into-drawer ()
2125 "Return the value of `org-log-into-drawer', but let properties overrule.
2126 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2127 used instead of the default value."
2128 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2129 (cond
2130 ((or (not p) (equal p "nil")) org-log-into-drawer)
2131 ((equal p "t") "LOGBOOK")
2132 (t p))))
2134 (defcustom org-log-state-notes-insert-after-drawers nil
2135 "Non-nil means insert state change notes after any drawers in entry.
2136 Only the drawers that *immediately* follow the headline and the
2137 deadline/scheduled line are skipped.
2138 When nil, insert notes right after the heading and perhaps the line
2139 with deadline/scheduling if present.
2141 This variable will have no effect if `org-log-into-drawer' is
2142 set."
2143 :group 'org-todo
2144 :group 'org-progress
2145 :type 'boolean)
2147 (defcustom org-log-states-order-reversed t
2148 "Non-nil means the latest state change note will be directly after heading.
2149 When nil, the notes will be orderer according to time."
2150 :group 'org-todo
2151 :group 'org-progress
2152 :type 'boolean)
2154 (defcustom org-log-repeat 'time
2155 "Non-nil means record moving through the DONE state when triggering repeat.
2156 An auto-repeating task is immediately switched back to TODO when
2157 marked DONE. If you are not logging state changes (by adding \"@\"
2158 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2159 record a closing note, there will be no record of the task moving
2160 through DONE. This variable forces taking a note anyway.
2162 nil Don't force a record
2163 time Record a time stamp
2164 note Record a note
2166 This option can also be set with on a per-file-basis with
2168 #+STARTUP: logrepeat
2169 #+STARTUP: lognoterepeat
2170 #+STARTUP: nologrepeat
2172 You can have local logging settings for a subtree by setting the LOGGING
2173 property to one or more of these keywords."
2174 :group 'org-todo
2175 :group 'org-progress
2176 :type '(choice
2177 (const :tag "Don't force a record" nil)
2178 (const :tag "Force recording the DONE state" time)
2179 (const :tag "Force recording a note with the DONE state" note)))
2182 (defgroup org-priorities nil
2183 "Priorities in Org-mode."
2184 :tag "Org Priorities"
2185 :group 'org-todo)
2187 (defcustom org-enable-priority-commands t
2188 "Non-nil means priority commands are active.
2189 When nil, these commands will be disabled, so that you never accidentally
2190 set a priority."
2191 :group 'org-priorities
2192 :type 'boolean)
2194 (defcustom org-highest-priority ?A
2195 "The highest priority of TODO items. A character like ?A, ?B etc.
2196 Must have a smaller ASCII number than `org-lowest-priority'."
2197 :group 'org-priorities
2198 :type 'character)
2200 (defcustom org-lowest-priority ?C
2201 "The lowest priority of TODO items. A character like ?A, ?B etc.
2202 Must have a larger ASCII number than `org-highest-priority'."
2203 :group 'org-priorities
2204 :type 'character)
2206 (defcustom org-default-priority ?B
2207 "The default priority of TODO items.
2208 This is the priority an item get if no explicit priority is given."
2209 :group 'org-priorities
2210 :type 'character)
2212 (defcustom org-priority-start-cycle-with-default t
2213 "Non-nil means start with default priority when starting to cycle.
2214 When this is nil, the first step in the cycle will be (depending on the
2215 command used) one higher or lower that the default priority."
2216 :group 'org-priorities
2217 :type 'boolean)
2219 (defgroup org-time nil
2220 "Options concerning time stamps and deadlines in Org-mode."
2221 :tag "Org Time"
2222 :group 'org)
2224 (defcustom org-insert-labeled-timestamps-at-point nil
2225 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2226 When nil, these labeled time stamps are forces into the second line of an
2227 entry, just after the headline. When scheduling from the global TODO list,
2228 the time stamp will always be forced into the second line."
2229 :group 'org-time
2230 :type 'boolean)
2232 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2233 "Formats for `format-time-string' which are used for time stamps.
2234 It is not recommended to change this constant.")
2236 (defcustom org-time-stamp-rounding-minutes '(0 5)
2237 "Number of minutes to round time stamps to.
2238 These are two values, the first applies when first creating a time stamp.
2239 The second applies when changing it with the commands `S-up' and `S-down'.
2240 When changing the time stamp, this means that it will change in steps
2241 of N minutes, as given by the second value.
2243 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2244 numbers should be factors of 60, so for example 5, 10, 15.
2246 When this is larger than 1, you can still force an exact time-stamp by using
2247 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2248 and by using a prefix arg to `S-up/down' to specify the exact number
2249 of minutes to shift."
2250 :group 'org-time
2251 :get '(lambda (var) ; Make sure all entries have 5 elements
2252 (if (integerp (default-value var))
2253 (list (default-value var) 5)
2254 (default-value var)))
2255 :type '(list
2256 (integer :tag "when inserting times")
2257 (integer :tag "when modifying times")))
2259 ;; Normalize old customizations of this variable.
2260 (when (integerp org-time-stamp-rounding-minutes)
2261 (setq org-time-stamp-rounding-minutes
2262 (list org-time-stamp-rounding-minutes
2263 org-time-stamp-rounding-minutes)))
2265 (defcustom org-display-custom-times nil
2266 "Non-nil means overlay custom formats over all time stamps.
2267 The formats are defined through the variable `org-time-stamp-custom-formats'.
2268 To turn this on on a per-file basis, insert anywhere in the file:
2269 #+STARTUP: customtime"
2270 :group 'org-time
2271 :set 'set-default
2272 :type 'sexp)
2273 (make-variable-buffer-local 'org-display-custom-times)
2275 (defcustom org-time-stamp-custom-formats
2276 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2277 "Custom formats for time stamps. See `format-time-string' for the syntax.
2278 These are overlayed over the default ISO format if the variable
2279 `org-display-custom-times' is set. Time like %H:%M should be at the
2280 end of the second format. The custom formats are also honored by export
2281 commands, if custom time display is turned on at the time of export."
2282 :group 'org-time
2283 :type 'sexp)
2285 (defun org-time-stamp-format (&optional long inactive)
2286 "Get the right format for a time string."
2287 (let ((f (if long (cdr org-time-stamp-formats)
2288 (car org-time-stamp-formats))))
2289 (if inactive
2290 (concat "[" (substring f 1 -1) "]")
2291 f)))
2293 (defcustom org-time-clocksum-format "%d:%02d"
2294 "The format string used when creating CLOCKSUM lines, or when
2295 org-mode generates a time duration."
2296 :group 'org-time
2297 :type 'string)
2299 (defcustom org-time-clocksum-use-fractional nil
2300 "If non-nil, \\[org-clock-display] uses fractional times.
2301 org-mode generates a time duration."
2302 :group 'org-time
2303 :type 'boolean)
2305 (defcustom org-time-clocksum-fractional-format "%.2f"
2306 "The format string used when creating CLOCKSUM lines, or when
2307 org-mode generates a time duration."
2308 :group 'org-time
2309 :type 'string)
2311 (defcustom org-deadline-warning-days 14
2312 "No. of days before expiration during which a deadline becomes active.
2313 This variable governs the display in sparse trees and in the agenda.
2314 When 0 or negative, it means use this number (the absolute value of it)
2315 even if a deadline has a different individual lead time specified.
2317 Custom commands can set this variable in the options section."
2318 :group 'org-time
2319 :group 'org-agenda-daily/weekly
2320 :type 'integer)
2322 (defcustom org-read-date-prefer-future t
2323 "Non-nil means assume future for incomplete date input from user.
2324 This affects the following situations:
2325 1. The user gives a month but not a year.
2326 For example, if it is april and you enter \"feb 2\", this will be read
2327 as feb 2, *next* year. \"May 5\", however, will be this year.
2328 2. The user gives a day, but no month.
2329 For example, if today is the 15th, and you enter \"3\", Org-mode will
2330 read this as the third of *next* month. However, if you enter \"17\",
2331 it will be considered as *this* month.
2333 If you set this variable to the symbol `time', then also the following
2334 will work:
2336 3. If the user gives a time, but no day. If the time is before now,
2337 to will be interpreted as tomorrow.
2339 Currently none of this works for ISO week specifications.
2341 When this option is nil, the current day, month and year will always be
2342 used as defaults."
2343 :group 'org-time
2344 :type '(choice
2345 (const :tag "Never" nil)
2346 (const :tag "Check month and day" t)
2347 (const :tag "Check month, day, and time" time)))
2349 (defcustom org-read-date-display-live t
2350 "Non-nil means display current interpretation of date prompt live.
2351 This display will be in an overlay, in the minibuffer."
2352 :group 'org-time
2353 :type 'boolean)
2355 (defcustom org-read-date-popup-calendar t
2356 "Non-nil means pop up a calendar when prompting for a date.
2357 In the calendar, the date can be selected with mouse-1. However, the
2358 minibuffer will also be active, and you can simply enter the date as well.
2359 When nil, only the minibuffer will be available."
2360 :group 'org-time
2361 :type 'boolean)
2362 (if (fboundp 'defvaralias)
2363 (defvaralias 'org-popup-calendar-for-date-prompt
2364 'org-read-date-popup-calendar))
2366 (defcustom org-read-date-minibuffer-setup-hook nil
2367 "Hook to be used to set up keys for the date/time interface.
2368 Add key definitions to `minibuffer-local-map', which will be a temporary
2369 copy."
2370 :group 'org-time
2371 :type 'hook)
2373 (defcustom org-extend-today-until 0
2374 "The hour when your day really ends. Must be an integer.
2375 This has influence for the following applications:
2376 - When switching the agenda to \"today\". It it is still earlier than
2377 the time given here, the day recognized as TODAY is actually yesterday.
2378 - When a date is read from the user and it is still before the time given
2379 here, the current date and time will be assumed to be yesterday, 23:59.
2380 Also, timestamps inserted in remember templates follow this rule.
2382 IMPORTANT: This is a feature whose implementation is and likely will
2383 remain incomplete. Really, it is only here because past midnight seems to
2384 be the favorite working time of John Wiegley :-)"
2385 :group 'org-time
2386 :type 'integer)
2388 (defcustom org-edit-timestamp-down-means-later nil
2389 "Non-nil means S-down will increase the time in a time stamp.
2390 When nil, S-up will increase."
2391 :group 'org-time
2392 :type 'boolean)
2394 (defcustom org-calendar-follow-timestamp-change t
2395 "Non-nil means make the calendar window follow timestamp changes.
2396 When a timestamp is modified and the calendar window is visible, it will be
2397 moved to the new date."
2398 :group 'org-time
2399 :type 'boolean)
2401 (defgroup org-tags nil
2402 "Options concerning tags in Org-mode."
2403 :tag "Org Tags"
2404 :group 'org)
2406 (defcustom org-tag-alist nil
2407 "List of tags allowed in Org-mode files.
2408 When this list is nil, Org-mode will base TAG input on what is already in the
2409 buffer.
2410 The value of this variable is an alist, the car of each entry must be a
2411 keyword as a string, the cdr may be a character that is used to select
2412 that tag through the fast-tag-selection interface.
2413 See the manual for details."
2414 :group 'org-tags
2415 :type '(repeat
2416 (choice
2417 (cons (string :tag "Tag name")
2418 (character :tag "Access char"))
2419 (list :tag "Start radio group"
2420 (const :startgroup)
2421 (option (string :tag "Group description")))
2422 (list :tag "End radio group"
2423 (const :endgroup)
2424 (option (string :tag "Group description")))
2425 (const :tag "New line" (:newline)))))
2427 (defcustom org-tag-persistent-alist nil
2428 "List of tags that will always appear in all Org-mode files.
2429 This is in addition to any in buffer settings or customizations
2430 of `org-tag-alist'.
2431 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2432 The value of this variable is an alist, the car of each entry must be a
2433 keyword as a string, the cdr may be a character that is used to select
2434 that tag through the fast-tag-selection interface.
2435 See the manual for details.
2436 To disable these tags on a per-file basis, insert anywhere in the file:
2437 #+STARTUP: noptag"
2438 :group 'org-tags
2439 :type '(repeat
2440 (choice
2441 (cons (string :tag "Tag name")
2442 (character :tag "Access char"))
2443 (const :tag "Start radio group" (:startgroup))
2444 (const :tag "End radio group" (:endgroup))
2445 (const :tag "New line" (:newline)))))
2447 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2448 "If non-nil, always offer completion for all tags of all agenda files.
2449 Instead of customizing this variable directly, you might want to
2450 set it locally for remember buffers, because there no list of
2451 tags in that file can be created dynamically (there are none).
2453 (add-hook 'org-remember-mode-hook
2454 (lambda ()
2455 (set (make-local-variable
2456 'org-complete-tags-always-offer-all-agenda-tags)
2457 t)))"
2458 :group 'org-tags
2459 :type 'boolean)
2461 (defvar org-file-tags nil
2462 "List of tags that can be inherited by all entries in the file.
2463 The tags will be inherited if the variable `org-use-tag-inheritance'
2464 says they should be.
2465 This variable is populated from #+FILETAGS lines.")
2467 (defcustom org-use-fast-tag-selection 'auto
2468 "Non-nil means use fast tag selection scheme.
2469 This is a special interface to select and deselect tags with single keys.
2470 When nil, fast selection is never used.
2471 When the symbol `auto', fast selection is used if and only if selection
2472 characters for tags have been configured, either through the variable
2473 `org-tag-alist' or through a #+TAGS line in the buffer.
2474 When t, fast selection is always used and selection keys are assigned
2475 automatically if necessary."
2476 :group 'org-tags
2477 :type '(choice
2478 (const :tag "Always" t)
2479 (const :tag "Never" nil)
2480 (const :tag "When selection characters are configured" 'auto)))
2482 (defcustom org-fast-tag-selection-single-key nil
2483 "Non-nil means fast tag selection exits after first change.
2484 When nil, you have to press RET to exit it.
2485 During fast tag selection, you can toggle this flag with `C-c'.
2486 This variable can also have the value `expert'. In this case, the window
2487 displaying the tags menu is not even shown, until you press C-c again."
2488 :group 'org-tags
2489 :type '(choice
2490 (const :tag "No" nil)
2491 (const :tag "Yes" t)
2492 (const :tag "Expert" expert)))
2494 (defvar org-fast-tag-selection-include-todo nil
2495 "Non-nil means fast tags selection interface will also offer TODO states.
2496 This is an undocumented feature, you should not rely on it.")
2498 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2499 "The column to which tags should be indented in a headline.
2500 If this number is positive, it specifies the column. If it is negative,
2501 it means that the tags should be flushright to that column. For example,
2502 -80 works well for a normal 80 character screen."
2503 :group 'org-tags
2504 :type 'integer)
2506 (defcustom org-auto-align-tags t
2507 "Non-nil means realign tags after pro/demotion of TODO state change.
2508 These operations change the length of a headline and therefore shift
2509 the tags around. With this options turned on, after each such operation
2510 the tags are again aligned to `org-tags-column'."
2511 :group 'org-tags
2512 :type 'boolean)
2514 (defcustom org-use-tag-inheritance t
2515 "Non-nil means tags in levels apply also for sublevels.
2516 When nil, only the tags directly given in a specific line apply there.
2517 This may also be a list of tags that should be inherited, or a regexp that
2518 matches tags that should be inherited. Additional control is possible
2519 with the variable `org-tags-exclude-from-inheritance' which gives an
2520 explicit list of tags to be excluded from inheritance., even if the value of
2521 `org-use-tag-inheritance' would select it for inheritance.
2523 If this option is t, a match early-on in a tree can lead to a large
2524 number of matches in the subtree when constructing the agenda or creating
2525 a sparse tree. If you only want to see the first match in a tree during
2526 a search, check out the variable `org-tags-match-list-sublevels'."
2527 :group 'org-tags
2528 :type '(choice
2529 (const :tag "Not" nil)
2530 (const :tag "Always" t)
2531 (repeat :tag "Specific tags" (string :tag "Tag"))
2532 (regexp :tag "Tags matched by regexp")))
2534 (defcustom org-tags-exclude-from-inheritance nil
2535 "List of tags that should never be inherited.
2536 This is a way to exclude a few tags from inheritance. For way to do
2537 the opposite, to actively allow inheritance for selected tags,
2538 see the variable `org-use-tag-inheritance'."
2539 :group 'org-tags
2540 :type '(repeat (string :tag "Tag")))
2542 (defun org-tag-inherit-p (tag)
2543 "Check if TAG is one that should be inherited."
2544 (cond
2545 ((member tag org-tags-exclude-from-inheritance) nil)
2546 ((eq org-use-tag-inheritance t) t)
2547 ((not org-use-tag-inheritance) nil)
2548 ((stringp org-use-tag-inheritance)
2549 (string-match org-use-tag-inheritance tag))
2550 ((listp org-use-tag-inheritance)
2551 (member tag org-use-tag-inheritance))
2552 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2554 (defcustom org-tags-match-list-sublevels t
2555 "Non-nil means list also sublevels of headlines matching a search.
2556 This variable applies to tags/property searches, and also to stuck
2557 projects because this search is based on a tags match as well.
2559 When set to the symbol `indented', sublevels are indented with
2560 leading dots.
2562 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2563 the sublevels of a headline matching a tag search often also match
2564 the same search. Listing all of them can create very long lists.
2565 Setting this variable to nil causes subtrees of a match to be skipped.
2567 This variable is semi-obsolete and probably should always be true. It
2568 is better to limit inheritance to certain tags using the variables
2569 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2570 :group 'org-tags
2571 :type '(choice
2572 (const :tag "No, don't list them" nil)
2573 (const :tag "Yes, do list them" t)
2574 (const :tag "List them, indented with leading dots" indented)))
2576 (defcustom org-tags-sort-function nil
2577 "When set, tags are sorted using this function as a comparator"
2578 :group 'org-tags
2579 :type '(choice
2580 (const :tag "No sorting" nil)
2581 (const :tag "Alphabetical" string<)
2582 (const :tag "Reverse alphabetical" string>)
2583 (function :tag "Custom function" nil)))
2585 (defvar org-tags-history nil
2586 "History of minibuffer reads for tags.")
2587 (defvar org-last-tags-completion-table nil
2588 "The last used completion table for tags.")
2589 (defvar org-after-tags-change-hook nil
2590 "Hook that is run after the tags in a line have changed.")
2592 (defgroup org-properties nil
2593 "Options concerning properties in Org-mode."
2594 :tag "Org Properties"
2595 :group 'org)
2597 (defcustom org-property-format "%-10s %s"
2598 "How property key/value pairs should be formatted by `indent-line'.
2599 When `indent-line' hits a property definition, it will format the line
2600 according to this format, mainly to make sure that the values are
2601 lined-up with respect to each other."
2602 :group 'org-properties
2603 :type 'string)
2605 (defcustom org-use-property-inheritance nil
2606 "Non-nil means properties apply also for sublevels.
2608 This setting is chiefly used during property searches. Turning it on can
2609 cause significant overhead when doing a search, which is why it is not
2610 on by default.
2612 When nil, only the properties directly given in the current entry count.
2613 When t, every property is inherited. The value may also be a list of
2614 properties that should have inheritance, or a regular expression matching
2615 properties that should be inherited.
2617 However, note that some special properties use inheritance under special
2618 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2619 and the properties ending in \"_ALL\" when they are used as descriptor
2620 for valid values of a property.
2622 Note for programmers:
2623 When querying an entry with `org-entry-get', you can control if inheritance
2624 should be used. By default, `org-entry-get' looks only at the local
2625 properties. You can request inheritance by setting the inherit argument
2626 to t (to force inheritance) or to `selective' (to respect the setting
2627 in this variable)."
2628 :group 'org-properties
2629 :type '(choice
2630 (const :tag "Not" nil)
2631 (const :tag "Always" t)
2632 (repeat :tag "Specific properties" (string :tag "Property"))
2633 (regexp :tag "Properties matched by regexp")))
2635 (defun org-property-inherit-p (property)
2636 "Check if PROPERTY is one that should be inherited."
2637 (cond
2638 ((eq org-use-property-inheritance t) t)
2639 ((not org-use-property-inheritance) nil)
2640 ((stringp org-use-property-inheritance)
2641 (string-match org-use-property-inheritance property))
2642 ((listp org-use-property-inheritance)
2643 (member property org-use-property-inheritance))
2644 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2646 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2647 "The default column format, if no other format has been defined.
2648 This variable can be set on the per-file basis by inserting a line
2650 #+COLUMNS: %25ITEM ....."
2651 :group 'org-properties
2652 :type 'string)
2654 (defcustom org-columns-ellipses ".."
2655 "The ellipses to be used when a field in column view is truncated.
2656 When this is the empty string, as many characters as possible are shown,
2657 but then there will be no visual indication that the field has been truncated.
2658 When this is a string of length N, the last N characters of a truncated
2659 field are replaced by this string. If the column is narrower than the
2660 ellipses string, only part of the ellipses string will be shown."
2661 :group 'org-properties
2662 :type 'string)
2664 (defcustom org-columns-modify-value-for-display-function nil
2665 "Function that modifies values for display in column view.
2666 For example, it can be used to cut out a certain part from a time stamp.
2667 The function must take 2 arguments:
2669 column-title The title of the column (*not* the property name)
2670 value The value that should be modified.
2672 The function should return the value that should be displayed,
2673 or nil if the normal value should be used."
2674 :group 'org-properties
2675 :type 'function)
2677 (defcustom org-effort-property "Effort"
2678 "The property that is being used to keep track of effort estimates.
2679 Effort estimates given in this property need to have the format H:MM."
2680 :group 'org-properties
2681 :group 'org-progress
2682 :type '(string :tag "Property"))
2684 (defconst org-global-properties-fixed
2685 '(("VISIBILITY_ALL" . "folded children content all")
2686 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2687 "List of property/value pairs that can be inherited by any entry.
2689 These are fixed values, for the preset properties. The user variable
2690 that can be used to add to this list is `org-global-properties'.
2692 The entries in this list are cons cells where the car is a property
2693 name and cdr is a string with the value. If the value represents
2694 multiple items like an \"_ALL\" property, separate the items by
2695 spaces.")
2697 (defcustom org-global-properties nil
2698 "List of property/value pairs that can be inherited by any entry.
2700 This list will be combined with the constant `org-global-properties-fixed'.
2702 The entries in this list are cons cells where the car is a property
2703 name and cdr is a string with the value.
2705 You can set buffer-local values for the same purpose in the variable
2706 `org-file-properties' this by adding lines like
2708 #+PROPERTY: NAME VALUE"
2709 :group 'org-properties
2710 :type '(repeat
2711 (cons (string :tag "Property")
2712 (string :tag "Value"))))
2714 (defvar org-file-properties nil
2715 "List of property/value pairs that can be inherited by any entry.
2716 Valid for the current buffer.
2717 This variable is populated from #+PROPERTY lines.")
2718 (make-variable-buffer-local 'org-file-properties)
2720 (defgroup org-agenda nil
2721 "Options concerning agenda views in Org-mode."
2722 :tag "Org Agenda"
2723 :group 'org)
2725 (defvar org-category nil
2726 "Variable used by org files to set a category for agenda display.
2727 Such files should use a file variable to set it, for example
2729 # -*- mode: org; org-category: \"ELisp\"
2731 or contain a special line
2733 #+CATEGORY: ELisp
2735 If the file does not specify a category, then file's base name
2736 is used instead.")
2737 (make-variable-buffer-local 'org-category)
2738 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2740 (defcustom org-agenda-files nil
2741 "The files to be used for agenda display.
2742 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2743 \\[org-remove-file]. You can also use customize to edit the list.
2745 If an entry is a directory, all files in that directory that are matched by
2746 `org-agenda-file-regexp' will be part of the file list.
2748 If the value of the variable is not a list but a single file name, then
2749 the list of agenda files is actually stored and maintained in that file, one
2750 agenda file per line."
2751 :group 'org-agenda
2752 :type '(choice
2753 (repeat :tag "List of files and directories" file)
2754 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2756 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2757 "Regular expression to match files for `org-agenda-files'.
2758 If any element in the list in that variable contains a directory instead
2759 of a normal file, all files in that directory that are matched by this
2760 regular expression will be included."
2761 :group 'org-agenda
2762 :type 'regexp)
2764 (defcustom org-agenda-text-search-extra-files nil
2765 "List of extra files to be searched by text search commands.
2766 These files will be search in addition to the agenda files by the
2767 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2768 Note that these files will only be searched for text search commands,
2769 not for the other agenda views like todo lists, tag searches or the weekly
2770 agenda. This variable is intended to list notes and possibly archive files
2771 that should also be searched by these two commands.
2772 In fact, if the first element in the list is the symbol `agenda-archives',
2773 than all archive files of all agenda files will be added to the search
2774 scope."
2775 :group 'org-agenda
2776 :type '(set :greedy t
2777 (const :tag "Agenda Archives" agenda-archives)
2778 (repeat :inline t (file))))
2780 (if (fboundp 'defvaralias)
2781 (defvaralias 'org-agenda-multi-occur-extra-files
2782 'org-agenda-text-search-extra-files))
2784 (defcustom org-agenda-skip-unavailable-files nil
2785 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2786 A nil value means to remove them, after a query, from the list."
2787 :group 'org-agenda
2788 :type 'boolean)
2790 (defcustom org-calendar-to-agenda-key [?c]
2791 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2792 The command `org-calendar-goto-agenda' will be bound to this key. The
2793 default is the character `c' because then `c' can be used to switch back and
2794 forth between agenda and calendar."
2795 :group 'org-agenda
2796 :type 'sexp)
2798 (defcustom org-calendar-agenda-action-key [?k]
2799 "The key to be installed in `calendar-mode-map' for agenda-action.
2800 The command `org-agenda-action' will be bound to this key. The
2801 default is the character `k' because we use the same key in the agenda."
2802 :group 'org-agenda
2803 :type 'sexp)
2805 (defcustom org-calendar-insert-diary-entry-key [?i]
2806 "The key to be installed in `calendar-mode-map' for adding diary entries.
2807 This option is irrelevant until `org-agenda-diary-file' has been configured
2808 to point to an Org-mode file. When that is the case, the command
2809 `org-agenda-diary-entry' will be bound to the key given here, by default
2810 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2811 if you want to continue doing this, you need to change this to a different
2812 key."
2813 :group 'org-agenda
2814 :type 'sexp)
2816 (defcustom org-agenda-diary-file 'diary-file
2817 "File to which to add new entries with the `i' key in agenda and calendar.
2818 When this is the symbol `diary-file', the functionality in the Emacs
2819 calendar will be used to add entries to the `diary-file'. But when this
2820 points to a file, `org-agenda-diary-entry' will be used instead."
2821 :group 'org-agenda
2822 :type '(choice
2823 (const :tag "The standard Emacs diary file" diary-file)
2824 (file :tag "Special Org file diary entries")))
2826 (eval-after-load "calendar"
2827 '(progn
2828 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2829 'org-calendar-goto-agenda)
2830 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2831 'org-agenda-action)
2832 (add-hook 'calendar-mode-hook
2833 (lambda ()
2834 (unless (eq org-agenda-diary-file 'diary-file)
2835 (define-key calendar-mode-map
2836 org-calendar-insert-diary-entry-key
2837 'org-agenda-diary-entry))))))
2839 (defgroup org-latex nil
2840 "Options for embedding LaTeX code into Org-mode."
2841 :tag "Org LaTeX"
2842 :group 'org)
2844 (defcustom org-format-latex-options
2845 '(:foreground default :background default :scale 1.0
2846 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2847 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2848 "Options for creating images from LaTeX fragments.
2849 This is a property list with the following properties:
2850 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2851 `default' means use the foreground of the default face.
2852 :background the background color, or \"Transparent\".
2853 `default' means use the background of the default face.
2854 :scale a scaling factor for the size of the images.
2855 :html-foreground, :html-background, :html-scale
2856 the same numbers for HTML export.
2857 :matchers a list indicating which matchers should be used to
2858 find LaTeX fragments. Valid members of this list are:
2859 \"begin\" find environments
2860 \"$1\" find single characters surrounded by $.$
2861 \"$\" find math expressions surrounded by $...$
2862 \"$$\" find math expressions surrounded by $$....$$
2863 \"\\(\" find math expressions surrounded by \\(...\\)
2864 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2865 :group 'org-latex
2866 :type 'plist)
2868 (defcustom org-format-latex-header "\\documentclass{article}
2869 \\usepackage{amssymb}
2870 \\usepackage[usenames]{color}
2871 \\usepackage{amsmath}
2872 \\usepackage{latexsym}
2873 \\usepackage[mathscr]{eucal}
2874 \\pagestyle{empty} % do not remove
2875 % The settings below are copied from fullpage.sty
2876 \\setlength{\\textwidth}{\\paperwidth}
2877 \\addtolength{\\textwidth}{-3cm}
2878 \\setlength{\\oddsidemargin}{1.5cm}
2879 \\addtolength{\\oddsidemargin}{-2.54cm}
2880 \\setlength{\\evensidemargin}{\\oddsidemargin}
2881 \\setlength{\\textheight}{\\paperheight}
2882 \\addtolength{\\textheight}{-\\headheight}
2883 \\addtolength{\\textheight}{-\\headsep}
2884 \\addtolength{\\textheight}{-\\footskip}
2885 \\addtolength{\\textheight}{-3cm}
2886 \\setlength{\\topmargin}{1.5cm}
2887 \\addtolength{\\topmargin}{-2.54cm}"
2888 "The document header used for processing LaTeX fragments.
2889 It is imperative that this header make sure that no page number
2890 appears on the page."
2891 :group 'org-latex
2892 :type 'string)
2894 (defvar org-format-latex-header-extra nil)
2896 ;; The following variable is defined here because is it also used
2897 ;; when formatting latex fragments. Originally it was part of the
2898 ;; LaTeX exporter, which is why the name includes "export".
2899 (defcustom org-export-latex-packages-alist nil
2900 "Alist of packages to be inserted in the header.
2901 Each cell is of the format \( \"option\" . \"package\" \)."
2902 :group 'org-export-latex
2903 :type '(repeat
2904 (list
2905 (string :tag "option")
2906 (string :tag "package"))))
2908 (defgroup org-font-lock nil
2909 "Font-lock settings for highlighting in Org-mode."
2910 :tag "Org Font Lock"
2911 :group 'org)
2913 (defcustom org-level-color-stars-only nil
2914 "Non-nil means fontify only the stars in each headline.
2915 When nil, the entire headline is fontified.
2916 Changing it requires restart of `font-lock-mode' to become effective
2917 also in regions already fontified."
2918 :group 'org-font-lock
2919 :type 'boolean)
2921 (defcustom org-hide-leading-stars nil
2922 "Non-nil means hide the first N-1 stars in a headline.
2923 This works by using the face `org-hide' for these stars. This
2924 face is white for a light background, and black for a dark
2925 background. You may have to customize the face `org-hide' to
2926 make this work.
2927 Changing it requires restart of `font-lock-mode' to become effective
2928 also in regions already fontified.
2929 You may also set this on a per-file basis by adding one of the following
2930 lines to the buffer:
2932 #+STARTUP: hidestars
2933 #+STARTUP: showstars"
2934 :group 'org-font-lock
2935 :type 'boolean)
2937 (defcustom org-fontify-done-headline nil
2938 "Non-nil means change the face of a headline if it is marked DONE.
2939 Normally, only the TODO/DONE keyword indicates the state of a headline.
2940 When this is non-nil, the headline after the keyword is set to the
2941 `org-headline-done' as an additional indication."
2942 :group 'org-font-lock
2943 :type 'boolean)
2945 (defcustom org-fontify-emphasized-text t
2946 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2947 Changing this variable requires a restart of Emacs to take effect."
2948 :group 'org-font-lock
2949 :type 'boolean)
2951 (defcustom org-fontify-whole-heading-line nil
2952 "Non-nil means fontify the whole line for headings.
2953 This is useful when setting a background color for the
2954 org-level-* faces."
2955 :group 'org-font-lock
2956 :type 'boolean)
2958 (defcustom org-highlight-latex-fragments-and-specials nil
2959 "Non-nil means fontify what is treated specially by the exporters."
2960 :group 'org-font-lock
2961 :type 'boolean)
2963 (defcustom org-hide-emphasis-markers nil
2964 "Non-nil mean font-lock should hide the emphasis marker characters."
2965 :group 'org-font-lock
2966 :type 'boolean)
2968 (defvar org-emph-re nil
2969 "Regular expression for matching emphasis.")
2970 (defvar org-verbatim-re nil
2971 "Regular expression for matching verbatim text.")
2972 (defvar org-emphasis-regexp-components) ; defined just below
2973 (defvar org-emphasis-alist) ; defined just below
2974 (defun org-set-emph-re (var val)
2975 "Set variable and compute the emphasis regular expression."
2976 (set var val)
2977 (when (and (boundp 'org-emphasis-alist)
2978 (boundp 'org-emphasis-regexp-components)
2979 org-emphasis-alist org-emphasis-regexp-components)
2980 (let* ((e org-emphasis-regexp-components)
2981 (pre (car e))
2982 (post (nth 1 e))
2983 (border (nth 2 e))
2984 (body (nth 3 e))
2985 (nl (nth 4 e))
2986 (body1 (concat body "*?"))
2987 (markers (mapconcat 'car org-emphasis-alist ""))
2988 (vmarkers (mapconcat
2989 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2990 org-emphasis-alist "")))
2991 ;; make sure special characters appear at the right position in the class
2992 (if (string-match "\\^" markers)
2993 (setq markers (concat (replace-match "" t t markers) "^")))
2994 (if (string-match "-" markers)
2995 (setq markers (concat (replace-match "" t t markers) "-")))
2996 (if (string-match "\\^" vmarkers)
2997 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2998 (if (string-match "-" vmarkers)
2999 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3000 (if (> nl 0)
3001 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3002 (int-to-string nl) "\\}")))
3003 ;; Make the regexp
3004 (setq org-emph-re
3005 (concat "\\([" pre "]\\|^\\)"
3006 "\\("
3007 "\\([" markers "]\\)"
3008 "\\("
3009 "[^" border "]\\|"
3010 "[^" border "]"
3011 body1
3012 "[^" border "]"
3013 "\\)"
3014 "\\3\\)"
3015 "\\([" post "]\\|$\\)"))
3016 (setq org-verbatim-re
3017 (concat "\\([" pre "]\\|^\\)"
3018 "\\("
3019 "\\([" vmarkers "]\\)"
3020 "\\("
3021 "[^" border "]\\|"
3022 "[^" border "]"
3023 body1
3024 "[^" border "]"
3025 "\\)"
3026 "\\3\\)"
3027 "\\([" post "]\\|$\\)")))))
3029 (defcustom org-emphasis-regexp-components
3030 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3031 "Components used to build the regular expression for emphasis.
3032 This is a list with 6 entries. Terminology: In an emphasis string
3033 like \" *strong word* \", we call the initial space PREMATCH, the final
3034 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3035 and \"trong wor\" is the body. The different components in this variable
3036 specify what is allowed/forbidden in each part:
3038 pre Chars allowed as prematch. Beginning of line will be allowed too.
3039 post Chars allowed as postmatch. End of line will be allowed too.
3040 border The chars *forbidden* as border characters.
3041 body-regexp A regexp like \".\" to match a body character. Don't use
3042 non-shy groups here, and don't allow newline here.
3043 newline The maximum number of newlines allowed in an emphasis exp.
3045 Use customize to modify this, or restart Emacs after changing it."
3046 :group 'org-font-lock
3047 :set 'org-set-emph-re
3048 :type '(list
3049 (sexp :tag "Allowed chars in pre ")
3050 (sexp :tag "Allowed chars in post ")
3051 (sexp :tag "Forbidden chars in border ")
3052 (sexp :tag "Regexp for body ")
3053 (integer :tag "number of newlines allowed")
3054 (option (boolean :tag "Please ignore this button"))))
3056 (defcustom org-emphasis-alist
3057 `(("*" bold "<b>" "</b>")
3058 ("/" italic "<i>" "</i>")
3059 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3060 ("=" org-code "<code>" "</code>" verbatim)
3061 ("~" org-verbatim "<code>" "</code>" verbatim)
3062 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3063 "<del>" "</del>")
3065 "Special syntax for emphasized text.
3066 Text starting and ending with a special character will be emphasized, for
3067 example *bold*, _underlined_ and /italic/. This variable sets the marker
3068 characters, the face to be used by font-lock for highlighting in Org-mode
3069 Emacs buffers, and the HTML tags to be used for this.
3070 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3071 Use customize to modify this, or restart Emacs after changing it."
3072 :group 'org-font-lock
3073 :set 'org-set-emph-re
3074 :type '(repeat
3075 (list
3076 (string :tag "Marker character")
3077 (choice
3078 (face :tag "Font-lock-face")
3079 (plist :tag "Face property list"))
3080 (string :tag "HTML start tag")
3081 (string :tag "HTML end tag")
3082 (option (const verbatim)))))
3084 (defvar org-protecting-blocks
3085 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3086 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3087 This is needed for font-lock setup.")
3089 ;;; Miscellaneous options
3091 (defgroup org-completion nil
3092 "Completion in Org-mode."
3093 :tag "Org Completion"
3094 :group 'org)
3096 (defcustom org-completion-use-ido nil
3097 "Non-nil means use ido completion wherever possible.
3098 Note that `ido-mode' must be active for this variable to be relevant.
3099 If you decide to turn this variable on, you might well want to turn off
3100 `org-outline-path-complete-in-steps'.
3101 See also `org-completion-use-iswitchb'."
3102 :group 'org-completion
3103 :type 'boolean)
3105 (defcustom org-completion-use-iswitchb nil
3106 "Non-nil means use iswitchb completion wherever possible.
3107 Note that `iswitchb-mode' must be active for this variable to be relevant.
3108 If you decide to turn this variable on, you might well want to turn off
3109 `org-outline-path-complete-in-steps'.
3110 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3111 :group 'org-completion
3112 :type 'boolean)
3114 (defcustom org-completion-fallback-command 'hippie-expand
3115 "The expansion command called by \\[org-complete] in normal context.
3116 Normal means no org-mode-specific context."
3117 :group 'org-completion
3118 :type 'function)
3120 ;;; Functions and variables from their packages
3121 ;; Declared here to avoid compiler warnings
3123 ;; XEmacs only
3124 (defvar outline-mode-menu-heading)
3125 (defvar outline-mode-menu-show)
3126 (defvar outline-mode-menu-hide)
3127 (defvar zmacs-regions) ; XEmacs regions
3129 ;; Emacs only
3130 (defvar mark-active)
3132 ;; Various packages
3133 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3134 (declare-function calendar-forward-day "cal-move" (arg))
3135 (declare-function calendar-goto-date "cal-move" (date))
3136 (declare-function calendar-goto-today "cal-move" ())
3137 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3138 (defvar calc-embedded-close-formula)
3139 (defvar calc-embedded-open-formula)
3140 (declare-function cdlatex-tab "ext:cdlatex" ())
3141 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3142 (defvar font-lock-unfontify-region-function)
3143 (declare-function iswitchb-read-buffer "iswitchb"
3144 (prompt &optional default require-match start matches-set))
3145 (defvar iswitchb-temp-buflist)
3146 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3147 (defvar org-agenda-tags-todo-honor-ignore-options)
3148 (declare-function org-agenda-skip "org-agenda" ())
3149 (declare-function
3150 org-format-agenda-item "org-agenda"
3151 (extra txt &optional category tags dotime noprefix remove-re habitp))
3152 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3153 (declare-function org-agenda-change-all-lines "org-agenda"
3154 (newhead hdmarker &optional fixface just-this))
3155 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3156 (declare-function org-agenda-maybe-redo "org-agenda" ())
3157 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3158 (beg end))
3159 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3160 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3161 "org-agenda" (&optional end))
3162 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3163 (declare-function org-indent-mode "org-indent" (&optional arg))
3164 (declare-function parse-time-string "parse-time" (string))
3165 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3166 (defvar remember-data-file)
3167 (defvar texmathp-why)
3168 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3169 (declare-function table--at-cell-p "table" (position &optional object at-column))
3171 (defvar w3m-current-url)
3172 (defvar w3m-current-title)
3174 (defvar org-latex-regexps)
3176 ;;; Autoload and prepare some org modules
3178 ;; Some table stuff that needs to be defined here, because it is used
3179 ;; by the functions setting up org-mode or checking for table context.
3181 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3182 "Detects an org-type or table-type table.")
3183 (defconst org-table-line-regexp "^[ \t]*|"
3184 "Detects an org-type table line.")
3185 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3186 "Detects an org-type table line.")
3187 (defconst org-table-hline-regexp "^[ \t]*|-"
3188 "Detects an org-type table hline.")
3189 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3190 "Detects a table-type table hline.")
3191 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3192 "Searching from within a table (any type) this finds the first line
3193 outside the table.")
3195 ;; Autoload the functions in org-table.el that are needed by functions here.
3197 (eval-and-compile
3198 (org-autoload "org-table"
3199 '(org-table-align org-table-begin org-table-blank-field
3200 org-table-convert org-table-convert-region org-table-copy-down
3201 org-table-copy-region org-table-create
3202 org-table-create-or-convert-from-region
3203 org-table-create-with-table.el org-table-current-dline
3204 org-table-cut-region org-table-delete-column org-table-edit-field
3205 org-table-edit-formulas org-table-end org-table-eval-formula
3206 org-table-export org-table-field-info
3207 org-table-get-stored-formulas org-table-goto-column
3208 org-table-hline-and-move org-table-import org-table-insert-column
3209 org-table-insert-hline org-table-insert-row org-table-iterate
3210 org-table-justify-field-maybe org-table-kill-row
3211 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3212 org-table-move-column org-table-move-column-left
3213 org-table-move-column-right org-table-move-row
3214 org-table-move-row-down org-table-move-row-up
3215 org-table-next-field org-table-next-row org-table-paste-rectangle
3216 org-table-previous-field org-table-recalculate
3217 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3218 org-table-toggle-coordinate-overlays
3219 org-table-toggle-formula-debugger org-table-wrap-region
3220 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3222 (defun org-at-table-p (&optional table-type)
3223 "Return t if the cursor is inside an org-type table.
3224 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3225 (if org-enable-table-editor
3226 (save-excursion
3227 (beginning-of-line 1)
3228 (looking-at (if table-type org-table-any-line-regexp
3229 org-table-line-regexp)))
3230 nil))
3231 (defsubst org-table-p () (org-at-table-p))
3233 (defun org-at-table.el-p ()
3234 "Return t if and only if we are at a table.el table."
3235 (and (org-at-table-p 'any)
3236 (save-excursion
3237 (goto-char (org-table-begin 'any))
3238 (looking-at org-table1-hline-regexp))))
3239 (defun org-table-recognize-table.el ()
3240 "If there is a table.el table nearby, recognize it and move into it."
3241 (if org-table-tab-recognizes-table.el
3242 (if (org-at-table.el-p)
3243 (progn
3244 (beginning-of-line 1)
3245 (if (looking-at org-table-dataline-regexp)
3247 (if (looking-at org-table1-hline-regexp)
3248 (progn
3249 (beginning-of-line 2)
3250 (if (looking-at org-table-any-border-regexp)
3251 (beginning-of-line -1)))))
3252 (if (re-search-forward "|" (org-table-end t) t)
3253 (progn
3254 (require 'table)
3255 (if (table--at-cell-p (point))
3257 (message "recognizing table.el table...")
3258 (table-recognize-table)
3259 (message "recognizing table.el table...done")))
3260 (error "This should not happen..."))
3262 nil)
3263 nil))
3265 (defun org-at-table-hline-p ()
3266 "Return t if the cursor is inside a hline in a table."
3267 (if org-enable-table-editor
3268 (save-excursion
3269 (beginning-of-line 1)
3270 (looking-at org-table-hline-regexp))
3271 nil))
3273 (defvar org-table-clean-did-remove-column nil)
3275 (defun org-table-map-tables (function)
3276 "Apply FUNCTION to the start of all tables in the buffer."
3277 (save-excursion
3278 (save-restriction
3279 (widen)
3280 (goto-char (point-min))
3281 (while (re-search-forward org-table-any-line-regexp nil t)
3282 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3283 (beginning-of-line 1)
3284 (when (looking-at org-table-line-regexp)
3285 (save-excursion (funcall function))
3286 (or (looking-at org-table-line-regexp)
3287 (forward-char 1)))
3288 (re-search-forward org-table-any-border-regexp nil 1))))
3289 (message "Mapping tables: done"))
3291 ;; Declare and autoload functions from org-exp.el & Co
3293 (declare-function org-default-export-plist "org-exp")
3294 (declare-function org-infile-export-plist "org-exp")
3295 (declare-function org-get-current-options "org-exp")
3296 (eval-and-compile
3297 (org-autoload "org-exp"
3298 '(org-export org-export-visible
3299 org-insert-export-options-template
3300 org-table-clean-before-export))
3301 (org-autoload "org-ascii"
3302 '(org-export-as-ascii org-export-ascii-preprocess
3303 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3304 org-export-region-as-ascii))
3305 (org-autoload "org-latex"
3306 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3307 org-replace-region-by-latex org-export-region-as-latex
3308 org-export-as-latex org-export-as-pdf
3309 org-export-as-pdf-and-open))
3310 (org-autoload "org-html"
3311 '(org-export-as-html-and-open
3312 org-export-as-html-batch org-export-as-html-to-buffer
3313 org-replace-region-by-html org-export-region-as-html
3314 org-export-as-html))
3315 (org-autoload "org-docbook"
3316 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3317 org-replace-region-by-docbook org-export-region-as-docbook
3318 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3319 org-export-as-docbook))
3320 (org-autoload "org-icalendar"
3321 '(org-export-icalendar-this-file
3322 org-export-icalendar-all-agenda-files
3323 org-export-icalendar-combine-agenda-files))
3324 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3325 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3327 ;; Declare and autoload functions from org-agenda.el
3329 (eval-and-compile
3330 (org-autoload "org-agenda"
3331 '(org-agenda org-agenda-list org-search-view
3332 org-todo-list org-tags-view org-agenda-list-stuck-projects
3333 org-diary org-agenda-to-appt
3334 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3336 ;; Autoload org-remember
3338 (eval-and-compile
3339 (org-autoload "org-remember"
3340 '(org-remember-insinuate org-remember-annotation
3341 org-remember-apply-template org-remember org-remember-handler)))
3343 ;; Autoload org-clock.el
3346 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3347 (beg end))
3348 (declare-function org-clock-update-mode-line "org-clock" ())
3349 (declare-function org-resolve-clocks "org-clock"
3350 (&optional also-non-dangling-p prompt last-valid))
3351 (defvar org-clock-start-time)
3352 (defvar org-clock-marker (make-marker)
3353 "Marker recording the last clock-in.")
3354 (defvar org-clock-hd-marker (make-marker)
3355 "Marker recording the last clock-in, but the headline position.")
3356 (defvar org-clock-heading ""
3357 "The heading of the current clock entry.")
3358 (defun org-clock-is-active ()
3359 "Return non-nil if clock is currently running.
3360 The return value is actually the clock marker."
3361 (marker-buffer org-clock-marker))
3363 (eval-and-compile
3364 (org-autoload
3365 "org-clock"
3366 '(org-clock-in org-clock-out org-clock-cancel
3367 org-clock-goto org-clock-sum org-clock-display
3368 org-clock-remove-overlays org-clock-report
3369 org-clocktable-shift org-dblock-write:clocktable
3370 org-get-clocktable org-resolve-clocks)))
3372 (defun org-clock-update-time-maybe ()
3373 "If this is a CLOCK line, update it and return t.
3374 Otherwise, return nil."
3375 (interactive)
3376 (save-excursion
3377 (beginning-of-line 1)
3378 (skip-chars-forward " \t")
3379 (when (looking-at org-clock-string)
3380 (let ((re (concat "[ \t]*" org-clock-string
3381 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3382 "\\([ \t]*=>.*\\)?\\)?"))
3383 ts te h m s neg)
3384 (cond
3385 ((not (looking-at re))
3386 nil)
3387 ((not (match-end 2))
3388 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3389 (> org-clock-marker (point))
3390 (<= org-clock-marker (point-at-eol)))
3391 ;; The clock is running here
3392 (setq org-clock-start-time
3393 (apply 'encode-time
3394 (org-parse-time-string (match-string 1))))
3395 (org-clock-update-mode-line)))
3397 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3398 (end-of-line 1)
3399 (setq ts (match-string 1)
3400 te (match-string 3))
3401 (setq s (- (org-float-time
3402 (apply 'encode-time (org-parse-time-string te)))
3403 (org-float-time
3404 (apply 'encode-time (org-parse-time-string ts))))
3405 neg (< s 0)
3406 s (abs s)
3407 h (floor (/ s 3600))
3408 s (- s (* 3600 h))
3409 m (floor (/ s 60))
3410 s (- s (* 60 s)))
3411 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3412 t))))))
3414 (defun org-check-running-clock ()
3415 "Check if the current buffer contains the running clock.
3416 If yes, offer to stop it and to save the buffer with the changes."
3417 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3418 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3419 (buffer-name))))
3420 (org-clock-out)
3421 (when (y-or-n-p "Save changed buffer?")
3422 (save-buffer))))
3424 (defun org-clocktable-try-shift (dir n)
3425 "Check if this line starts a clock table, if yes, shift the time block."
3426 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3427 (org-clocktable-shift dir n)))
3429 ;; Autoload org-timer.el
3431 (eval-and-compile
3432 (org-autoload
3433 "org-timer"
3434 '(org-timer-start org-timer org-timer-item
3435 org-timer-change-times-in-region
3436 org-timer-set-timer
3437 org-timer-reset-timers
3438 org-timer-show-remaining-time)))
3440 ;; Autoload org-feed.el
3442 (eval-and-compile
3443 (org-autoload
3444 "org-feed"
3445 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3448 ;; Autoload org-indent.el
3450 ;; Define the variable already here, to make sure we have it.
3451 (defvar org-indent-mode nil
3452 "Non-nil if Org-Indent mode is enabled.
3453 Use the command `org-indent-mode' to change this variable.")
3455 (eval-and-compile
3456 (org-autoload
3457 "org-indent"
3458 '(org-indent-mode)))
3460 ;; Autoload org-mobile.el
3462 (eval-and-compile
3463 (org-autoload
3464 "org-mobile"
3465 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3467 ;; Autoload archiving code
3468 ;; The stuff that is needed for cycling and tags has to be defined here.
3470 (defgroup org-archive nil
3471 "Options concerning archiving in Org-mode."
3472 :tag "Org Archive"
3473 :group 'org-structure)
3475 (defcustom org-archive-location "%s_archive::"
3476 "The location where subtrees should be archived.
3478 The value of this variable is a string, consisting of two parts,
3479 separated by a double-colon. The first part is a filename and
3480 the second part is a headline.
3482 When the filename is omitted, archiving happens in the same file.
3483 %s in the filename will be replaced by the current file
3484 name (without the directory part). Archiving to a different file
3485 is useful to keep archived entries from contributing to the
3486 Org-mode Agenda.
3488 The archived entries will be filed as subtrees of the specified
3489 headline. When the headline is omitted, the subtrees are simply
3490 filed away at the end of the file, as top-level entries. Also in
3491 the heading you can use %s to represent the file name, this can be
3492 useful when using the same archive for a number of different files.
3494 Here are a few examples:
3495 \"%s_archive::\"
3496 If the current file is Projects.org, archive in file
3497 Projects.org_archive, as top-level trees. This is the default.
3499 \"::* Archived Tasks\"
3500 Archive in the current file, under the top-level headline
3501 \"* Archived Tasks\".
3503 \"~/org/archive.org::\"
3504 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3506 \"~/org/archive.org::From %s\"
3507 Archive in file ~/org/archive.org (absolute path), under headlines
3508 \"From FILENAME\" where file name is the current file name.
3510 \"basement::** Finished Tasks\"
3511 Archive in file ./basement (relative path), as level 3 trees
3512 below the level 2 heading \"** Finished Tasks\".
3514 You may set this option on a per-file basis by adding to the buffer a
3515 line like
3517 #+ARCHIVE: basement::** Finished Tasks
3519 You may also define it locally for a subtree by setting an ARCHIVE property
3520 in the entry. If such a property is found in an entry, or anywhere up
3521 the hierarchy, it will be used."
3522 :group 'org-archive
3523 :type 'string)
3525 (defcustom org-archive-tag "ARCHIVE"
3526 "The tag that marks a subtree as archived.
3527 An archived subtree does not open during visibility cycling, and does
3528 not contribute to the agenda listings.
3529 After changing this, font-lock must be restarted in the relevant buffers to
3530 get the proper fontification."
3531 :group 'org-archive
3532 :group 'org-keywords
3533 :type 'string)
3535 (defcustom org-agenda-skip-archived-trees t
3536 "Non-nil means the agenda will skip any items located in archived trees.
3537 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3538 variable is no longer recommended, you should leave it at the value t.
3539 Instead, use the key `v' to cycle the archives-mode in the agenda."
3540 :group 'org-archive
3541 :group 'org-agenda-skip
3542 :type 'boolean)
3544 (defcustom org-columns-skip-archived-trees t
3545 "Non-nil means ignore archived trees when creating column view."
3546 :group 'org-archive
3547 :group 'org-properties
3548 :type 'boolean)
3550 (defcustom org-cycle-open-archived-trees nil
3551 "Non-nil means `org-cycle' will open archived trees.
3552 An archived tree is a tree marked with the tag ARCHIVE.
3553 When nil, archived trees will stay folded. You can still open them with
3554 normal outline commands like `show-all', but not with the cycling commands."
3555 :group 'org-archive
3556 :group 'org-cycle
3557 :type 'boolean)
3559 (defcustom org-sparse-tree-open-archived-trees nil
3560 "Non-nil means sparse tree construction shows matches in archived trees.
3561 When nil, matches in these trees are highlighted, but the trees are kept in
3562 collapsed state."
3563 :group 'org-archive
3564 :group 'org-sparse-trees
3565 :type 'boolean)
3567 (defun org-cycle-hide-archived-subtrees (state)
3568 "Re-hide all archived subtrees after a visibility state change."
3569 (when (and (not org-cycle-open-archived-trees)
3570 (not (memq state '(overview folded))))
3571 (save-excursion
3572 (let* ((globalp (memq state '(contents all)))
3573 (beg (if globalp (point-min) (point)))
3574 (end (if globalp (point-max) (org-end-of-subtree t))))
3575 (org-hide-archived-subtrees beg end)
3576 (goto-char beg)
3577 (if (looking-at (concat ".*:" org-archive-tag ":"))
3578 (message "%s" (substitute-command-keys
3579 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3581 (defun org-force-cycle-archived ()
3582 "Cycle subtree even if it is archived."
3583 (interactive)
3584 (setq this-command 'org-cycle)
3585 (let ((org-cycle-open-archived-trees t))
3586 (call-interactively 'org-cycle)))
3588 (defun org-hide-archived-subtrees (beg end)
3589 "Re-hide all archived subtrees after a visibility state change."
3590 (save-excursion
3591 (let* ((re (concat ":" org-archive-tag ":")))
3592 (goto-char beg)
3593 (while (re-search-forward re end t)
3594 (and (org-on-heading-p) (org-flag-subtree t))
3595 (org-end-of-subtree t)))))
3597 (defun org-flag-subtree (flag)
3598 (save-excursion
3599 (org-back-to-heading t)
3600 (outline-end-of-heading)
3601 (outline-flag-region (point)
3602 (progn (org-end-of-subtree t) (point))
3603 flag)))
3605 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3607 (eval-and-compile
3608 (org-autoload "org-archive"
3609 '(org-add-archive-files org-archive-subtree
3610 org-archive-to-archive-sibling org-toggle-archive-tag
3611 org-archive-subtree-default
3612 org-archive-subtree-default-with-confirmation)))
3614 ;; Autoload Column View Code
3616 (declare-function org-columns-number-to-string "org-colview")
3617 (declare-function org-columns-get-format-and-top-level "org-colview")
3618 (declare-function org-columns-compute "org-colview")
3620 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3621 '(org-columns-number-to-string org-columns-get-format-and-top-level
3622 org-columns-compute org-agenda-columns org-columns-remove-overlays
3623 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3625 ;; Autoload ID code
3627 (declare-function org-id-store-link "org-id")
3628 (declare-function org-id-locations-load "org-id")
3629 (declare-function org-id-locations-save "org-id")
3630 (defvar org-id-track-globally)
3631 (org-autoload "org-id"
3632 '(org-id-get-create org-id-new org-id-copy org-id-get
3633 org-id-get-with-outline-path-completion
3634 org-id-get-with-outline-drilling
3635 org-id-goto org-id-find org-id-store-link))
3637 ;; Autoload Plotting Code
3639 (org-autoload "org-plot"
3640 '(org-plot/gnuplot))
3642 ;;; Variables for pre-computed regular expressions, all buffer local
3644 (defvar org-drawer-regexp nil
3645 "Matches first line of a hidden block.")
3646 (make-variable-buffer-local 'org-drawer-regexp)
3647 (defvar org-todo-regexp nil
3648 "Matches any of the TODO state keywords.")
3649 (make-variable-buffer-local 'org-todo-regexp)
3650 (defvar org-not-done-regexp nil
3651 "Matches any of the TODO state keywords except the last one.")
3652 (make-variable-buffer-local 'org-not-done-regexp)
3653 (defvar org-not-done-heading-regexp nil
3654 "Matches a TODO headline that is not done.")
3655 (make-variable-buffer-local 'org-not-done-regexp)
3656 (defvar org-todo-line-regexp nil
3657 "Matches a headline and puts TODO state into group 2 if present.")
3658 (make-variable-buffer-local 'org-todo-line-regexp)
3659 (defvar org-complex-heading-regexp nil
3660 "Matches a headline and puts everything into groups:
3661 group 1: the stars
3662 group 2: The todo keyword, maybe
3663 group 3: Priority cookie
3664 group 4: True headline
3665 group 5: Tags")
3666 (make-variable-buffer-local 'org-complex-heading-regexp)
3667 (defvar org-complex-heading-regexp-format nil)
3668 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3669 (defvar org-todo-line-tags-regexp nil
3670 "Matches a headline and puts TODO state into group 2 if present.
3671 Also put tags into group 4 if tags are present.")
3672 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3673 (defvar org-nl-done-regexp nil
3674 "Matches newline followed by a headline with the DONE keyword.")
3675 (make-variable-buffer-local 'org-nl-done-regexp)
3676 (defvar org-looking-at-done-regexp nil
3677 "Matches the DONE keyword a point.")
3678 (make-variable-buffer-local 'org-looking-at-done-regexp)
3679 (defvar org-ds-keyword-length 12
3680 "Maximum length of the Deadline and SCHEDULED keywords.")
3681 (make-variable-buffer-local 'org-ds-keyword-length)
3682 (defvar org-deadline-regexp nil
3683 "Matches the DEADLINE keyword.")
3684 (make-variable-buffer-local 'org-deadline-regexp)
3685 (defvar org-deadline-time-regexp nil
3686 "Matches the DEADLINE keyword together with a time stamp.")
3687 (make-variable-buffer-local 'org-deadline-time-regexp)
3688 (defvar org-deadline-line-regexp nil
3689 "Matches the DEADLINE keyword and the rest of the line.")
3690 (make-variable-buffer-local 'org-deadline-line-regexp)
3691 (defvar org-scheduled-regexp nil
3692 "Matches the SCHEDULED keyword.")
3693 (make-variable-buffer-local 'org-scheduled-regexp)
3694 (defvar org-scheduled-time-regexp nil
3695 "Matches the SCHEDULED keyword together with a time stamp.")
3696 (make-variable-buffer-local 'org-scheduled-time-regexp)
3697 (defvar org-closed-time-regexp nil
3698 "Matches the CLOSED keyword together with a time stamp.")
3699 (make-variable-buffer-local 'org-closed-time-regexp)
3701 (defvar org-keyword-time-regexp nil
3702 "Matches any of the 4 keywords, together with the time stamp.")
3703 (make-variable-buffer-local 'org-keyword-time-regexp)
3704 (defvar org-keyword-time-not-clock-regexp nil
3705 "Matches any of the 3 keywords, together with the time stamp.")
3706 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3707 (defvar org-maybe-keyword-time-regexp nil
3708 "Matches a timestamp, possibly preceeded by a keyword.")
3709 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3710 (defvar org-planning-or-clock-line-re nil
3711 "Matches a line with planning or clock info.")
3712 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3713 (defvar org-all-time-keywords nil
3714 "List of time keywords.")
3715 (make-variable-buffer-local 'org-all-time-keywords)
3717 (defconst org-plain-time-of-day-regexp
3718 (concat
3719 "\\(\\<[012]?[0-9]"
3720 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3721 "\\(--?"
3722 "\\(\\<[012]?[0-9]"
3723 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3724 "\\)?")
3725 "Regular expression to match a plain time or time range.
3726 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3727 groups carry important information:
3728 0 the full match
3729 1 the first time, range or not
3730 8 the second time, if it is a range.")
3732 (defconst org-plain-time-extension-regexp
3733 (concat
3734 "\\(\\<[012]?[0-9]"
3735 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3736 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3737 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3738 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3739 groups carry important information:
3740 0 the full match
3741 7 hours of duration
3742 9 minutes of duration")
3744 (defconst org-stamp-time-of-day-regexp
3745 (concat
3746 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3747 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3748 "\\(--?"
3749 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3750 "Regular expression to match a timestamp time or time range.
3751 After a match, the following groups carry important information:
3752 0 the full match
3753 1 date plus weekday, for back referencing to make sure both times are on the same day
3754 2 the first time, range or not
3755 4 the second time, if it is a range.")
3757 (defconst org-startup-options
3758 '(("fold" org-startup-folded t)
3759 ("overview" org-startup-folded t)
3760 ("nofold" org-startup-folded nil)
3761 ("showall" org-startup-folded nil)
3762 ("showeverything" org-startup-folded showeverything)
3763 ("content" org-startup-folded content)
3764 ("indent" org-startup-indented t)
3765 ("noindent" org-startup-indented nil)
3766 ("hidestars" org-hide-leading-stars t)
3767 ("showstars" org-hide-leading-stars nil)
3768 ("odd" org-odd-levels-only t)
3769 ("oddeven" org-odd-levels-only nil)
3770 ("align" org-startup-align-all-tables t)
3771 ("noalign" org-startup-align-all-tables nil)
3772 ("customtime" org-display-custom-times t)
3773 ("logdone" org-log-done time)
3774 ("lognotedone" org-log-done note)
3775 ("nologdone" org-log-done nil)
3776 ("lognoteclock-out" org-log-note-clock-out t)
3777 ("nolognoteclock-out" org-log-note-clock-out nil)
3778 ("logrepeat" org-log-repeat state)
3779 ("lognoterepeat" org-log-repeat note)
3780 ("nologrepeat" org-log-repeat nil)
3781 ("logreschedule" org-log-reschedule time)
3782 ("lognotereschedule" org-log-reschedule note)
3783 ("nologreschedule" org-log-reschedule nil)
3784 ("logredeadline" org-log-redeadline time)
3785 ("lognoteredeadline" org-log-redeadline note)
3786 ("nologredeadline" org-log-redeadline nil)
3787 ("fninline" org-footnote-define-inline t)
3788 ("nofninline" org-footnote-define-inline nil)
3789 ("fnlocal" org-footnote-section nil)
3790 ("fnauto" org-footnote-auto-label t)
3791 ("fnprompt" org-footnote-auto-label nil)
3792 ("fnconfirm" org-footnote-auto-label confirm)
3793 ("fnplain" org-footnote-auto-label plain)
3794 ("fnadjust" org-footnote-auto-adjust t)
3795 ("nofnadjust" org-footnote-auto-adjust nil)
3796 ("constcgs" constants-unit-system cgs)
3797 ("constSI" constants-unit-system SI)
3798 ("noptag" org-tag-persistent-alist nil)
3799 ("hideblocks" org-hide-block-startup t)
3800 ("nohideblocks" org-hide-block-startup nil)
3801 ("beamer" org-startup-with-beamer-mode t))
3802 "Variable associated with STARTUP options for org-mode.
3803 Each element is a list of three items: The startup options as written
3804 in the #+STARTUP line, the corresponding variable, and the value to
3805 set this variable to if the option is found. An optional forth element PUSH
3806 means to push this value onto the list in the variable.")
3808 (defun org-set-regexps-and-options ()
3809 "Precompute regular expressions for current buffer."
3810 (when (org-mode-p)
3811 (org-set-local 'org-todo-kwd-alist nil)
3812 (org-set-local 'org-todo-key-alist nil)
3813 (org-set-local 'org-todo-key-trigger nil)
3814 (org-set-local 'org-todo-keywords-1 nil)
3815 (org-set-local 'org-done-keywords nil)
3816 (org-set-local 'org-todo-heads nil)
3817 (org-set-local 'org-todo-sets nil)
3818 (org-set-local 'org-todo-log-states nil)
3819 (org-set-local 'org-file-properties nil)
3820 (org-set-local 'org-file-tags nil)
3821 (let ((re (org-make-options-regexp
3822 '("CATEGORY" "TODO" "COLUMNS"
3823 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3824 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS")
3825 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3826 (splitre "[ \t]+")
3827 kwds kws0 kwsa key log value cat arch tags const links hw dws
3828 tail sep kws1 prio props ftags drawers beamer-p
3829 ext-setup-or-nil setup-contents (start 0))
3830 (save-excursion
3831 (save-restriction
3832 (widen)
3833 (goto-char (point-min))
3834 (while (or (and ext-setup-or-nil
3835 (string-match re ext-setup-or-nil start)
3836 (setq start (match-end 0)))
3837 (and (setq ext-setup-or-nil nil start 0)
3838 (re-search-forward re nil t)))
3839 (setq key (upcase (match-string 1 ext-setup-or-nil))
3840 value (org-match-string-no-properties 2 ext-setup-or-nil))
3841 (cond
3842 ((equal key "CATEGORY")
3843 (if (string-match "[ \t]+$" value)
3844 (setq value (replace-match "" t t value)))
3845 (setq cat value))
3846 ((member key '("SEQ_TODO" "TODO"))
3847 (push (cons 'sequence (org-split-string value splitre)) kwds))
3848 ((equal key "TYP_TODO")
3849 (push (cons 'type (org-split-string value splitre)) kwds))
3850 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3851 ;; general TODO-like setup
3852 (push (cons (intern (downcase (match-string 1 key)))
3853 (org-split-string value splitre)) kwds))
3854 ((equal key "TAGS")
3855 (setq tags (append tags (if tags '("\\n") nil)
3856 (org-split-string value splitre))))
3857 ((equal key "COLUMNS")
3858 (org-set-local 'org-columns-default-format value))
3859 ((equal key "LINK")
3860 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3861 (push (cons (match-string 1 value)
3862 (org-trim (match-string 2 value)))
3863 links)))
3864 ((equal key "PRIORITIES")
3865 (setq prio (org-split-string value " +")))
3866 ((equal key "PROPERTY")
3867 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3868 (push (cons (match-string 1 value) (match-string 2 value))
3869 props)))
3870 ((equal key "FILETAGS")
3871 (when (string-match "\\S-" value)
3872 (setq ftags
3873 (append
3874 ftags
3875 (apply 'append
3876 (mapcar (lambda (x) (org-split-string x ":"))
3877 (org-split-string value)))))))
3878 ((equal key "DRAWERS")
3879 (setq drawers (org-split-string value splitre)))
3880 ((equal key "CONSTANTS")
3881 (setq const (append const (org-split-string value splitre))))
3882 ((equal key "STARTUP")
3883 (let ((opts (org-split-string value splitre))
3884 l var val)
3885 (while (setq l (pop opts))
3886 (when (setq l (assoc l org-startup-options))
3887 (setq var (nth 1 l) val (nth 2 l))
3888 (if (not (nth 3 l))
3889 (set (make-local-variable var) val)
3890 (if (not (listp (symbol-value var)))
3891 (set (make-local-variable var) nil))
3892 (set (make-local-variable var) (symbol-value var))
3893 (add-to-list var val))))))
3894 ((equal key "ARCHIVE")
3895 (string-match " *$" value)
3896 (setq arch (replace-match "" t t value))
3897 (remove-text-properties 0 (length arch)
3898 '(face t fontified t) arch))
3899 ((equal key "LATEX_CLASS")
3900 (setq beamer-p (equal value "beamer")))
3901 ((equal key "SETUPFILE")
3902 (setq setup-contents (org-file-contents
3903 (expand-file-name
3904 (org-remove-double-quotes value))
3905 'noerror))
3906 (if (not ext-setup-or-nil)
3907 (setq ext-setup-or-nil setup-contents start 0)
3908 (setq ext-setup-or-nil
3909 (concat (substring ext-setup-or-nil 0 start)
3910 "\n" setup-contents "\n"
3911 (substring ext-setup-or-nil start)))))
3912 ))))
3913 (when cat
3914 (org-set-local 'org-category (intern cat))
3915 (push (cons "CATEGORY" cat) props))
3916 (when prio
3917 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3918 (setq prio (mapcar 'string-to-char prio))
3919 (org-set-local 'org-highest-priority (nth 0 prio))
3920 (org-set-local 'org-lowest-priority (nth 1 prio))
3921 (org-set-local 'org-default-priority (nth 2 prio)))
3922 (and props (org-set-local 'org-file-properties (nreverse props)))
3923 (and ftags (org-set-local 'org-file-tags
3924 (mapcar 'org-add-prop-inherited ftags)))
3925 (and drawers (org-set-local 'org-drawers drawers))
3926 (and arch (org-set-local 'org-archive-location arch))
3927 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3928 ;; Process the TODO keywords
3929 (unless kwds
3930 ;; Use the global values as if they had been given locally.
3931 (setq kwds (default-value 'org-todo-keywords))
3932 (if (stringp (car kwds))
3933 (setq kwds (list (cons org-todo-interpretation
3934 (default-value 'org-todo-keywords)))))
3935 (setq kwds (reverse kwds)))
3936 (setq kwds (nreverse kwds))
3937 (let (inter kws kw)
3938 (while (setq kws (pop kwds))
3939 (let ((kws (or
3940 (run-hook-with-args-until-success
3941 'org-todo-setup-filter-hook kws)
3942 kws)))
3943 (setq inter (pop kws) sep (member "|" kws)
3944 kws0 (delete "|" (copy-sequence kws))
3945 kwsa nil
3946 kws1 (mapcar
3947 (lambda (x)
3948 ;; 1 2
3949 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3950 (progn
3951 (setq kw (match-string 1 x)
3952 key (and (match-end 2) (match-string 2 x))
3953 log (org-extract-log-state-settings x))
3954 (push (cons kw (and key (string-to-char key))) kwsa)
3955 (and log (push log org-todo-log-states))
3957 (error "Invalid TODO keyword %s" x)))
3958 kws0)
3959 kwsa (if kwsa (append '((:startgroup))
3960 (nreverse kwsa)
3961 '((:endgroup))))
3962 hw (car kws1)
3963 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3964 tail (list inter hw (car dws) (org-last dws))))
3965 (add-to-list 'org-todo-heads hw 'append)
3966 (push kws1 org-todo-sets)
3967 (setq org-done-keywords (append org-done-keywords dws nil))
3968 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3969 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3970 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3971 (setq org-todo-sets (nreverse org-todo-sets)
3972 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3973 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3974 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3975 ;; Process the constants
3976 (when const
3977 (let (e cst)
3978 (while (setq e (pop const))
3979 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3980 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3981 (setq org-table-formula-constants-local cst)))
3983 ;; Process the tags.
3984 (when tags
3985 (let (e tgs)
3986 (while (setq e (pop tags))
3987 (cond
3988 ((equal e "{") (push '(:startgroup) tgs))
3989 ((equal e "}") (push '(:endgroup) tgs))
3990 ((equal e "\\n") (push '(:newline) tgs))
3991 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3992 (push (cons (match-string 1 e)
3993 (string-to-char (match-string 2 e)))
3994 tgs))
3995 (t (push (list e) tgs))))
3996 (org-set-local 'org-tag-alist nil)
3997 (while (setq e (pop tgs))
3998 (or (and (stringp (car e))
3999 (assoc (car e) org-tag-alist))
4000 (push e org-tag-alist)))))
4002 ;; Compute the regular expressions and other local variables
4003 (if (not org-done-keywords)
4004 (setq org-done-keywords (and org-todo-keywords-1
4005 (list (org-last org-todo-keywords-1)))))
4006 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4007 (length org-scheduled-string)
4008 (length org-clock-string)
4009 (length org-closed-string)))
4010 org-drawer-regexp
4011 (concat "^[ \t]*:\\("
4012 (mapconcat 'regexp-quote org-drawers "\\|")
4013 "\\):[ \t]*$")
4014 org-not-done-keywords
4015 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4016 org-todo-regexp
4017 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4018 "\\|") "\\)\\>")
4019 org-not-done-regexp
4020 (concat "\\<\\("
4021 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4022 "\\)\\>")
4023 org-not-done-heading-regexp
4024 (concat "^\\(\\*+\\)[ \t]+\\("
4025 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4026 "\\)\\>")
4027 org-todo-line-regexp
4028 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4029 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4030 "\\)\\>\\)?[ \t]*\\(.*\\)")
4031 org-complex-heading-regexp
4032 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4033 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4034 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4035 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4036 org-complex-heading-regexp-format
4037 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4038 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4039 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
4040 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4041 org-nl-done-regexp
4042 (concat "\n\\*+[ \t]+"
4043 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4044 "\\)" "\\>")
4045 org-todo-line-tags-regexp
4046 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4047 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4048 (org-re
4049 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4050 org-looking-at-done-regexp
4051 (concat "^" "\\(?:"
4052 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4053 "\\>")
4054 org-deadline-regexp (concat "\\<" org-deadline-string)
4055 org-deadline-time-regexp
4056 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4057 org-deadline-line-regexp
4058 (concat "\\<\\(" org-deadline-string "\\).*")
4059 org-scheduled-regexp
4060 (concat "\\<" org-scheduled-string)
4061 org-scheduled-time-regexp
4062 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4063 org-closed-time-regexp
4064 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4065 org-keyword-time-regexp
4066 (concat "\\<\\(" org-scheduled-string
4067 "\\|" org-deadline-string
4068 "\\|" org-closed-string
4069 "\\|" org-clock-string "\\)"
4070 " *[[<]\\([^]>]+\\)[]>]")
4071 org-keyword-time-not-clock-regexp
4072 (concat "\\<\\(" org-scheduled-string
4073 "\\|" org-deadline-string
4074 "\\|" org-closed-string
4075 "\\)"
4076 " *[[<]\\([^]>]+\\)[]>]")
4077 org-maybe-keyword-time-regexp
4078 (concat "\\(\\<\\(" org-scheduled-string
4079 "\\|" org-deadline-string
4080 "\\|" org-closed-string
4081 "\\|" org-clock-string "\\)\\)?"
4082 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4083 org-planning-or-clock-line-re
4084 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4085 "\\|" org-deadline-string
4086 "\\|" org-closed-string "\\|" org-clock-string
4087 "\\)\\>\\)")
4088 org-all-time-keywords
4089 (mapcar (lambda (w) (substring w 0 -1))
4090 (list org-scheduled-string org-deadline-string
4091 org-clock-string org-closed-string))
4093 (org-compute-latex-and-specials-regexp)
4094 (org-set-font-lock-defaults))))
4096 (defun org-file-contents (file &optional noerror)
4097 "Return the contents of FILE, as a string."
4098 (if (or (not file)
4099 (not (file-readable-p file)))
4100 (if noerror
4101 (progn
4102 (message "Cannot read file %s" file)
4103 (ding) (sit-for 2)
4105 (error "Cannot read file %s" file))
4106 (with-temp-buffer
4107 (insert-file-contents file)
4108 (buffer-string))))
4110 (defun org-extract-log-state-settings (x)
4111 "Extract the log state setting from a TODO keyword string.
4112 This will extract info from a string like \"WAIT(w@/!)\"."
4113 (let (kw key log1 log2)
4114 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4115 (setq kw (match-string 1 x)
4116 key (and (match-end 2) (match-string 2 x))
4117 log1 (and (match-end 3) (match-string 3 x))
4118 log2 (and (match-end 4) (match-string 4 x)))
4119 (and (or log1 log2)
4120 (list kw
4121 (and log1 (if (equal log1 "!") 'time 'note))
4122 (and log2 (if (equal log2 "!") 'time 'note)))))))
4124 (defun org-remove-keyword-keys (list)
4125 "Remove a pair of parenthesis at the end of each string in LIST."
4126 (mapcar (lambda (x)
4127 (if (string-match "(.*)$" x)
4128 (substring x 0 (match-beginning 0))
4130 list))
4132 (defun org-assign-fast-keys (alist)
4133 "Assign fast keys to a keyword-key alist.
4134 Respect keys that are already there."
4135 (let (new e (alt ?0))
4136 (while (setq e (pop alist))
4137 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4138 (cdr e)) ;; Key already assigned.
4139 (push e new)
4140 (let ((clist (string-to-list (downcase (car e))))
4141 (used (append new alist)))
4142 (when (= (car clist) ?@)
4143 (pop clist))
4144 (while (and clist (rassoc (car clist) used))
4145 (pop clist))
4146 (unless clist
4147 (while (rassoc alt used)
4148 (incf alt)))
4149 (push (cons (car e) (or (car clist) alt)) new))))
4150 (nreverse new)))
4152 ;;; Some variables used in various places
4154 (defvar org-window-configuration nil
4155 "Used in various places to store a window configuration.")
4156 (defvar org-selected-window nil
4157 "Used in various places to store a window configuration.")
4158 (defvar org-finish-function nil
4159 "Function to be called when `C-c C-c' is used.
4160 This is for getting out of special buffers like remember.")
4163 ;; FIXME: Occasionally check by commenting these, to make sure
4164 ;; no other functions uses these, forgetting to let-bind them.
4165 (defvar entry)
4166 (defvar last-state)
4167 (defvar date)
4169 ;; Defined somewhere in this file, but used before definition.
4170 (defvar org-html-entities)
4171 (defvar org-struct-menu)
4172 (defvar org-org-menu)
4173 (defvar org-tbl-menu)
4175 ;;;; Define the Org-mode
4177 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4178 (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."))
4181 ;; We use a before-change function to check if a table might need
4182 ;; an update.
4183 (defvar org-table-may-need-update t
4184 "Indicates that a table might need an update.
4185 This variable is set by `org-before-change-function'.
4186 `org-table-align' sets it back to nil.")
4187 (defun org-before-change-function (beg end)
4188 "Every change indicates that a table might need an update."
4189 (setq org-table-may-need-update t))
4190 (defvar org-mode-map)
4191 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4192 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4193 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4194 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4195 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4196 (defvar org-table-buffer-is-an nil)
4197 (defconst org-outline-regexp "\\*+ ")
4199 ;;;###autoload
4200 (define-derived-mode org-mode outline-mode "Org"
4201 "Outline-based notes management and organizer, alias
4202 \"Carsten's outline-mode for keeping track of everything.\"
4204 Org-mode develops organizational tasks around a NOTES file which
4205 contains information about projects as plain text. Org-mode is
4206 implemented on top of outline-mode, which is ideal to keep the content
4207 of large files well structured. It supports ToDo items, deadlines and
4208 time stamps, which magically appear in the diary listing of the Emacs
4209 calendar. Tables are easily created with a built-in table editor.
4210 Plain text URL-like links connect to websites, emails (VM), Usenet
4211 messages (Gnus), BBDB entries, and any files related to the project.
4212 For printing and sharing of notes, an Org-mode file (or a part of it)
4213 can be exported as a structured ASCII or HTML file.
4215 The following commands are available:
4217 \\{org-mode-map}"
4219 ;; Get rid of Outline menus, they are not needed
4220 ;; Need to do this here because define-derived-mode sets up
4221 ;; the keymap so late. Still, it is a waste to call this each time
4222 ;; we switch another buffer into org-mode.
4223 (if (featurep 'xemacs)
4224 (when (boundp 'outline-mode-menu-heading)
4225 ;; Assume this is Greg's port, it used easymenu
4226 (easy-menu-remove outline-mode-menu-heading)
4227 (easy-menu-remove outline-mode-menu-show)
4228 (easy-menu-remove outline-mode-menu-hide))
4229 (define-key org-mode-map [menu-bar headings] 'undefined)
4230 (define-key org-mode-map [menu-bar hide] 'undefined)
4231 (define-key org-mode-map [menu-bar show] 'undefined))
4233 (org-load-modules-maybe)
4234 (easy-menu-add org-org-menu)
4235 (easy-menu-add org-tbl-menu)
4236 (org-install-agenda-files-menu)
4237 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4238 (org-add-to-invisibility-spec '(org-cwidth))
4239 (org-add-to-invisibility-spec '(org-hide-block . t))
4240 (when (featurep 'xemacs)
4241 (org-set-local 'line-move-ignore-invisible t))
4242 (org-set-local 'outline-regexp org-outline-regexp)
4243 (org-set-local 'outline-level 'org-outline-level)
4244 (when (and org-ellipsis
4245 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4246 (fboundp 'make-glyph-code))
4247 (unless org-display-table
4248 (setq org-display-table (make-display-table)))
4249 (set-display-table-slot
4250 org-display-table 4
4251 (vconcat (mapcar
4252 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4253 org-ellipsis)))
4254 (if (stringp org-ellipsis) org-ellipsis "..."))))
4255 (setq buffer-display-table org-display-table))
4256 (org-set-regexps-and-options)
4257 (when (and org-tag-faces (not org-tags-special-faces-re))
4258 ;; tag faces set outside customize.... force initialization.
4259 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4260 ;; Calc embedded
4261 (org-set-local 'calc-embedded-open-mode "# ")
4262 (modify-syntax-entry ?# "<")
4263 (modify-syntax-entry ?@ "w")
4264 (if org-startup-truncated (setq truncate-lines t))
4265 (org-set-local 'font-lock-unfontify-region-function
4266 'org-unfontify-region)
4267 ;; Activate before-change-function
4268 (org-set-local 'org-table-may-need-update t)
4269 (org-add-hook 'before-change-functions 'org-before-change-function nil
4270 'local)
4271 ;; Check for running clock before killing a buffer
4272 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4273 ;; Paragraphs and auto-filling
4274 (org-set-autofill-regexps)
4275 (setq indent-line-function 'org-indent-line-function)
4276 (org-update-radio-target-regexp)
4277 ;; Make sure dependence stuff works reliably, even for users who set it
4278 ;; too late :-(
4279 (if org-enforce-todo-dependencies
4280 (add-hook 'org-blocker-hook
4281 'org-block-todo-from-children-or-siblings-or-parent)
4282 (remove-hook 'org-blocker-hook
4283 'org-block-todo-from-children-or-siblings-or-parent))
4284 (if org-enforce-todo-checkbox-dependencies
4285 (add-hook 'org-blocker-hook
4286 'org-block-todo-from-checkboxes)
4287 (remove-hook 'org-blocker-hook
4288 'org-block-todo-from-checkboxes))
4290 ;; Comment characters
4291 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4292 (org-set-local 'comment-padding " ")
4294 ;; Align options lines
4295 (org-set-local
4296 'align-mode-rules-list
4297 '((org-in-buffer-settings
4298 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4299 (modes . '(org-mode)))))
4301 ;; Imenu
4302 (org-set-local 'imenu-create-index-function
4303 'org-imenu-get-tree)
4305 ;; Make isearch reveal context
4306 (if (or (featurep 'xemacs)
4307 (not (boundp 'outline-isearch-open-invisible-function)))
4308 ;; Emacs 21 and XEmacs make use of the hook
4309 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4310 ;; Emacs 22 deals with this through a special variable
4311 (org-set-local 'outline-isearch-open-invisible-function
4312 (lambda (&rest ignore) (org-show-context 'isearch))))
4314 ;; Turn on org-beamer-mode?
4315 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4317 ;; If empty file that did not turn on org-mode automatically, make it to.
4318 (if (and org-insert-mode-line-in-empty-file
4319 (interactive-p)
4320 (= (point-min) (point-max)))
4321 (insert "# -*- mode: org -*-\n\n"))
4322 (unless org-inhibit-startup
4323 (when org-startup-align-all-tables
4324 (let ((bmp (buffer-modified-p)))
4325 (org-table-map-tables 'org-table-align)
4326 (set-buffer-modified-p bmp)))
4327 (when org-startup-indented
4328 (require 'org-indent)
4329 (org-indent-mode 1))
4330 (unless org-inhibit-startup-visibility-stuff
4331 (org-set-startup-visibility))))
4333 (when (fboundp 'abbrev-table-put)
4334 (abbrev-table-put org-mode-abbrev-table
4335 :parents (list text-mode-abbrev-table)))
4337 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4339 (defun org-current-time ()
4340 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4341 (if (> (car org-time-stamp-rounding-minutes) 1)
4342 (let ((r (car org-time-stamp-rounding-minutes))
4343 (time (decode-time)))
4344 (apply 'encode-time
4345 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4346 (nthcdr 2 time))))
4347 (current-time)))
4349 ;;;; Font-Lock stuff, including the activators
4351 (defvar org-mouse-map (make-sparse-keymap))
4352 (org-defkey org-mouse-map
4353 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4354 (org-defkey org-mouse-map
4355 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4356 (when org-mouse-1-follows-link
4357 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4358 (when org-tab-follows-link
4359 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4360 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4362 (require 'font-lock)
4364 (defconst org-non-link-chars "]\t\n\r<>")
4365 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4366 "shell" "elisp"))
4367 (defvar org-link-types-re nil
4368 "Matches a link that has a url-like prefix like \"http:\"")
4369 (defvar org-link-re-with-space nil
4370 "Matches a link with spaces, optional angular brackets around it.")
4371 (defvar org-link-re-with-space2 nil
4372 "Matches a link with spaces, optional angular brackets around it.")
4373 (defvar org-link-re-with-space3 nil
4374 "Matches a link with spaces, only for internal part in bracket links.")
4375 (defvar org-angle-link-re nil
4376 "Matches link with angular brackets, spaces are allowed.")
4377 (defvar org-plain-link-re nil
4378 "Matches plain link, without spaces.")
4379 (defvar org-bracket-link-regexp nil
4380 "Matches a link in double brackets.")
4381 (defvar org-bracket-link-analytic-regexp nil
4382 "Regular expression used to analyze links.
4383 Here is what the match groups contain after a match:
4384 1: http:
4385 2: http
4386 3: path
4387 4: [desc]
4388 5: desc")
4389 (defvar org-bracket-link-analytic-regexp++ nil
4390 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4391 (defvar org-any-link-re nil
4392 "Regular expression matching any link.")
4394 (defun org-make-link-regexps ()
4395 "Update the link regular expressions.
4396 This should be called after the variable `org-link-types' has changed."
4397 (setq org-link-types-re
4398 (concat
4399 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4400 org-link-re-with-space
4401 (concat
4402 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4403 "\\([^" org-non-link-chars " ]"
4404 "[^" org-non-link-chars "]*"
4405 "[^" org-non-link-chars " ]\\)>?")
4406 org-link-re-with-space2
4407 (concat
4408 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4409 "\\([^" org-non-link-chars " ]"
4410 "[^\t\n\r]*"
4411 "[^" org-non-link-chars " ]\\)>?")
4412 org-link-re-with-space3
4413 (concat
4414 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4415 "\\([^" org-non-link-chars " ]"
4416 "[^\t\n\r]*\\)")
4417 org-angle-link-re
4418 (concat
4419 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4420 "\\([^" org-non-link-chars " ]"
4421 "[^" org-non-link-chars "]*"
4422 "\\)>")
4423 org-plain-link-re
4424 (concat
4425 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4426 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4427 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4428 org-bracket-link-regexp
4429 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4430 org-bracket-link-analytic-regexp
4431 (concat
4432 "\\[\\["
4433 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4434 "\\([^]]+\\)"
4435 "\\]"
4436 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4437 "\\]")
4438 org-bracket-link-analytic-regexp++
4439 (concat
4440 "\\[\\["
4441 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4442 "\\([^]]+\\)"
4443 "\\]"
4444 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4445 "\\]")
4446 org-any-link-re
4447 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4448 org-angle-link-re "\\)\\|\\("
4449 org-plain-link-re "\\)")))
4451 (org-make-link-regexps)
4453 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4454 "Regular expression for fast time stamp matching.")
4455 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4456 "Regular expression for fast time stamp matching.")
4457 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4458 "Regular expression matching time strings for analysis.
4459 This one does not require the space after the date, so it can be used
4460 on a string that terminates immediately after the date.")
4461 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4462 "Regular expression matching time strings for analysis.")
4463 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4464 "Regular expression matching time stamps, with groups.")
4465 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4466 "Regular expression matching time stamps (also [..]), with groups.")
4467 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4468 "Regular expression matching a time stamp range.")
4469 (defconst org-tr-regexp-both
4470 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4471 "Regular expression matching a time stamp range.")
4472 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4473 org-ts-regexp "\\)?")
4474 "Regular expression matching a time stamp or time stamp range.")
4475 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4476 org-ts-regexp-both "\\)?")
4477 "Regular expression matching a time stamp or time stamp range.
4478 The time stamps may be either active or inactive.")
4480 (defvar org-emph-face nil)
4482 (defun org-do-emphasis-faces (limit)
4483 "Run through the buffer and add overlays to links."
4484 (let (rtn a)
4485 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4486 (if (not (= (char-after (match-beginning 3))
4487 (char-after (match-beginning 4))))
4488 (progn
4489 (setq rtn t)
4490 (setq a (assoc (match-string 3) org-emphasis-alist))
4491 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4492 'face
4493 (nth 1 a))
4494 (and (nth 4 a)
4495 (org-remove-flyspell-overlays-in
4496 (match-beginning 0) (match-end 0)))
4497 (add-text-properties (match-beginning 2) (match-end 2)
4498 '(font-lock-multiline t))
4499 (when org-hide-emphasis-markers
4500 (add-text-properties (match-end 4) (match-beginning 5)
4501 '(invisible org-link))
4502 (add-text-properties (match-beginning 3) (match-end 3)
4503 '(invisible org-link)))))
4504 (backward-char 1))
4505 rtn))
4507 (defun org-emphasize (&optional char)
4508 "Insert or change an emphasis, i.e. a font like bold or italic.
4509 If there is an active region, change that region to a new emphasis.
4510 If there is no region, just insert the marker characters and position
4511 the cursor between them.
4512 CHAR should be either the marker character, or the first character of the
4513 HTML tag associated with that emphasis. If CHAR is a space, the means
4514 to remove the emphasis of the selected region.
4515 If char is not given (for example in an interactive call) it
4516 will be prompted for."
4517 (interactive)
4518 (let ((eal org-emphasis-alist) e det
4519 (erc org-emphasis-regexp-components)
4520 (prompt "")
4521 (string "") beg end move tag c s)
4522 (if (org-region-active-p)
4523 (setq beg (region-beginning) end (region-end)
4524 string (buffer-substring beg end))
4525 (setq move t))
4527 (while (setq e (pop eal))
4528 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4529 c (aref tag 0))
4530 (push (cons c (string-to-char (car e))) det)
4531 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4532 (substring tag 1)))))
4533 (setq det (nreverse det))
4534 (unless char
4535 (message "%s" (concat "Emphasis marker or tag:" prompt))
4536 (setq char (read-char-exclusive)))
4537 (setq char (or (cdr (assoc char det)) char))
4538 (if (equal char ?\ )
4539 (setq s "" move nil)
4540 (unless (assoc (char-to-string char) org-emphasis-alist)
4541 (error "No such emphasis marker: \"%c\"" char))
4542 (setq s (char-to-string char)))
4543 (while (and (> (length string) 1)
4544 (equal (substring string 0 1) (substring string -1))
4545 (assoc (substring string 0 1) org-emphasis-alist))
4546 (setq string (substring string 1 -1)))
4547 (setq string (concat s string s))
4548 (if beg (delete-region beg end))
4549 (unless (or (bolp)
4550 (string-match (concat "[" (nth 0 erc) "\n]")
4551 (char-to-string (char-before (point)))))
4552 (insert " "))
4553 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4554 (char-to-string (char-after (point))))
4555 (insert " ") (backward-char 1))
4556 (insert string)
4557 (and move (backward-char 1))))
4559 (defconst org-nonsticky-props
4560 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4562 (defsubst org-rear-nonsticky-at (pos)
4563 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4565 (defun org-activate-plain-links (limit)
4566 "Run through the buffer and add overlays to links."
4567 (catch 'exit
4568 (let (f)
4569 (if (re-search-forward org-plain-link-re limit t)
4570 (progn
4571 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4572 (setq f (get-text-property (match-beginning 0) 'face))
4573 (if (or (eq f 'org-tag)
4574 (and (listp f) (memq 'org-tag f)))
4576 (add-text-properties (match-beginning 0) (match-end 0)
4577 (list 'mouse-face 'highlight
4578 'face 'org-link
4579 'keymap org-mouse-map))
4580 (org-rear-nonsticky-at (match-end 0)))
4581 t)))))
4583 (defun org-activate-code (limit)
4584 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4585 (progn
4586 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4587 (remove-text-properties (match-beginning 0) (match-end 0)
4588 '(display t invisible t intangible t))
4589 t)))
4591 (defun org-fontify-meta-lines-and-blocks (limit)
4592 "Fontify #+ lines and blocks, in the correct ways."
4593 (let ((case-fold-search t))
4594 (if (re-search-forward
4595 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4596 limit t)
4597 (let ((beg (match-beginning 0))
4598 (beg1 (line-beginning-position 2))
4599 (dc1 (downcase (match-string 2)))
4600 (dc3 (downcase (match-string 3)))
4601 end end1 quoting block-type)
4602 (cond
4603 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4604 ;; a single line of backend-specific content
4605 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4606 (remove-text-properties (match-beginning 0) (match-end 0)
4607 '(display t invisible t intangible t))
4608 (add-text-properties (match-beginning 1) (match-end 3)
4609 '(font-lock-fontified t face org-meta-line))
4610 (add-text-properties (match-beginning 6) (match-end 6)
4611 '(font-lock-fontified t face org-block))
4613 ((and (match-end 4) (equal dc3 "begin"))
4614 ;; Truely a block
4615 (setq block-type (downcase (match-string 5))
4616 quoting (member block-type org-protecting-blocks))
4617 (when (re-search-forward
4618 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4619 nil t) ;; on purpose, we look further than LIMIT
4620 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4621 (when quoting
4622 (remove-text-properties beg end
4623 '(display t invisible t intangible t)))
4624 (add-text-properties
4625 beg end
4626 '(font-lock-fontified t font-lock-multiline t))
4627 (add-text-properties beg beg1 '(face org-meta-line))
4628 (add-text-properties end1 end '(face org-meta-line))
4629 (cond
4630 (quoting
4631 (add-text-properties beg1 end1 '(face org-block)))
4632 ((string= block-type "quote")
4633 (add-text-properties beg1 end1 '(face org-quote)))
4634 ((string= block-type "verse")
4635 (add-text-properties beg1 end1 '(face org-verse))))
4637 ((not (member (char-after beg) '(?\ ?\t)))
4638 ;; just any other in-buffer setting, but not indented
4639 (add-text-properties
4640 beg (match-end 0)
4641 '(font-lock-fontified t face org-meta-line))
4643 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4644 "orgtbl:" "tblfm:" "tblname:"))
4645 (and (match-end 4) (equal dc3 "attr")))
4646 (add-text-properties
4647 beg (match-end 0)
4648 '(font-lock-fontified t face org-meta-line))
4650 ((member dc3 '(" " ""))
4651 (add-text-properties
4652 beg (match-end 0)
4653 '(font-lock-fontified t face font-lock-comment-face)))
4654 (t nil))))))
4656 (defun org-activate-angle-links (limit)
4657 "Run through the buffer and add overlays to links."
4658 (if (re-search-forward org-angle-link-re limit t)
4659 (progn
4660 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4661 (add-text-properties (match-beginning 0) (match-end 0)
4662 (list 'mouse-face 'highlight
4663 'keymap org-mouse-map))
4664 (org-rear-nonsticky-at (match-end 0))
4665 t)))
4667 (defun org-activate-footnote-links (limit)
4668 "Run through the buffer and add overlays to links."
4669 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4670 limit t)
4671 (progn
4672 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4673 (add-text-properties (match-beginning 2) (match-end 2)
4674 (list 'mouse-face 'highlight
4675 'keymap org-mouse-map
4676 'help-echo
4677 (if (= (point-at-bol) (match-beginning 2))
4678 "Footnote definition"
4679 "Footnote reference")
4681 (org-rear-nonsticky-at (match-end 2))
4682 t)))
4684 (defun org-activate-bracket-links (limit)
4685 "Run through the buffer and add overlays to bracketed links."
4686 (if (re-search-forward org-bracket-link-regexp limit t)
4687 (let* ((help (concat "LINK: "
4688 (org-match-string-no-properties 1)))
4689 ;; FIXME: above we should remove the escapes.
4690 ;; but that requires another match, protecting match data,
4691 ;; a lot of overhead for font-lock.
4692 (ip (org-maybe-intangible
4693 (list 'invisible 'org-link
4694 'keymap org-mouse-map 'mouse-face 'highlight
4695 'font-lock-multiline t 'help-echo help)))
4696 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4697 'font-lock-multiline t 'help-echo help)))
4698 ;; We need to remove the invisible property here. Table narrowing
4699 ;; may have made some of this invisible.
4700 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4701 (remove-text-properties (match-beginning 0) (match-end 0)
4702 '(invisible nil))
4703 (if (match-end 3)
4704 (progn
4705 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4706 (org-rear-nonsticky-at (match-beginning 3))
4707 (add-text-properties (match-beginning 3) (match-end 3) vp)
4708 (org-rear-nonsticky-at (match-end 3))
4709 (add-text-properties (match-end 3) (match-end 0) ip)
4710 (org-rear-nonsticky-at (match-end 0)))
4711 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4712 (org-rear-nonsticky-at (match-beginning 1))
4713 (add-text-properties (match-beginning 1) (match-end 1) vp)
4714 (org-rear-nonsticky-at (match-end 1))
4715 (add-text-properties (match-end 1) (match-end 0) ip)
4716 (org-rear-nonsticky-at (match-end 0)))
4717 t)))
4719 (defun org-activate-dates (limit)
4720 "Run through the buffer and add overlays to dates."
4721 (if (re-search-forward org-tsr-regexp-both limit t)
4722 (progn
4723 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4724 (add-text-properties (match-beginning 0) (match-end 0)
4725 (list 'mouse-face 'highlight
4726 'keymap org-mouse-map))
4727 (org-rear-nonsticky-at (match-end 0))
4728 (when org-display-custom-times
4729 (if (match-end 3)
4730 (org-display-custom-time (match-beginning 3) (match-end 3)))
4731 (org-display-custom-time (match-beginning 1) (match-end 1)))
4732 t)))
4734 (defvar org-target-link-regexp nil
4735 "Regular expression matching radio targets in plain text.")
4736 (make-variable-buffer-local 'org-target-link-regexp)
4737 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4738 "Regular expression matching a link target.")
4739 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4740 "Regular expression matching a radio target.")
4741 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4742 "Regular expression matching any target.")
4744 (defun org-activate-target-links (limit)
4745 "Run through the buffer and add overlays to target matches."
4746 (when org-target-link-regexp
4747 (let ((case-fold-search t))
4748 (if (re-search-forward org-target-link-regexp limit t)
4749 (progn
4750 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4751 (add-text-properties (match-beginning 0) (match-end 0)
4752 (list 'mouse-face 'highlight
4753 'keymap org-mouse-map
4754 'help-echo "Radio target link"
4755 'org-linked-text t))
4756 (org-rear-nonsticky-at (match-end 0))
4757 t)))))
4759 (defun org-update-radio-target-regexp ()
4760 "Find all radio targets in this file and update the regular expression."
4761 (interactive)
4762 (when (memq 'radio org-activate-links)
4763 (setq org-target-link-regexp
4764 (org-make-target-link-regexp (org-all-targets 'radio)))
4765 (org-restart-font-lock)))
4767 (defun org-hide-wide-columns (limit)
4768 (let (s e)
4769 (setq s (text-property-any (point) (or limit (point-max))
4770 'org-cwidth t))
4771 (when s
4772 (setq e (next-single-property-change s 'org-cwidth))
4773 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4774 (goto-char e)
4775 t)))
4777 (defvar org-latex-and-specials-regexp nil
4778 "Regular expression for highlighting export special stuff.")
4779 (defvar org-match-substring-regexp)
4780 (defvar org-match-substring-with-braces-regexp)
4782 ;; This should be with the exporter code, but we also use if for font-locking
4783 (defconst org-export-html-special-string-regexps
4784 '(("\\\\-" . "&shy;")
4785 ("---\\([^-]\\)" . "&mdash;\\1")
4786 ("--\\([^-]\\)" . "&ndash;\\1")
4787 ("\\.\\.\\." . "&hellip;"))
4788 "Regular expressions for special string conversion.")
4791 (defun org-compute-latex-and-specials-regexp ()
4792 "Compute regular expression for stuff treated specially by exporters."
4793 (if (not org-highlight-latex-fragments-and-specials)
4794 (org-set-local 'org-latex-and-specials-regexp nil)
4795 (require 'org-exp)
4796 (let*
4797 ((matchers (plist-get org-format-latex-options :matchers))
4798 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4799 org-latex-regexps)))
4800 (org-export-allow-BIND nil)
4801 (options (org-combine-plists (org-default-export-plist)
4802 (org-infile-export-plist)))
4803 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4804 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4805 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4806 (org-export-html-expand (plist-get options :expand-quoted-html))
4807 (org-export-with-special-strings (plist-get options :special-strings))
4808 (re-sub
4809 (cond
4810 ((equal org-export-with-sub-superscripts '{})
4811 (list org-match-substring-with-braces-regexp))
4812 (org-export-with-sub-superscripts
4813 (list org-match-substring-regexp))
4814 (t nil)))
4815 (re-latex
4816 (if org-export-with-LaTeX-fragments
4817 (mapcar (lambda (x) (nth 1 x)) latexs)))
4818 (re-macros
4819 (if org-export-with-TeX-macros
4820 (list (concat "\\\\"
4821 (regexp-opt
4822 (append (mapcar 'car org-html-entities)
4823 (if (boundp 'org-latex-entities)
4824 (mapcar (lambda (x)
4825 (or (car-safe x) x))
4826 org-latex-entities)
4827 nil))
4828 'words))) ; FIXME
4830 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4831 (re-special (if org-export-with-special-strings
4832 (mapcar (lambda (x) (car x))
4833 org-export-html-special-string-regexps)))
4834 (re-rest
4835 (delq nil
4836 (list
4837 (if org-export-html-expand "@<[^>\n]+>")
4838 ))))
4839 (org-set-local
4840 'org-latex-and-specials-regexp
4841 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4842 re-rest) "\\|")))))
4844 (defun org-do-latex-and-special-faces (limit)
4845 "Run through the buffer and add overlays to links."
4846 (when org-latex-and-specials-regexp
4847 (let (rtn d)
4848 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4849 limit t))
4850 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4851 'face))
4852 '(org-code org-verbatim underline)))
4853 (progn
4854 (setq rtn t
4855 d (cond ((member (char-after (1+ (match-beginning 0)))
4856 '(?_ ?^)) 1)
4857 (t 0)))
4858 (font-lock-prepend-text-property
4859 (+ d (match-beginning 0)) (match-end 0)
4860 'face 'org-latex-and-export-specials)
4861 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4862 '(font-lock-multiline t)))))
4863 rtn)))
4865 (defun org-restart-font-lock ()
4866 "Restart font-lock-mode, to force refontification."
4867 (when (and (boundp 'font-lock-mode) font-lock-mode)
4868 (font-lock-mode -1)
4869 (font-lock-mode 1)))
4871 (defun org-all-targets (&optional radio)
4872 "Return a list of all targets in this file.
4873 With optional argument RADIO, only find radio targets."
4874 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4875 rtn)
4876 (save-excursion
4877 (goto-char (point-min))
4878 (while (re-search-forward re nil t)
4879 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4880 rtn)))
4882 (defun org-make-target-link-regexp (targets)
4883 "Make regular expression matching all strings in TARGETS.
4884 The regular expression finds the targets also if there is a line break
4885 between words."
4886 (and targets
4887 (concat
4888 "\\<\\("
4889 (mapconcat
4890 (lambda (x)
4891 (while (string-match " +" x)
4892 (setq x (replace-match "\\s-+" t t x)))
4894 targets
4895 "\\|")
4896 "\\)\\>")))
4898 (defun org-activate-tags (limit)
4899 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4900 (progn
4901 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
4902 (add-text-properties (match-beginning 1) (match-end 1)
4903 (list 'mouse-face 'highlight
4904 'keymap org-mouse-map))
4905 (org-rear-nonsticky-at (match-end 1))
4906 t)))
4908 (defun org-outline-level ()
4909 "Compute the outline level of the heading at point.
4910 This function assumes that the cursor is at the beginning of a line matched
4911 by outline-regexp. Otherwise it returns garbage.
4912 If this is called at a normal headline, the level is the number of stars.
4913 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4914 For plain list items, if they are matched by `outline-regexp', this returns
4915 1000 plus the line indentation."
4916 (save-excursion
4917 (looking-at outline-regexp)
4918 (if (match-beginning 1)
4919 (+ (org-get-string-indentation (match-string 1)) 1000)
4920 (1- (- (match-end 0) (match-beginning 0))))))
4922 (defvar org-font-lock-keywords nil)
4924 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4925 "Regular expression matching a property line.")
4927 (defvar org-font-lock-hook nil
4928 "Functions to be called for special font lock stuff.")
4930 (defun org-font-lock-hook (limit)
4931 (run-hook-with-args 'org-font-lock-hook limit))
4933 (defun org-set-font-lock-defaults ()
4934 (let* ((em org-fontify-emphasized-text)
4935 (lk org-activate-links)
4936 (org-font-lock-extra-keywords
4937 (list
4938 ;; Call the hook
4939 '(org-font-lock-hook)
4940 ;; Headlines
4941 `(,(if org-fontify-whole-heading-line
4942 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4943 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4944 (1 (org-get-level-face 1))
4945 (2 (org-get-level-face 2))
4946 (3 (org-get-level-face 3)))
4947 ;; Table lines
4948 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4949 (1 'org-table t))
4950 ;; Table internals
4951 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4952 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4953 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4954 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4955 ;; Drawers
4956 (list org-drawer-regexp '(0 'org-special-keyword t))
4957 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4958 ;; Properties
4959 (list org-property-re
4960 '(1 'org-special-keyword t)
4961 '(3 'org-property-value t))
4962 ;; Links
4963 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4964 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4965 (if (memq 'plain lk) '(org-activate-plain-links))
4966 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4967 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4968 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4969 (if (memq 'footnote lk) '(org-activate-footnote-links
4970 (2 'org-footnote t)))
4971 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4972 '(org-hide-wide-columns (0 nil append))
4973 ;; TODO lines
4974 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4975 '(1 (org-get-todo-face 1) t))
4976 ;; DONE
4977 (if org-fontify-done-headline
4978 (list (concat "^[*]+ +\\<\\("
4979 (mapconcat 'regexp-quote org-done-keywords "\\|")
4980 "\\)\\(.*\\)")
4981 '(2 'org-headline-done t))
4982 nil)
4983 ;; Priorities
4984 '(org-font-lock-add-priority-faces)
4985 ;; Tags
4986 '(org-font-lock-add-tag-faces)
4987 ;; Special keywords
4988 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4989 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4990 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4991 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4992 ;; Emphasis
4993 (if em
4994 (if (featurep 'xemacs)
4995 '(org-do-emphasis-faces (0 nil append))
4996 '(org-do-emphasis-faces)))
4997 ;; Checkboxes
4998 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4999 2 'org-checkbox prepend)
5000 (if org-provide-checkbox-statistics
5001 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5002 (0 (org-get-checkbox-statistics-face) t)))
5003 ;; Description list items
5004 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5005 2 'bold prepend)
5006 ;; ARCHIVEd headings
5007 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5008 '(1 'org-archived prepend))
5009 ;; Specials
5010 '(org-do-latex-and-special-faces)
5011 ;; Code
5012 '(org-activate-code (1 'org-code t))
5013 ;; COMMENT
5014 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5015 "\\|" org-quote-string "\\)\\>")
5016 '(1 'org-special-keyword t))
5017 '("^#.*" (0 'font-lock-comment-face t))
5018 ;; Blocks and meta lines
5019 '(org-fontify-meta-lines-and-blocks)
5021 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5022 ;; Now set the full font-lock-keywords
5023 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5024 (org-set-local 'font-lock-defaults
5025 '(org-font-lock-keywords t nil nil backward-paragraph))
5026 (kill-local-variable 'font-lock-keywords) nil))
5028 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5029 "Fontify string S like in Org-mode"
5030 (with-temp-buffer
5031 (insert s)
5032 (let ((org-odd-levels-only odd-levels))
5033 (org-mode)
5034 (font-lock-fontify-buffer)
5035 (buffer-string))))
5037 (defvar org-m nil)
5038 (defvar org-l nil)
5039 (defvar org-f nil)
5040 (defun org-get-level-face (n)
5041 "Get the right face for match N in font-lock matching of headlines."
5042 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5043 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5044 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5045 (cond
5046 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5047 ((eq n 2) org-f)
5048 (t (if org-level-color-stars-only nil org-f))))
5050 (defun org-get-todo-face (kwd)
5051 "Get the right face for a TODO keyword KWD.
5052 If KWD is a number, get the corresponding match group."
5053 (if (numberp kwd) (setq kwd (match-string kwd)))
5054 (or (cdr (assoc kwd org-todo-keyword-faces))
5055 (and (member kwd org-done-keywords) 'org-done)
5056 'org-todo))
5058 (defun org-font-lock-add-tag-faces (limit)
5059 "Add the special tag faces."
5060 (when (and org-tag-faces org-tags-special-faces-re)
5061 (while (re-search-forward org-tags-special-faces-re limit t)
5062 (add-text-properties (match-beginning 1) (match-end 1)
5063 (list 'face (org-get-tag-face 1)
5064 'font-lock-fontified t))
5065 (backward-char 1))))
5067 (defun org-font-lock-add-priority-faces (limit)
5068 "Add the special priority faces."
5069 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5070 (add-text-properties
5071 (match-beginning 0) (match-end 0)
5072 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
5073 org-priority-faces))
5074 'org-special-keyword)
5075 'font-lock-fontified t))))
5077 (defun org-get-tag-face (kwd)
5078 "Get the right face for a TODO keyword KWD.
5079 If KWD is a number, get the corresponding match group."
5080 (if (numberp kwd) (setq kwd (match-string kwd)))
5081 (or (cdr (assoc kwd org-tag-faces))
5082 'org-tag))
5084 (defun org-unfontify-region (beg end &optional maybe_loudly)
5085 "Remove fontification and activation overlays from links."
5086 (font-lock-default-unfontify-region beg end)
5087 (let* ((buffer-undo-list t)
5088 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5089 (inhibit-modification-hooks t)
5090 deactivate-mark buffer-file-name buffer-file-truename)
5091 (remove-text-properties
5092 beg end
5093 (if org-indent-mode
5094 ;; also remove line-prefix and wrap-prefix properties
5095 '(mouse-face t keymap t org-linked-text t
5096 invisible t intangible t
5097 line-prefix t wrap-prefix t
5098 org-no-flyspell t)
5099 '(mouse-face t keymap t org-linked-text t
5100 invisible t intangible t
5101 org-no-flyspell t)))))
5103 ;;;; Visibility cycling, including org-goto and indirect buffer
5105 ;;; Cycling
5107 (defvar org-cycle-global-status nil)
5108 (make-variable-buffer-local 'org-cycle-global-status)
5109 (defvar org-cycle-subtree-status nil)
5110 (make-variable-buffer-local 'org-cycle-subtree-status)
5112 ;;;###autoload
5114 (defvar org-inlinetask-min-level)
5116 (defun org-cycle (&optional arg)
5117 "TAB-action and visibility cycling for Org-mode.
5119 This is the command invoked in Org-mode by the TAB key. Its main purpose
5120 is outline visibility cycling, but it also invokes other actions
5121 in special contexts.
5123 - When this function is called with a prefix argument, rotate the entire
5124 buffer through 3 states (global cycling)
5125 1. OVERVIEW: Show only top-level headlines.
5126 2. CONTENTS: Show all headlines of all levels, but no body text.
5127 3. SHOW ALL: Show everything.
5128 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5129 determined by the variable `org-startup-folded', and by any VISIBILITY
5130 properties in the buffer.
5131 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5132 including any drawers.
5134 - When inside a table, re-align the table and move to the next field.
5136 - When point is at the beginning of a headline, rotate the subtree started
5137 by this line through 3 different states (local cycling)
5138 1. FOLDED: Only the main headline is shown.
5139 2. CHILDREN: The main headline and the direct children are shown.
5140 From this state, you can move to one of the children
5141 and zoom in further.
5142 3. SUBTREE: Show the entire subtree, including body text.
5143 If there is no subtree, switch directly from CHILDREN to FOLDED.
5145 - When point is at the beginning of an empty headline and the variable
5146 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5147 of the headline by demoting and promoting it to likely levels. This
5148 speeds up creation document structure by presing TAB once or several
5149 times right after creating a new headline.
5151 - When there is a numeric prefix, go up to a heading with level ARG, do
5152 a `show-subtree' and return to the previous cursor position. If ARG
5153 is negative, go up that many levels.
5155 - When point is not at the beginning of a headline, execute the global
5156 binding for TAB, which is re-indenting the line. See the option
5157 `org-cycle-emulate-tab' for details.
5159 - Special case: if point is at the beginning of the buffer and there is
5160 no headline in line 1, this function will act as if called with prefix arg.
5161 But only if also the variable `org-cycle-global-at-bob' is t."
5162 (interactive "P")
5163 (org-load-modules-maybe)
5164 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5165 (and org-cycle-level-after-item/entry-creation
5166 (or (org-cycle-level)
5167 (org-cycle-item-indentation))))
5168 (let* ((limit-level
5169 (or org-cycle-max-level
5170 (and (boundp 'org-inlinetask-min-level)
5171 org-inlinetask-min-level
5172 (1- org-inlinetask-min-level))))
5173 (nstars (and limit-level
5174 (if org-odd-levels-only
5175 (and limit-level (1- (* limit-level 2)))
5176 limit-level)))
5177 (outline-regexp
5178 (cond
5179 ((not (org-mode-p)) outline-regexp)
5180 ((or (eq org-cycle-include-plain-lists 'integrate)
5181 (and org-cycle-include-plain-lists (org-at-item-p)))
5182 (concat "\\(?:\\*"
5183 (if nstars (format "\\{1,%d\\}" nstars) "+")
5184 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5185 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5186 (bob-special (and org-cycle-global-at-bob (bobp)
5187 (not (looking-at outline-regexp))))
5188 (org-cycle-hook
5189 (if bob-special
5190 (delq 'org-optimize-window-after-visibility-change
5191 (copy-sequence org-cycle-hook))
5192 org-cycle-hook))
5193 (pos (point)))
5195 (if (or bob-special (equal arg '(4)))
5196 ;; special case: use global cycling
5197 (setq arg t))
5199 (cond
5201 ((equal arg '(16))
5202 (org-set-startup-visibility)
5203 (message "Startup visibility, plus VISIBILITY properties"))
5205 ((equal arg '(64))
5206 (show-all)
5207 (message "Entire buffer visible, including drawers"))
5209 ((org-at-table-p 'any)
5210 ;; Enter the table or move to the next field in the table
5211 (or (org-table-recognize-table.el)
5212 (progn
5213 (if arg (org-table-edit-field t)
5214 (org-table-justify-field-maybe)
5215 (call-interactively 'org-table-next-field)))))
5217 ((run-hook-with-args-until-success
5218 'org-tab-after-check-for-table-hook))
5220 ((eq arg t) ;; Global cycling
5221 (org-cycle-internal-global))
5223 ((and org-drawers org-drawer-regexp
5224 (save-excursion
5225 (beginning-of-line 1)
5226 (looking-at org-drawer-regexp)))
5227 ;; Toggle block visibility
5228 (org-flag-drawer
5229 (not (get-char-property (match-end 0) 'invisible))))
5231 ((integerp arg)
5232 ;; Show-subtree, ARG levels up from here.
5233 (save-excursion
5234 (org-back-to-heading)
5235 (outline-up-heading (if (< arg 0) (- arg)
5236 (- (funcall outline-level) arg)))
5237 (org-show-subtree)))
5239 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5240 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5242 (org-cycle-internal-local))
5244 ;; TAB emulation and template completion
5245 (buffer-read-only (org-back-to-heading))
5247 ((run-hook-with-args-until-success
5248 'org-tab-after-check-for-cycling-hook))
5250 ((org-try-structure-completion))
5252 ((org-try-cdlatex-tab))
5254 ((run-hook-with-args-until-success
5255 'org-tab-before-tab-emulation-hook))
5257 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5258 (or (not (bolp))
5259 (not (looking-at outline-regexp))))
5260 (call-interactively (global-key-binding "\t")))
5262 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5263 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5264 (or (and (eq org-cycle-emulate-tab 'white)
5265 (= (match-end 0) (point-at-eol)))
5266 (and (eq org-cycle-emulate-tab 'whitestart)
5267 (>= (match-end 0) pos))))
5269 (eq org-cycle-emulate-tab t))
5270 (call-interactively (global-key-binding "\t")))
5272 (t (save-excursion
5273 (org-back-to-heading)
5274 (org-cycle)))))))
5276 (defun org-cycle-internal-global ()
5277 "Do the global cycling action."
5278 (cond
5279 ((and (eq last-command this-command)
5280 (eq org-cycle-global-status 'overview))
5281 ;; We just created the overview - now do table of contents
5282 ;; This can be slow in very large buffers, so indicate action
5283 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5284 (message "CONTENTS...")
5285 (org-content)
5286 (message "CONTENTS...done")
5287 (setq org-cycle-global-status 'contents)
5288 (run-hook-with-args 'org-cycle-hook 'contents))
5290 ((and (eq last-command this-command)
5291 (eq org-cycle-global-status 'contents))
5292 ;; We just showed the table of contents - now show everything
5293 (run-hook-with-args 'org-pre-cycle-hook 'all)
5294 (show-all)
5295 (message "SHOW ALL")
5296 (setq org-cycle-global-status 'all)
5297 (run-hook-with-args 'org-cycle-hook 'all))
5300 ;; Default action: go to overview
5301 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5302 (org-overview)
5303 (message "OVERVIEW")
5304 (setq org-cycle-global-status 'overview)
5305 (run-hook-with-args 'org-cycle-hook 'overview))))
5307 (defun org-cycle-internal-local ()
5308 "Do the local cycling action."
5309 (org-back-to-heading)
5310 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5311 ;; First, some boundaries
5312 (save-excursion
5313 (org-back-to-heading)
5314 (setq level (funcall outline-level))
5315 (save-excursion
5316 (beginning-of-line 2)
5317 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5318 ; XEmacs does not have `next-single-char-property-change'
5319 ; I'm not sure about Emacs 21.
5320 (while (and (not (eobp)) ;; this is like `next-line'
5321 (get-char-property (1- (point)) 'invisible))
5322 (beginning-of-line 2))
5323 (while (and (not (eobp)) ;; this is like `next-line'
5324 (get-char-property (1- (point)) 'invisible))
5325 (goto-char (next-single-char-property-change (point) 'invisible))
5326 ;;;??? (or (bolp) (beginning-of-line 2))))
5327 (and (eolp) (beginning-of-line 2))))
5328 (setq eol (point)))
5329 (outline-end-of-heading) (setq eoh (point))
5330 (save-excursion
5331 (outline-next-heading)
5332 (setq has-children (and (org-at-heading-p t)
5333 (> (funcall outline-level) level))))
5334 (org-end-of-subtree t)
5335 (unless (eobp)
5336 (skip-chars-forward " \t\n")
5337 (beginning-of-line 1) ; in case this is an item
5339 (setq eos (if (eobp) (point) (1- (point)))))
5340 ;; Find out what to do next and set `this-command'
5341 (cond
5342 ((= eos eoh)
5343 ;; Nothing is hidden behind this heading
5344 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5345 (message "EMPTY ENTRY")
5346 (setq org-cycle-subtree-status nil)
5347 (save-excursion
5348 (goto-char eos)
5349 (outline-next-heading)
5350 (if (org-invisible-p) (org-flag-heading nil))))
5351 ((and (or (>= eol eos)
5352 (not (string-match "\\S-" (buffer-substring eol eos))))
5353 (or has-children
5354 (not (setq children-skipped
5355 org-cycle-skip-children-state-if-no-children))))
5356 ;; Entire subtree is hidden in one line: children view
5357 (run-hook-with-args 'org-pre-cycle-hook 'children)
5358 (org-show-entry)
5359 (show-children)
5360 (message "CHILDREN")
5361 (save-excursion
5362 (goto-char eos)
5363 (outline-next-heading)
5364 (if (org-invisible-p) (org-flag-heading nil)))
5365 (setq org-cycle-subtree-status 'children)
5366 (run-hook-with-args 'org-cycle-hook 'children))
5367 ((or children-skipped
5368 (and (eq last-command this-command)
5369 (eq org-cycle-subtree-status 'children)))
5370 ;; We just showed the children, or no children are there,
5371 ;; now show everything.
5372 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5373 (org-show-subtree)
5374 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5375 (setq org-cycle-subtree-status 'subtree)
5376 (run-hook-with-args 'org-cycle-hook 'subtree))
5378 ;; Default action: hide the subtree.
5379 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5380 (hide-subtree)
5381 (message "FOLDED")
5382 (setq org-cycle-subtree-status 'folded)
5383 (run-hook-with-args 'org-cycle-hook 'folded)))))
5385 ;;;###autoload
5386 (defun org-global-cycle (&optional arg)
5387 "Cycle the global visibility. For details see `org-cycle'.
5388 With C-u prefix arg, switch to startup visibility.
5389 With a numeric prefix, show all headlines up to that level."
5390 (interactive "P")
5391 (let ((org-cycle-include-plain-lists
5392 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5393 (cond
5394 ((integerp arg)
5395 (show-all)
5396 (hide-sublevels arg)
5397 (setq org-cycle-global-status 'contents))
5398 ((equal arg '(4))
5399 (org-set-startup-visibility)
5400 (message "Startup visibility, plus VISIBILITY properties."))
5402 (org-cycle '(4))))))
5404 (defun org-set-startup-visibility ()
5405 "Set the visibility required by startup options and properties."
5406 (cond
5407 ((eq org-startup-folded t)
5408 (org-cycle '(4)))
5409 ((eq org-startup-folded 'content)
5410 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5411 (org-cycle '(4)) (org-cycle '(4)))))
5412 (unless (eq org-startup-folded 'showeverything)
5413 (if org-hide-block-startup (org-hide-block-all))
5414 (org-set-visibility-according-to-property 'no-cleanup)
5415 (org-cycle-hide-archived-subtrees 'all)
5416 (org-cycle-hide-drawers 'all)
5417 (org-cycle-show-empty-lines 'all)))
5419 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5420 "Switch subtree visibilities according to :VISIBILITY: property."
5421 (interactive)
5422 (let (org-show-entry-below state)
5423 (save-excursion
5424 (goto-char (point-min))
5425 (while (re-search-forward
5426 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5427 nil t)
5428 (setq state (match-string 1))
5429 (save-excursion
5430 (org-back-to-heading t)
5431 (hide-subtree)
5432 (org-reveal)
5433 (cond
5434 ((equal state '("fold" "folded"))
5435 (hide-subtree))
5436 ((equal state "children")
5437 (org-show-hidden-entry)
5438 (show-children))
5439 ((equal state "content")
5440 (save-excursion
5441 (save-restriction
5442 (org-narrow-to-subtree)
5443 (org-content))))
5444 ((member state '("all" "showall"))
5445 (show-subtree)))))
5446 (unless no-cleanup
5447 (org-cycle-hide-archived-subtrees 'all)
5448 (org-cycle-hide-drawers 'all)
5449 (org-cycle-show-empty-lines 'all)))))
5451 (defun org-overview ()
5452 "Switch to overview mode, showing only top-level headlines.
5453 Really, this shows all headlines with level equal or greater than the level
5454 of the first headline in the buffer. This is important, because if the
5455 first headline is not level one, then (hide-sublevels 1) gives confusing
5456 results."
5457 (interactive)
5458 (let ((level (save-excursion
5459 (goto-char (point-min))
5460 (if (re-search-forward (concat "^" outline-regexp) nil t)
5461 (progn
5462 (goto-char (match-beginning 0))
5463 (funcall outline-level))))))
5464 (and level (hide-sublevels level))))
5466 (defun org-content (&optional arg)
5467 "Show all headlines in the buffer, like a table of contents.
5468 With numerical argument N, show content up to level N."
5469 (interactive "P")
5470 (save-excursion
5471 ;; Visit all headings and show their offspring
5472 (and (integerp arg) (org-overview))
5473 (goto-char (point-max))
5474 (catch 'exit
5475 (while (and (progn (condition-case nil
5476 (outline-previous-visible-heading 1)
5477 (error (goto-char (point-min))))
5479 (looking-at outline-regexp))
5480 (if (integerp arg)
5481 (show-children (1- arg))
5482 (show-branches))
5483 (if (bobp) (throw 'exit nil))))))
5486 (defun org-optimize-window-after-visibility-change (state)
5487 "Adjust the window after a change in outline visibility.
5488 This function is the default value of the hook `org-cycle-hook'."
5489 (when (get-buffer-window (current-buffer))
5490 (cond
5491 ((eq state 'content) nil)
5492 ((eq state 'all) nil)
5493 ((eq state 'folded) nil)
5494 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5495 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5497 (defun org-remove-empty-overlays-at (pos)
5498 "Remove outline overlays that do not contain non-white stuff."
5499 (mapc
5500 (lambda (o)
5501 (and (eq 'outline (org-overlay-get o 'invisible))
5502 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5503 (org-overlay-end o))))
5504 (org-delete-overlay o)))
5505 (org-overlays-at pos)))
5507 (defun org-clean-visibility-after-subtree-move ()
5508 "Fix visibility issues after moving a subtree."
5509 ;; First, find a reasonable region to look at:
5510 ;; Start two siblings above, end three below
5511 (let* ((beg (save-excursion
5512 (and (org-get-last-sibling)
5513 (org-get-last-sibling))
5514 (point)))
5515 (end (save-excursion
5516 (and (org-get-next-sibling)
5517 (org-get-next-sibling)
5518 (org-get-next-sibling))
5519 (if (org-at-heading-p)
5520 (point-at-eol)
5521 (point))))
5522 (level (looking-at "\\*+"))
5523 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5524 (save-excursion
5525 (save-restriction
5526 (narrow-to-region beg end)
5527 (when re
5528 ;; Properly fold already folded siblings
5529 (goto-char (point-min))
5530 (while (re-search-forward re nil t)
5531 (if (and (not (org-invisible-p))
5532 (save-excursion
5533 (goto-char (point-at-eol)) (org-invisible-p)))
5534 (hide-entry))))
5535 (org-cycle-show-empty-lines 'overview)
5536 (org-cycle-hide-drawers 'overview)))))
5538 (defun org-cycle-show-empty-lines (state)
5539 "Show empty lines above all visible headlines.
5540 The region to be covered depends on STATE when called through
5541 `org-cycle-hook'. Lisp program can use t for STATE to get the
5542 entire buffer covered. Note that an empty line is only shown if there
5543 are at least `org-cycle-separator-lines' empty lines before the headline."
5544 (when (not (= org-cycle-separator-lines 0))
5545 (save-excursion
5546 (let* ((n (abs org-cycle-separator-lines))
5547 (re (cond
5548 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5549 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5550 (t (let ((ns (number-to-string (- n 2))))
5551 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5552 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5553 beg end b e)
5554 (cond
5555 ((memq state '(overview contents t))
5556 (setq beg (point-min) end (point-max)))
5557 ((memq state '(children folded))
5558 (setq beg (point) end (progn (org-end-of-subtree t t)
5559 (beginning-of-line 2)
5560 (point)))))
5561 (when beg
5562 (goto-char beg)
5563 (while (re-search-forward re end t)
5564 (unless (get-char-property (match-end 1) 'invisible)
5565 (setq e (match-end 1))
5566 (if (< org-cycle-separator-lines 0)
5567 (setq b (save-excursion
5568 (goto-char (match-beginning 0))
5569 (org-back-over-empty-lines)
5570 (if (save-excursion
5571 (goto-char (max (point-min) (1- (point))))
5572 (org-on-heading-p))
5573 (1- (point))
5574 (point))))
5575 (setq b (match-beginning 1)))
5576 (outline-flag-region b e nil)))))))
5577 ;; Never hide empty lines at the end of the file.
5578 (save-excursion
5579 (goto-char (point-max))
5580 (outline-previous-heading)
5581 (outline-end-of-heading)
5582 (if (and (looking-at "[ \t\n]+")
5583 (= (match-end 0) (point-max)))
5584 (outline-flag-region (point) (match-end 0) nil))))
5586 (defun org-show-empty-lines-in-parent ()
5587 "Move to the parent and re-show empty lines before visible headlines."
5588 (save-excursion
5589 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5590 (org-cycle-show-empty-lines context))))
5592 (defun org-files-list ()
5593 "Return `org-agenda-files' list, plus all open org-mode files.
5594 This is useful for operations that need to scan all of a user's
5595 open and agenda-wise Org files."
5596 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5597 (dolist (buf (buffer-list))
5598 (with-current-buffer buf
5599 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5600 (let ((file (expand-file-name (buffer-file-name))))
5601 (unless (member file files)
5602 (push file files))))))
5603 files))
5605 (defsubst org-entry-beginning-position ()
5606 "Return the beginning position of the current entry."
5607 (save-excursion (outline-back-to-heading t) (point)))
5609 (defsubst org-entry-end-position ()
5610 "Return the end position of the current entry."
5611 (save-excursion (outline-next-heading) (point)))
5613 (defun org-cycle-hide-drawers (state)
5614 "Re-hide all drawers after a visibility state change."
5615 (when (and (org-mode-p)
5616 (not (memq state '(overview folded contents))))
5617 (save-excursion
5618 (let* ((globalp (memq state '(contents all)))
5619 (beg (if globalp (point-min) (point)))
5620 (end (if globalp (point-max)
5621 (if (eq state 'children)
5622 (save-excursion (outline-next-heading) (point))
5623 (org-end-of-subtree t)))))
5624 (goto-char beg)
5625 (while (re-search-forward org-drawer-regexp end t)
5626 (org-flag-drawer t))))))
5628 (defun org-flag-drawer (flag)
5629 (save-excursion
5630 (beginning-of-line 1)
5631 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5632 (let ((b (match-end 0))
5633 (outline-regexp org-outline-regexp))
5634 (if (re-search-forward
5635 "^[ \t]*:END:"
5636 (save-excursion (outline-next-heading) (point)) t)
5637 (outline-flag-region b (point-at-eol) flag)
5638 (error ":END: line missing at position %s" b))))))
5640 (defun org-subtree-end-visible-p ()
5641 "Is the end of the current subtree visible?"
5642 (pos-visible-in-window-p
5643 (save-excursion (org-end-of-subtree t) (point))))
5645 (defun org-first-headline-recenter (&optional N)
5646 "Move cursor to the first headline and recenter the headline.
5647 Optional argument N means put the headline into the Nth line of the window."
5648 (goto-char (point-min))
5649 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5650 (beginning-of-line)
5651 (recenter (prefix-numeric-value N))))
5653 ;;; Saving and restoring visibility
5655 (defun org-outline-overlay-data (&optional use-markers)
5656 "Return a list of the locations of all outline overlays.
5657 The are overlays with the `invisible' property value `outline'.
5658 The return valus is a list of cons cells, with start and stop
5659 positions for each overlay.
5660 If USE-MARKERS is set, return the positions as markers."
5661 (let (beg end)
5662 (save-excursion
5663 (save-restriction
5664 (widen)
5665 (delq nil
5666 (mapcar (lambda (o)
5667 (when (eq (org-overlay-get o 'invisible) 'outline)
5668 (setq beg (org-overlay-start o)
5669 end (org-overlay-end o))
5670 (and beg end (> end beg)
5671 (if use-markers
5672 (cons (move-marker (make-marker) beg)
5673 (move-marker (make-marker) end))
5674 (cons beg end)))))
5675 (org-overlays-in (point-min) (point-max))))))))
5677 (defun org-set-outline-overlay-data (data)
5678 "Create visibility overlays for all positions in DATA.
5679 DATA should have been made by `org-outline-overlay-data'."
5680 (let (o)
5681 (save-excursion
5682 (save-restriction
5683 (widen)
5684 (show-all)
5685 (mapc (lambda (c)
5686 (setq o (org-make-overlay (car c) (cdr c)))
5687 (org-overlay-put o 'invisible 'outline))
5688 data)))))
5690 (defmacro org-save-outline-visibility (use-markers &rest body)
5691 "Save and restore outline visibility around BODY.
5692 If USE-MARKERS is non-nil, use markers for the positions.
5693 This means that the buffer may change while running BODY,
5694 but it also means that the buffer should stay alive
5695 during the operation, because otherwise all these markers will
5696 point nowhere."
5697 `(let ((data (org-outline-overlay-data ,use-markers)))
5698 (unwind-protect
5699 (progn
5700 ,@body
5701 (org-set-outline-overlay-data data))
5702 (when ,use-markers
5703 (mapc (lambda (c)
5704 (and (markerp (car c)) (move-marker (car c) nil))
5705 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
5706 data)))))
5709 ;;; Folding of blocks
5711 (defconst org-block-regexp
5713 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5714 "Regular expression for hiding blocks.")
5716 (defvar org-hide-block-overlays nil
5717 "Overlays hiding blocks.")
5718 (make-variable-buffer-local 'org-hide-block-overlays)
5720 (defun org-block-map (function &optional start end)
5721 "Call func at the head of all source blocks in the current
5722 buffer. Optional arguments START and END can be used to limit
5723 the range."
5724 (let ((start (or start (point-min)))
5725 (end (or end (point-max))))
5726 (save-excursion
5727 (goto-char start)
5728 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5729 (save-excursion
5730 (save-match-data
5731 (goto-char (match-beginning 0))
5732 (funcall function)))))))
5734 (defun org-hide-block-toggle-all ()
5735 "Toggle the visibility of all blocks in the current buffer."
5736 (org-block-map #'org-hide-block-toggle))
5738 (defun org-hide-block-all ()
5739 "Fold all blocks in the current buffer."
5740 (interactive)
5741 (org-show-block-all)
5742 (org-block-map #'org-hide-block-toggle-maybe))
5744 (defun org-show-block-all ()
5745 "Unfold all blocks in the current buffer."
5746 (mapc 'org-delete-overlay org-hide-block-overlays)
5747 (setq org-hide-block-overlays nil))
5749 (defun org-hide-block-toggle-maybe ()
5750 "Toggle visibility of block at point."
5751 (interactive)
5752 (let ((case-fold-search t))
5753 (if (save-excursion
5754 (beginning-of-line 1)
5755 (looking-at org-block-regexp))
5756 (progn (org-hide-block-toggle)
5757 t) ;; to signal that we took action
5758 nil))) ;; to signal that we did not
5760 (defun org-hide-block-toggle (&optional force)
5761 "Toggle the visibility of the current block."
5762 (interactive)
5763 (save-excursion
5764 (beginning-of-line)
5765 (if (re-search-forward org-block-regexp nil t)
5766 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5767 (end (match-end 0)) ;; end of entire body
5769 (if (memq t (mapcar (lambda (overlay)
5770 (eq (org-overlay-get overlay 'invisible)
5771 'org-hide-block))
5772 (org-overlays-at start)))
5773 (if (or (not force) (eq force 'off))
5774 (mapc (lambda (ov)
5775 (when (member ov org-hide-block-overlays)
5776 (setq org-hide-block-overlays
5777 (delq ov org-hide-block-overlays)))
5778 (when (eq (org-overlay-get ov 'invisible)
5779 'org-hide-block)
5780 (org-delete-overlay ov)))
5781 (org-overlays-at start)))
5782 (setq ov (org-make-overlay start end))
5783 (org-overlay-put ov 'invisible 'org-hide-block)
5784 ;; make the block accessible to isearch
5785 (org-overlay-put
5786 ov 'isearch-open-invisible
5787 (lambda (ov)
5788 (when (member ov org-hide-block-overlays)
5789 (setq org-hide-block-overlays
5790 (delq ov org-hide-block-overlays)))
5791 (when (eq (org-overlay-get ov 'invisible)
5792 'org-hide-block)
5793 (org-delete-overlay ov))))
5794 (push ov org-hide-block-overlays)))
5795 (error "Not looking at a source block"))))
5797 ;; org-tab-after-check-for-cycling-hook
5798 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5799 ;; Remove overlays when changing major mode
5800 (add-hook 'org-mode-hook
5801 (lambda () (org-add-hook 'change-major-mode-hook
5802 'org-show-block-all 'append 'local)))
5804 ;;; Org-goto
5806 (defvar org-goto-window-configuration nil)
5807 (defvar org-goto-marker nil)
5808 (defvar org-goto-map
5809 (let ((map (make-sparse-keymap)))
5810 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5811 (while (setq cmd (pop cmds))
5812 (substitute-key-definition cmd cmd map global-map)))
5813 (suppress-keymap map)
5814 (org-defkey map "\C-m" 'org-goto-ret)
5815 (org-defkey map [(return)] 'org-goto-ret)
5816 (org-defkey map [(left)] 'org-goto-left)
5817 (org-defkey map [(right)] 'org-goto-right)
5818 (org-defkey map [(control ?g)] 'org-goto-quit)
5819 (org-defkey map "\C-i" 'org-cycle)
5820 (org-defkey map [(tab)] 'org-cycle)
5821 (org-defkey map [(down)] 'outline-next-visible-heading)
5822 (org-defkey map [(up)] 'outline-previous-visible-heading)
5823 (if org-goto-auto-isearch
5824 (if (fboundp 'define-key-after)
5825 (define-key-after map [t] 'org-goto-local-auto-isearch)
5826 nil)
5827 (org-defkey map "q" 'org-goto-quit)
5828 (org-defkey map "n" 'outline-next-visible-heading)
5829 (org-defkey map "p" 'outline-previous-visible-heading)
5830 (org-defkey map "f" 'outline-forward-same-level)
5831 (org-defkey map "b" 'outline-backward-same-level)
5832 (org-defkey map "u" 'outline-up-heading))
5833 (org-defkey map "/" 'org-occur)
5834 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5835 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5836 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5837 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5838 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5839 map))
5841 (defconst org-goto-help
5842 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5843 RET=jump to location [Q]uit and return to previous location
5844 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5846 (defvar org-goto-start-pos) ; dynamically scoped parameter
5848 ;; FIXME: Docstring does not mention both interfaces
5849 (defun org-goto (&optional alternative-interface)
5850 "Look up a different location in the current file, keeping current visibility.
5852 When you want look-up or go to a different location in a document, the
5853 fastest way is often to fold the entire buffer and then dive into the tree.
5854 This method has the disadvantage, that the previous location will be folded,
5855 which may not be what you want.
5857 This command works around this by showing a copy of the current buffer
5858 in an indirect buffer, in overview mode. You can dive into the tree in
5859 that copy, use org-occur and incremental search to find a location.
5860 When pressing RET or `Q', the command returns to the original buffer in
5861 which the visibility is still unchanged. After RET is will also jump to
5862 the location selected in the indirect buffer and expose the
5863 the headline hierarchy above."
5864 (interactive "P")
5865 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5866 (org-refile-use-outline-path t)
5867 (org-refile-target-verify-function nil)
5868 (interface
5869 (if (not alternative-interface)
5870 org-goto-interface
5871 (if (eq org-goto-interface 'outline)
5872 'outline-path-completion
5873 'outline)))
5874 (org-goto-start-pos (point))
5875 (selected-point
5876 (if (eq interface 'outline)
5877 (car (org-get-location (current-buffer) org-goto-help))
5878 (nth 3 (org-refile-get-location "Goto: ")))))
5879 (if selected-point
5880 (progn
5881 (org-mark-ring-push org-goto-start-pos)
5882 (goto-char selected-point)
5883 (if (or (org-invisible-p) (org-invisible-p2))
5884 (org-show-context 'org-goto)))
5885 (message "Quit"))))
5887 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5888 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5889 (defvar org-goto-local-auto-isearch-map) ; defined below
5891 (defun org-get-location (buf help)
5892 "Let the user select a location in the Org-mode buffer BUF.
5893 This function uses a recursive edit. It returns the selected position
5894 or nil."
5895 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5896 (isearch-hide-immediately nil)
5897 (isearch-search-fun-function
5898 (lambda () 'org-goto-local-search-headings))
5899 (org-goto-selected-point org-goto-exit-command))
5900 (save-excursion
5901 (save-window-excursion
5902 (delete-other-windows)
5903 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5904 (switch-to-buffer
5905 (condition-case nil
5906 (make-indirect-buffer (current-buffer) "*org-goto*")
5907 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5908 (with-output-to-temp-buffer "*Help*"
5909 (princ help))
5910 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5911 (setq buffer-read-only nil)
5912 (let ((org-startup-truncated t)
5913 (org-startup-folded nil)
5914 (org-startup-align-all-tables nil))
5915 (org-mode)
5916 (org-overview))
5917 (setq buffer-read-only t)
5918 (if (and (boundp 'org-goto-start-pos)
5919 (integer-or-marker-p org-goto-start-pos))
5920 (let ((org-show-hierarchy-above t)
5921 (org-show-siblings t)
5922 (org-show-following-heading t))
5923 (goto-char org-goto-start-pos)
5924 (and (org-invisible-p) (org-show-context)))
5925 (goto-char (point-min)))
5926 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5927 (message "Select location and press RET")
5928 (use-local-map org-goto-map)
5929 (recursive-edit)
5931 (kill-buffer "*org-goto*")
5932 (cons org-goto-selected-point org-goto-exit-command)))
5934 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5935 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5936 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5937 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5939 (defun org-goto-local-search-headings (string bound noerror)
5940 "Search and make sure that any matches are in headlines."
5941 (catch 'return
5942 (while (if isearch-forward
5943 (search-forward string bound noerror)
5944 (search-backward string bound noerror))
5945 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5946 (and (member :headline context)
5947 (not (member :tags context))))
5948 (throw 'return (point))))))
5950 (defun org-goto-local-auto-isearch ()
5951 "Start isearch."
5952 (interactive)
5953 (goto-char (point-min))
5954 (let ((keys (this-command-keys)))
5955 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5956 (isearch-mode t)
5957 (isearch-process-search-char (string-to-char keys)))))
5959 (defun org-goto-ret (&optional arg)
5960 "Finish `org-goto' by going to the new location."
5961 (interactive "P")
5962 (setq org-goto-selected-point (point)
5963 org-goto-exit-command 'return)
5964 (throw 'exit nil))
5966 (defun org-goto-left ()
5967 "Finish `org-goto' by going to the new location."
5968 (interactive)
5969 (if (org-on-heading-p)
5970 (progn
5971 (beginning-of-line 1)
5972 (setq org-goto-selected-point (point)
5973 org-goto-exit-command 'left)
5974 (throw 'exit nil))
5975 (error "Not on a heading")))
5977 (defun org-goto-right ()
5978 "Finish `org-goto' by going to the new location."
5979 (interactive)
5980 (if (org-on-heading-p)
5981 (progn
5982 (setq org-goto-selected-point (point)
5983 org-goto-exit-command 'right)
5984 (throw 'exit nil))
5985 (error "Not on a heading")))
5987 (defun org-goto-quit ()
5988 "Finish `org-goto' without cursor motion."
5989 (interactive)
5990 (setq org-goto-selected-point nil)
5991 (setq org-goto-exit-command 'quit)
5992 (throw 'exit nil))
5994 ;;; Indirect buffer display of subtrees
5996 (defvar org-indirect-dedicated-frame nil
5997 "This is the frame being used for indirect tree display.")
5998 (defvar org-last-indirect-buffer nil)
6000 (defun org-tree-to-indirect-buffer (&optional arg)
6001 "Create indirect buffer and narrow it to current subtree.
6002 With numerical prefix ARG, go up to this level and then take that tree.
6003 If ARG is negative, go up that many levels.
6004 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6005 indirect buffer previously made with this command, to avoid proliferation of
6006 indirect buffers. However, when you call the command with a `C-u' prefix, or
6007 when `org-indirect-buffer-display' is `new-frame', the last buffer
6008 is kept so that you can work with several indirect buffers at the same time.
6009 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6010 requests that a new frame be made for the new buffer, so that the dedicated
6011 frame is not changed."
6012 (interactive "P")
6013 (let ((cbuf (current-buffer))
6014 (cwin (selected-window))
6015 (pos (point))
6016 beg end level heading ibuf)
6017 (save-excursion
6018 (org-back-to-heading t)
6019 (when (numberp arg)
6020 (setq level (org-outline-level))
6021 (if (< arg 0) (setq arg (+ level arg)))
6022 (while (> (setq level (org-outline-level)) arg)
6023 (outline-up-heading 1 t)))
6024 (setq beg (point)
6025 heading (org-get-heading))
6026 (org-end-of-subtree t t)
6027 (if (org-on-heading-p) (backward-char 1))
6028 (setq end (point)))
6029 (if (and (buffer-live-p org-last-indirect-buffer)
6030 (not (eq org-indirect-buffer-display 'new-frame))
6031 (not arg))
6032 (kill-buffer org-last-indirect-buffer))
6033 (setq ibuf (org-get-indirect-buffer cbuf)
6034 org-last-indirect-buffer ibuf)
6035 (cond
6036 ((or (eq org-indirect-buffer-display 'new-frame)
6037 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6038 (select-frame (make-frame))
6039 (delete-other-windows)
6040 (switch-to-buffer ibuf)
6041 (org-set-frame-title heading))
6042 ((eq org-indirect-buffer-display 'dedicated-frame)
6043 (raise-frame
6044 (select-frame (or (and org-indirect-dedicated-frame
6045 (frame-live-p org-indirect-dedicated-frame)
6046 org-indirect-dedicated-frame)
6047 (setq org-indirect-dedicated-frame (make-frame)))))
6048 (delete-other-windows)
6049 (switch-to-buffer ibuf)
6050 (org-set-frame-title (concat "Indirect: " heading)))
6051 ((eq org-indirect-buffer-display 'current-window)
6052 (switch-to-buffer ibuf))
6053 ((eq org-indirect-buffer-display 'other-window)
6054 (pop-to-buffer ibuf))
6055 (t (error "Invalid value")))
6056 (if (featurep 'xemacs)
6057 (save-excursion (org-mode) (turn-on-font-lock)))
6058 (narrow-to-region beg end)
6059 (show-all)
6060 (goto-char pos)
6061 (and (window-live-p cwin) (select-window cwin))))
6063 (defun org-get-indirect-buffer (&optional buffer)
6064 (setq buffer (or buffer (current-buffer)))
6065 (let ((n 1) (base (buffer-name buffer)) bname)
6066 (while (buffer-live-p
6067 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6068 (setq n (1+ n)))
6069 (condition-case nil
6070 (make-indirect-buffer buffer bname 'clone)
6071 (error (make-indirect-buffer buffer bname)))))
6073 (defun org-set-frame-title (title)
6074 "Set the title of the current frame to the string TITLE."
6075 ;; FIXME: how to name a single frame in XEmacs???
6076 (unless (featurep 'xemacs)
6077 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6079 ;;;; Structure editing
6081 ;;; Inserting headlines
6083 (defun org-previous-line-empty-p ()
6084 (save-excursion
6085 (and (not (bobp))
6086 (or (beginning-of-line 0) t)
6087 (save-match-data
6088 (looking-at "[ \t]*$")))))
6090 (defun org-insert-heading (&optional force-heading invisible-ok)
6091 "Insert a new heading or item with same depth at point.
6092 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6093 If point is at the beginning of a headline, insert a sibling before the
6094 current headline. If point is not at the beginning, do not split the line,
6095 but create the new headline after the current line.
6096 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6097 This is important for non-interactive uses of the command."
6098 (interactive "P")
6099 (if (or (= (buffer-size) 0)
6100 (and (not (save-excursion (and (ignore-errors (org-back-to-heading invisible-ok))
6101 (org-on-heading-p))))
6102 (not (org-in-item-p))))
6103 (insert "\n* ")
6104 (when (or force-heading (not (org-insert-item)))
6105 (let* ((empty-line-p nil)
6106 (head (save-excursion
6107 (condition-case nil
6108 (progn
6109 (org-back-to-heading invisible-ok)
6110 (setq empty-line-p (org-previous-line-empty-p))
6111 (match-string 0))
6112 (error "*"))))
6113 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6114 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6115 pos hide-previous previous-pos)
6116 (cond
6117 ((and (org-on-heading-p) (bolp)
6118 (or (bobp)
6119 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6120 ;; insert before the current line
6121 (open-line (if blank 2 1)))
6122 ((and (bolp)
6123 (not org-insert-heading-respect-content)
6124 (or (bobp)
6125 (save-excursion
6126 (backward-char 1) (not (org-invisible-p)))))
6127 ;; insert right here
6128 nil)
6130 ;; somewhere in the line
6131 (save-excursion
6132 (setq previous-pos (point-at-bol))
6133 (end-of-line)
6134 (setq hide-previous (org-invisible-p)))
6135 (and org-insert-heading-respect-content (org-show-subtree))
6136 (let ((split
6137 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6138 (save-excursion
6139 (let ((p (point)))
6140 (goto-char (point-at-bol))
6141 (and (looking-at org-complex-heading-regexp)
6142 (> p (match-beginning 4)))))))
6143 tags pos)
6144 (cond
6145 (org-insert-heading-respect-content
6146 (org-end-of-subtree nil t)
6147 (or (bolp) (newline))
6148 (or (org-previous-line-empty-p)
6149 (and blank (newline)))
6150 (open-line 1))
6151 ((org-on-heading-p)
6152 (when hide-previous
6153 (show-children)
6154 (org-show-entry))
6155 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6156 (setq tags (and (match-end 2) (match-string 2)))
6157 (and (match-end 1)
6158 (delete-region (match-beginning 1) (match-end 1)))
6159 (setq pos (point-at-bol))
6160 (or split (end-of-line 1))
6161 (delete-horizontal-space)
6162 (newline (if blank 2 1))
6163 (when tags
6164 (save-excursion
6165 (goto-char pos)
6166 (end-of-line 1)
6167 (insert " " tags)
6168 (org-set-tags nil 'align))))
6170 (or split (end-of-line 1))
6171 (newline (if blank 2 1)))))))
6172 (insert head) (just-one-space)
6173 (setq pos (point))
6174 (end-of-line 1)
6175 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6176 (when (and org-insert-heading-respect-content hide-previous)
6177 (save-excursion
6178 (goto-char previous-pos)
6179 (hide-subtree)))
6180 (run-hooks 'org-insert-heading-hook)))))
6182 (defun org-get-heading (&optional no-tags)
6183 "Return the heading of the current entry, without the stars."
6184 (save-excursion
6185 (org-back-to-heading t)
6186 (if (looking-at
6187 (if no-tags
6188 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6189 "\\*+[ \t]+\\([^\r\n]*\\)"))
6190 (match-string 1) "")))
6192 (defun org-heading-components ()
6193 "Return the components of the current heading.
6194 This is a list with the following elements:
6195 - the level as an integer
6196 - the reduced level, different if `org-odd-levels-only' is set.
6197 - the TODO keyword, or nil
6198 - the priority character, like ?A, or nil if no priority is given
6199 - the headline text itself, or the tags string if no headline text
6200 - the tags string, or nil."
6201 (save-excursion
6202 (org-back-to-heading t)
6203 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6204 (list (length (match-string 1))
6205 (org-reduced-level (length (match-string 1)))
6206 (org-match-string-no-properties 2)
6207 (and (match-end 3) (aref (match-string 3) 2))
6208 (org-match-string-no-properties 4)
6209 (org-match-string-no-properties 5)))))
6211 (defun org-get-entry ()
6212 "Get the entry text, after heading, entire subtree."
6213 (save-excursion
6214 (org-back-to-heading t)
6215 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6217 (defun org-insert-heading-after-current ()
6218 "Insert a new heading with same level as current, after current subtree."
6219 (interactive)
6220 (org-back-to-heading)
6221 (org-insert-heading)
6222 (org-move-subtree-down)
6223 (end-of-line 1))
6225 (defun org-insert-heading-respect-content ()
6226 (interactive)
6227 (let ((org-insert-heading-respect-content t))
6228 (org-insert-heading t)))
6230 (defun org-insert-todo-heading-respect-content (&optional force-state)
6231 (interactive "P")
6232 (let ((org-insert-heading-respect-content t))
6233 (org-insert-todo-heading force-state t)))
6235 (defun org-insert-todo-heading (arg &optional force-heading)
6236 "Insert a new heading with the same level and TODO state as current heading.
6237 If the heading has no TODO state, or if the state is DONE, use the first
6238 state (TODO by default). Also with prefix arg, force first state."
6239 (interactive "P")
6240 (when (or force-heading (not (org-insert-item 'checkbox)))
6241 (org-insert-heading force-heading)
6242 (save-excursion
6243 (org-back-to-heading)
6244 (outline-previous-heading)
6245 (looking-at org-todo-line-regexp))
6246 (let*
6247 ((new-mark-x
6248 (if (or arg
6249 (not (match-beginning 2))
6250 (member (match-string 2) org-done-keywords))
6251 (car org-todo-keywords-1)
6252 (match-string 2)))
6253 (new-mark
6255 (run-hook-with-args-until-success
6256 'org-todo-get-default-hook new-mark-x nil)
6257 new-mark-x)))
6258 (beginning-of-line 1)
6259 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6260 (if org-treat-insert-todo-heading-as-state-change
6261 (org-todo new-mark)
6262 (insert new-mark " "))))
6263 (when org-provide-todo-statistics
6264 (org-update-parent-todo-statistics))))
6266 (defun org-insert-subheading (arg)
6267 "Insert a new subheading and demote it.
6268 Works for outline headings and for plain lists alike."
6269 (interactive "P")
6270 (org-insert-heading arg)
6271 (cond
6272 ((org-on-heading-p) (org-do-demote))
6273 ((org-at-item-p) (org-indent-item 1))))
6275 (defun org-insert-todo-subheading (arg)
6276 "Insert a new subheading with TODO keyword or checkbox and demote it.
6277 Works for outline headings and for plain lists alike."
6278 (interactive "P")
6279 (org-insert-todo-heading arg)
6280 (cond
6281 ((org-on-heading-p) (org-do-demote))
6282 ((org-at-item-p) (org-indent-item 1))))
6284 ;;; Promotion and Demotion
6286 (defvar org-after-demote-entry-hook nil
6287 "Hook run after an entry has been demoted.
6288 The cursor will be at the beginning of the entry.
6289 When a subtree is being demoted, the hook will be called for each node.")
6291 (defvar org-after-promote-entry-hook nil
6292 "Hook run after an entry has been promoted.
6293 The cursor will be at the beginning of the entry.
6294 When a subtree is being promoted, the hook will be called for each node.")
6296 (defun org-promote-subtree ()
6297 "Promote the entire subtree.
6298 See also `org-promote'."
6299 (interactive)
6300 (save-excursion
6301 (org-map-tree 'org-promote))
6302 (org-fix-position-after-promote))
6304 (defun org-demote-subtree ()
6305 "Demote the entire subtree. See `org-demote'.
6306 See also `org-promote'."
6307 (interactive)
6308 (save-excursion
6309 (org-map-tree 'org-demote))
6310 (org-fix-position-after-promote))
6313 (defun org-do-promote ()
6314 "Promote the current heading higher up the tree.
6315 If the region is active in `transient-mark-mode', promote all headings
6316 in the region."
6317 (interactive)
6318 (save-excursion
6319 (if (org-region-active-p)
6320 (org-map-region 'org-promote (region-beginning) (region-end))
6321 (org-promote)))
6322 (org-fix-position-after-promote))
6324 (defun org-do-demote ()
6325 "Demote the current heading lower down the tree.
6326 If the region is active in `transient-mark-mode', demote all headings
6327 in the region."
6328 (interactive)
6329 (save-excursion
6330 (if (org-region-active-p)
6331 (org-map-region 'org-demote (region-beginning) (region-end))
6332 (org-demote)))
6333 (org-fix-position-after-promote))
6335 (defun org-fix-position-after-promote ()
6336 "Make sure that after pro/demotion cursor position is right."
6337 (let ((pos (point)))
6338 (when (save-excursion
6339 (beginning-of-line 1)
6340 (looking-at org-todo-line-regexp)
6341 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6342 (cond ((eobp) (insert " "))
6343 ((eolp) (insert " "))
6344 ((equal (char-after) ?\ ) (forward-char 1))))))
6346 (defun org-current-level ()
6347 "Return the level of the current entry, or nil if before the first headline.
6348 The level is the number of stars at the beginning of the headline."
6349 (save-excursion
6350 (condition-case nil
6351 (progn
6352 (org-back-to-heading t)
6353 (funcall outline-level))
6354 (error nil))))
6356 (defun org-reduced-level (l)
6357 "Compute the effective level of a heading.
6358 This takes into account the setting of `org-odd-levels-only'."
6359 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6361 (defun org-get-valid-level (level &optional change)
6362 "Rectify a level change under the influence of `org-odd-levels-only'
6363 LEVEL is a current level, CHANGE is by how much the level should be
6364 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6365 even level numbers will become the next higher odd number."
6366 (if org-odd-levels-only
6367 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6368 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6369 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6370 (max 1 (+ level (or change 0)))))
6372 (if (boundp 'define-obsolete-function-alias)
6373 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6374 (define-obsolete-function-alias 'org-get-legal-level
6375 'org-get-valid-level)
6376 (define-obsolete-function-alias 'org-get-legal-level
6377 'org-get-valid-level "23.1")))
6379 (defun org-promote ()
6380 "Promote the current heading higher up the tree.
6381 If the region is active in `transient-mark-mode', promote all headings
6382 in the region."
6383 (org-back-to-heading t)
6384 (let* ((level (save-match-data (funcall outline-level)))
6385 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6386 (diff (abs (- level (length up-head) -1))))
6387 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6388 (replace-match up-head nil t)
6389 ;; Fixup tag positioning
6390 (and org-auto-align-tags (org-set-tags nil t))
6391 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6392 (run-hooks 'org-after-promote-entry-hook)))
6394 (defun org-demote ()
6395 "Demote the current heading lower down the tree.
6396 If the region is active in `transient-mark-mode', demote all headings
6397 in the region."
6398 (org-back-to-heading t)
6399 (let* ((level (save-match-data (funcall outline-level)))
6400 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6401 (diff (abs (- level (length down-head) -1))))
6402 (replace-match down-head nil t)
6403 ;; Fixup tag positioning
6404 (and org-auto-align-tags (org-set-tags nil t))
6405 (if org-adapt-indentation (org-fixup-indentation diff))
6406 (run-hooks 'org-after-demote-entry-hook)))
6408 (defvar org-tab-ind-state nil)
6410 (defun org-cycle-level ()
6411 (let ((org-adapt-indentation nil))
6412 (when (and (looking-at "[ \t]*$")
6413 (org-looking-back
6414 (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))
6415 (setq this-command 'org-cycle-level)
6416 (if (eq last-command 'org-cycle-level)
6417 (condition-case nil
6418 (progn (org-do-promote)
6419 (if (equal org-tab-ind-state (org-current-level))
6420 (org-do-promote)))
6421 (error
6422 (progn
6423 (save-excursion
6424 (beginning-of-line 1)
6425 (and (looking-at "\\*+")
6426 (replace-match
6427 (make-string org-tab-ind-state ?*))))
6428 (setq this-command 'org-cycle))))
6429 (setq org-tab-ind-state (- (match-end 1) (match-beginning 1)))
6430 (org-do-demote))
6431 t)))
6433 (defun org-map-tree (fun)
6434 "Call FUN for every heading underneath the current one."
6435 (org-back-to-heading)
6436 (let ((level (funcall outline-level)))
6437 (save-excursion
6438 (funcall fun)
6439 (while (and (progn
6440 (outline-next-heading)
6441 (> (funcall outline-level) level))
6442 (not (eobp)))
6443 (funcall fun)))))
6445 (defun org-map-region (fun beg end)
6446 "Call FUN for every heading between BEG and END."
6447 (let ((org-ignore-region t))
6448 (save-excursion
6449 (setq end (copy-marker end))
6450 (goto-char beg)
6451 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6452 (< (point) end))
6453 (funcall fun))
6454 (while (and (progn
6455 (outline-next-heading)
6456 (< (point) end))
6457 (not (eobp)))
6458 (funcall fun)))))
6460 (defun org-fixup-indentation (diff)
6461 "Change the indentation in the current entry by DIFF
6462 However, if any line in the current entry has no indentation, or if it
6463 would end up with no indentation after the change, nothing at all is done."
6464 (save-excursion
6465 (let ((end (save-excursion (outline-next-heading)
6466 (point-marker)))
6467 (prohibit (if (> diff 0)
6468 "^\\S-"
6469 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6470 col)
6471 (unless (save-excursion (end-of-line 1)
6472 (re-search-forward prohibit end t))
6473 (while (and (< (point) end)
6474 (re-search-forward "^[ \t]+" end t))
6475 (goto-char (match-end 0))
6476 (setq col (current-column))
6477 (if (< diff 0) (replace-match ""))
6478 (org-indent-to-column (+ diff col))))
6479 (move-marker end nil))))
6481 (defun org-convert-to-odd-levels ()
6482 "Convert an org-mode file with all levels allowed to one with odd levels.
6483 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6484 level 5 etc."
6485 (interactive)
6486 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6487 (let ((outline-regexp org-outline-regexp)
6488 (outline-level 'org-outline-level)
6489 (org-odd-levels-only nil) n)
6490 (save-excursion
6491 (goto-char (point-min))
6492 (while (re-search-forward "^\\*\\*+ " nil t)
6493 (setq n (- (length (match-string 0)) 2))
6494 (while (>= (setq n (1- n)) 0)
6495 (org-demote))
6496 (end-of-line 1))))))
6498 (defun org-convert-to-oddeven-levels ()
6499 "Convert an org-mode file with only odd levels to one with odd and even levels.
6500 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6501 section with an even level, conversion would destroy the structure of the file. An error
6502 is signaled in this case."
6503 (interactive)
6504 (goto-char (point-min))
6505 ;; First check if there are no even levels
6506 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6507 (org-show-context t)
6508 (error "Not all levels are odd in this file. Conversion not possible"))
6509 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6510 (let ((outline-regexp org-outline-regexp)
6511 (outline-level 'org-outline-level)
6512 (org-odd-levels-only nil) n)
6513 (save-excursion
6514 (goto-char (point-min))
6515 (while (re-search-forward "^\\*\\*+ " nil t)
6516 (setq n (/ (1- (length (match-string 0))) 2))
6517 (while (>= (setq n (1- n)) 0)
6518 (org-promote))
6519 (end-of-line 1))))))
6521 (defun org-tr-level (n)
6522 "Make N odd if required."
6523 (if org-odd-levels-only (1+ (/ n 2)) n))
6525 ;;; Vertical tree motion, cutting and pasting of subtrees
6527 (defun org-move-subtree-up (&optional arg)
6528 "Move the current subtree up past ARG headlines of the same level."
6529 (interactive "p")
6530 (org-move-subtree-down (- (prefix-numeric-value arg))))
6532 (defun org-move-subtree-down (&optional arg)
6533 "Move the current subtree down past ARG headlines of the same level."
6534 (interactive "p")
6535 (setq arg (prefix-numeric-value arg))
6536 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6537 'org-get-last-sibling))
6538 (ins-point (make-marker))
6539 (cnt (abs arg))
6540 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6541 ;; Select the tree
6542 (org-back-to-heading)
6543 (setq beg0 (point))
6544 (save-excursion
6545 (setq ne-beg (org-back-over-empty-lines))
6546 (setq beg (point)))
6547 (save-match-data
6548 (save-excursion (outline-end-of-heading)
6549 (setq folded (org-invisible-p)))
6550 (outline-end-of-subtree))
6551 (outline-next-heading)
6552 (setq ne-end (org-back-over-empty-lines))
6553 (setq end (point))
6554 (goto-char beg0)
6555 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6556 ;; include less whitespace
6557 (save-excursion
6558 (goto-char beg)
6559 (forward-line (- ne-beg ne-end))
6560 (setq beg (point))))
6561 ;; Find insertion point, with error handling
6562 (while (> cnt 0)
6563 (or (and (funcall movfunc) (looking-at outline-regexp))
6564 (progn (goto-char beg0)
6565 (error "Cannot move past superior level or buffer limit")))
6566 (setq cnt (1- cnt)))
6567 (if (> arg 0)
6568 ;; Moving forward - still need to move over subtree
6569 (progn (org-end-of-subtree t t)
6570 (save-excursion
6571 (org-back-over-empty-lines)
6572 (or (bolp) (newline)))))
6573 (setq ne-ins (org-back-over-empty-lines))
6574 (move-marker ins-point (point))
6575 (setq txt (buffer-substring beg end))
6576 (org-save-markers-in-region beg end)
6577 (delete-region beg end)
6578 (org-remove-empty-overlays-at beg)
6579 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6580 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6581 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6582 (let ((bbb (point)))
6583 (insert-before-markers txt)
6584 (org-reinstall-markers-in-region bbb)
6585 (move-marker ins-point bbb))
6586 (or (bolp) (insert "\n"))
6587 (setq ins-end (point))
6588 (goto-char ins-point)
6589 (org-skip-whitespace)
6590 (when (and (< arg 0)
6591 (org-first-sibling-p)
6592 (> ne-ins ne-beg))
6593 ;; Move whitespace back to beginning
6594 (save-excursion
6595 (goto-char ins-end)
6596 (let ((kill-whole-line t))
6597 (kill-line (- ne-ins ne-beg)) (point)))
6598 (insert (make-string (- ne-ins ne-beg) ?\n)))
6599 (move-marker ins-point nil)
6600 (if folded
6601 (hide-subtree)
6602 (org-show-entry)
6603 (show-children)
6604 (org-cycle-hide-drawers 'children))
6605 (org-clean-visibility-after-subtree-move)))
6607 (defvar org-subtree-clip ""
6608 "Clipboard for cut and paste of subtrees.
6609 This is actually only a copy of the kill, because we use the normal kill
6610 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6612 (defvar org-subtree-clip-folded nil
6613 "Was the last copied subtree folded?
6614 This is used to fold the tree back after pasting.")
6616 (defun org-cut-subtree (&optional n)
6617 "Cut the current subtree into the clipboard.
6618 With prefix arg N, cut this many sequential subtrees.
6619 This is a short-hand for marking the subtree and then cutting it."
6620 (interactive "p")
6621 (org-copy-subtree n 'cut))
6623 (defun org-copy-subtree (&optional n cut force-store-markers)
6624 "Cut the current subtree into the clipboard.
6625 With prefix arg N, cut this many sequential subtrees.
6626 This is a short-hand for marking the subtree and then copying it.
6627 If CUT is non-nil, actually cut the subtree.
6628 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6629 of some markers in the region, even if CUT is non-nil. This is
6630 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6631 (interactive "p")
6632 (let (beg end folded (beg0 (point)))
6633 (if (interactive-p)
6634 (org-back-to-heading nil) ; take what looks like a subtree
6635 (org-back-to-heading t)) ; take what is really there
6636 (org-back-over-empty-lines)
6637 (setq beg (point))
6638 (skip-chars-forward " \t\r\n")
6639 (save-match-data
6640 (save-excursion (outline-end-of-heading)
6641 (setq folded (org-invisible-p)))
6642 (condition-case nil
6643 (org-forward-same-level (1- n) t)
6644 (error nil))
6645 (org-end-of-subtree t t))
6646 (org-back-over-empty-lines)
6647 (setq end (point))
6648 (goto-char beg0)
6649 (when (> end beg)
6650 (setq org-subtree-clip-folded folded)
6651 (when (or cut force-store-markers)
6652 (org-save-markers-in-region beg end))
6653 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6654 (setq org-subtree-clip (current-kill 0))
6655 (message "%s: Subtree(s) with %d characters"
6656 (if cut "Cut" "Copied")
6657 (length org-subtree-clip)))))
6659 (defun org-paste-subtree (&optional level tree for-yank)
6660 "Paste the clipboard as a subtree, with modification of headline level.
6661 The entire subtree is promoted or demoted in order to match a new headline
6662 level.
6664 If the cursor is at the beginning of a headline, the same level as
6665 that headline is used to paste the tree
6667 If not, the new level is derived from the *visible* headings
6668 before and after the insertion point, and taken to be the inferior headline
6669 level of the two. So if the previous visible heading is level 3 and the
6670 next is level 4 (or vice versa), level 4 will be used for insertion.
6671 This makes sure that the subtree remains an independent subtree and does
6672 not swallow low level entries.
6674 You can also force a different level, either by using a numeric prefix
6675 argument, or by inserting the heading marker by hand. For example, if the
6676 cursor is after \"*****\", then the tree will be shifted to level 5.
6678 If optional TREE is given, use this text instead of the kill ring.
6680 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6681 move back over whitespace before inserting, and move point to the end of
6682 the inserted text when done."
6683 (interactive "P")
6684 (setq tree (or tree (and kill-ring (current-kill 0))))
6685 (unless (org-kill-is-subtree-p tree)
6686 (error "%s"
6687 (substitute-command-keys
6688 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6689 (let* ((visp (not (org-invisible-p)))
6690 (txt tree)
6691 (^re (concat "^\\(" outline-regexp "\\)"))
6692 (re (concat "\\(" outline-regexp "\\)"))
6693 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6695 (old-level (if (string-match ^re txt)
6696 (- (match-end 0) (match-beginning 0) 1)
6697 -1))
6698 (force-level (cond (level (prefix-numeric-value level))
6699 ((and (looking-at "[ \t]*$")
6700 (string-match
6701 ^re_ (buffer-substring
6702 (point-at-bol) (point))))
6703 (- (match-end 1) (match-beginning 1)))
6704 ((and (bolp)
6705 (looking-at org-outline-regexp))
6706 (- (match-end 0) (point) 1))
6707 (t nil)))
6708 (previous-level (save-excursion
6709 (condition-case nil
6710 (progn
6711 (outline-previous-visible-heading 1)
6712 (if (looking-at re)
6713 (- (match-end 0) (match-beginning 0) 1)
6715 (error 1))))
6716 (next-level (save-excursion
6717 (condition-case nil
6718 (progn
6719 (or (looking-at outline-regexp)
6720 (outline-next-visible-heading 1))
6721 (if (looking-at re)
6722 (- (match-end 0) (match-beginning 0) 1)
6724 (error 1))))
6725 (new-level (or force-level (max previous-level next-level)))
6726 (shift (if (or (= old-level -1)
6727 (= new-level -1)
6728 (= old-level new-level))
6730 (- new-level old-level)))
6731 (delta (if (> shift 0) -1 1))
6732 (func (if (> shift 0) 'org-demote 'org-promote))
6733 (org-odd-levels-only nil)
6734 beg end newend)
6735 ;; Remove the forced level indicator
6736 (if force-level
6737 (delete-region (point-at-bol) (point)))
6738 ;; Paste
6739 (beginning-of-line 1)
6740 (unless for-yank (org-back-over-empty-lines))
6741 (setq beg (point))
6742 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6743 (insert-before-markers txt)
6744 (unless (string-match "\n\\'" txt) (insert "\n"))
6745 (setq newend (point))
6746 (org-reinstall-markers-in-region beg)
6747 (setq end (point))
6748 (goto-char beg)
6749 (skip-chars-forward " \t\n\r")
6750 (setq beg (point))
6751 (if (and (org-invisible-p) visp)
6752 (save-excursion (outline-show-heading)))
6753 ;; Shift if necessary
6754 (unless (= shift 0)
6755 (save-restriction
6756 (narrow-to-region beg end)
6757 (while (not (= shift 0))
6758 (org-map-region func (point-min) (point-max))
6759 (setq shift (+ delta shift)))
6760 (goto-char (point-min))
6761 (setq newend (point-max))))
6762 (when (or (interactive-p) for-yank)
6763 (message "Clipboard pasted as level %d subtree" new-level))
6764 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6765 kill-ring
6766 (eq org-subtree-clip (current-kill 0))
6767 org-subtree-clip-folded)
6768 ;; The tree was folded before it was killed/copied
6769 (hide-subtree))
6770 (and for-yank (goto-char newend))))
6772 (defun org-kill-is-subtree-p (&optional txt)
6773 "Check if the current kill is an outline subtree, or a set of trees.
6774 Returns nil if kill does not start with a headline, or if the first
6775 headline level is not the largest headline level in the tree.
6776 So this will actually accept several entries of equal levels as well,
6777 which is OK for `org-paste-subtree'.
6778 If optional TXT is given, check this string instead of the current kill."
6779 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6780 (start-level (and kill
6781 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6782 org-outline-regexp "\\)")
6783 kill)
6784 (- (match-end 2) (match-beginning 2) 1)))
6785 (re (concat "^" org-outline-regexp))
6786 (start (1+ (or (match-beginning 2) -1))))
6787 (if (not start-level)
6788 (progn
6789 nil) ;; does not even start with a heading
6790 (catch 'exit
6791 (while (setq start (string-match re kill (1+ start)))
6792 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6793 (throw 'exit nil)))
6794 t))))
6796 (defvar org-markers-to-move nil
6797 "Markers that should be moved with a cut-and-paste operation.
6798 Those markers are stored together with their positions relative to
6799 the start of the region.")
6801 (defun org-save-markers-in-region (beg end)
6802 "Check markers in region.
6803 If these markers are between BEG and END, record their position relative
6804 to BEG, so that after moving the block of text, we can put the markers back
6805 into place.
6806 This function gets called just before an entry or tree gets cut from the
6807 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6808 called immediately, to move the markers with the entries."
6809 (setq org-markers-to-move nil)
6810 (when (featurep 'org-clock)
6811 (org-clock-save-markers-for-cut-and-paste beg end))
6812 (when (featurep 'org-agenda)
6813 (org-agenda-save-markers-for-cut-and-paste beg end)))
6815 (defun org-check-and-save-marker (marker beg end)
6816 "Check if MARKER is between BEG and END.
6817 If yes, remember the marker and the distance to BEG."
6818 (when (and (marker-buffer marker)
6819 (equal (marker-buffer marker) (current-buffer)))
6820 (if (and (>= marker beg) (< marker end))
6821 (push (cons marker (- marker beg)) org-markers-to-move))))
6823 (defun org-reinstall-markers-in-region (beg)
6824 "Move all remembered markers to their position relative to BEG."
6825 (mapc (lambda (x)
6826 (move-marker (car x) (+ beg (cdr x))))
6827 org-markers-to-move)
6828 (setq org-markers-to-move nil))
6830 (defun org-narrow-to-subtree ()
6831 "Narrow buffer to the current subtree."
6832 (interactive)
6833 (save-excursion
6834 (save-match-data
6835 (narrow-to-region
6836 (progn (org-back-to-heading t) (point))
6837 (progn (org-end-of-subtree t t)
6838 (if (org-on-heading-p) (backward-char 1))
6839 (point))))))
6841 (defun org-clone-subtree-with-time-shift (n &optional shift)
6842 "Clone the task (subtree) at point N times.
6843 The clones will be inserted as siblings.
6845 In interactive use, the user will be prompted for the number of clones
6846 to be produced, and for a time SHIFT, which may be a repeater as used
6847 in time stamps, for example `+3d'.
6849 When a valid repeater is given and the entry contains any time stamps,
6850 the clones will become a sequence in time, with time stamps in the
6851 subtree shifted for each clone produced. If SHIFT is nil or the
6852 empty string, time stamps will be left alone.
6854 If the original subtree did contain time stamps with a repeater,
6855 the following will happen:
6856 - the repeater will be removed in each clone
6857 - an additional clone will be produced, with the current, unshifted
6858 date(s) in the entry.
6859 - the original entry will be placed *after* all the clones, with
6860 repeater intact.
6861 - the start days in the repeater in the original entry will be shifted
6862 to past the last clone.
6863 I this way you can spell out a number of instances of a repeating task,
6864 and still retain the repeater to cover future instances of the task."
6865 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6866 (let (beg end template task
6867 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6868 (if (not (and (integerp n) (> n 0)))
6869 (error "Invalid number of replications %s" n))
6870 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6871 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6872 shift)))
6873 (error "Invalid shift specification %s" shift))
6874 (when doshift
6875 (setq shift-n (string-to-number (match-string 1 shift))
6876 shift-what (cdr (assoc (match-string 2 shift)
6877 '(("d" . day) ("w" . week)
6878 ("m" . month) ("y" . year))))))
6879 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6880 (setq nmin 1 nmax n)
6881 (org-back-to-heading t)
6882 (setq beg (point))
6883 (org-end-of-subtree t t)
6884 (or (bolp) (insert "\n"))
6885 (setq end (point))
6886 (setq template (buffer-substring beg end))
6887 (when (and doshift
6888 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6889 (delete-region beg end)
6890 (setq end beg)
6891 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6892 (goto-char end)
6893 (loop for n from nmin to nmax do
6894 (if (not doshift)
6895 (setq task template)
6896 (with-temp-buffer
6897 (insert template)
6898 (org-mode)
6899 (goto-char (point-min))
6900 (while (re-search-forward org-ts-regexp-both nil t)
6901 (org-timestamp-change (* n shift-n) shift-what))
6902 (unless (= n n-no-remove)
6903 (goto-char (point-min))
6904 (while (re-search-forward org-ts-regexp nil t)
6905 (save-excursion
6906 (goto-char (match-beginning 0))
6907 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6908 (delete-region (match-beginning 1) (match-end 1))))))
6909 (setq task (buffer-string))))
6910 (insert task))
6911 (goto-char beg)))
6913 ;;; Outline Sorting
6915 (defun org-sort (with-case)
6916 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6917 Optional argument WITH-CASE means sort case-sensitively.
6918 With a double prefix argument, also remove duplicate entries."
6919 (interactive "P")
6920 (if (org-at-table-p)
6921 (org-call-with-arg 'org-table-sort-lines with-case)
6922 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6924 (defun org-sort-remove-invisible (s)
6925 (remove-text-properties 0 (length s) org-rm-props s)
6926 (while (string-match org-bracket-link-regexp s)
6927 (setq s (replace-match (if (match-end 2)
6928 (match-string 3 s)
6929 (match-string 1 s)) t t s)))
6932 (defvar org-priority-regexp) ; defined later in the file
6934 (defvar org-after-sorting-entries-or-items-hook nil
6935 "Hook that is run after a bunch of entries or items have been sorted.
6936 When children are sorted, the cursor is in the parent line when this
6937 hook gets called. When a region or a plain list is sorted, the cursor
6938 will be in the first entry of the sorted region/list.")
6940 (defun org-sort-entries-or-items
6941 (&optional with-case sorting-type getkey-func compare-func property)
6942 "Sort entries on a certain level of an outline tree, or plain list items.
6943 If there is an active region, the entries in the region are sorted.
6944 Else, if the cursor is before the first entry, sort the top-level items.
6945 Else, the children of the entry at point are sorted.
6946 If the cursor is at the first item in a plain list, the list items will be
6947 sorted.
6949 Sorting can be alphabetically, numerically, by date/time as given by
6950 a time stamp, by a property or by priority.
6952 The command prompts for the sorting type unless it has been given to the
6953 function through the SORTING-TYPE argument, which needs to a character,
6954 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6955 precise meaning of each character:
6957 n Numerically, by converting the beginning of the entry/item to a number.
6958 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6959 t By date/time, either the first active time stamp in the entry, or, if
6960 none exist, by the first inactive one.
6961 In items, only the first line will be checked.
6962 s By the scheduled date/time.
6963 d By deadline date/time.
6964 c By creation time, which is assumed to be the first inactive time stamp
6965 at the beginning of a line.
6966 p By priority according to the cookie.
6967 r By the value of a property.
6969 Capital letters will reverse the sort order.
6971 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6972 called with point at the beginning of the record. It must return either
6973 a string or a number that should serve as the sorting key for that record.
6975 Comparing entries ignores case by default. However, with an optional argument
6976 WITH-CASE, the sorting considers case as well."
6977 (interactive "P")
6978 (let ((case-func (if with-case 'identity 'downcase))
6979 start beg end stars re re2
6980 txt what tmp plain-list-p)
6981 ;; Find beginning and end of region to sort
6982 (cond
6983 ((org-region-active-p)
6984 ;; we will sort the region
6985 (setq end (region-end)
6986 what "region")
6987 (goto-char (region-beginning))
6988 (if (not (org-on-heading-p)) (outline-next-heading))
6989 (setq start (point)))
6990 ((org-at-item-p)
6991 ;; we will sort this plain list
6992 (org-beginning-of-item-list) (setq start (point))
6993 (org-end-of-item-list)
6994 (or (bolp) (insert "\n"))
6995 (setq end (point))
6996 (goto-char start)
6997 (setq plain-list-p t
6998 what "plain list"))
6999 ((or (org-on-heading-p)
7000 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7001 ;; we will sort the children of the current headline
7002 (org-back-to-heading)
7003 (setq start (point)
7004 end (progn (org-end-of-subtree t t)
7005 (or (bolp) (insert "\n"))
7006 (org-back-over-empty-lines)
7007 (point))
7008 what "children")
7009 (goto-char start)
7010 (show-subtree)
7011 (outline-next-heading))
7013 ;; we will sort the top-level entries in this file
7014 (goto-char (point-min))
7015 (or (org-on-heading-p) (outline-next-heading))
7016 (setq start (point))
7017 (goto-char (point-max))
7018 (beginning-of-line 1)
7019 (when (looking-at ".*?\\S-")
7020 ;; File ends in a non-white line
7021 (end-of-line 1)
7022 (insert "\n"))
7023 (setq end (point-max))
7024 (setq what "top-level")
7025 (goto-char start)
7026 (show-all)))
7028 (setq beg (point))
7029 (if (>= beg end) (error "Nothing to sort"))
7031 (unless plain-list-p
7032 (looking-at "\\(\\*+\\)")
7033 (setq stars (match-string 1)
7034 re (concat "^" (regexp-quote stars) " +")
7035 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7036 txt (buffer-substring beg end))
7037 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7038 (if (and (not (equal stars "*")) (string-match re2 txt))
7039 (error "Region to sort contains a level above the first entry")))
7041 (unless sorting-type
7042 (message
7043 (if plain-list-p
7044 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7045 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7046 [t]ime [s]cheduled [d]eadline [c]reated
7047 A/N/T/S/D/C/P/O/F means reversed:")
7048 what)
7049 (setq sorting-type (read-char-exclusive))
7051 (and (= (downcase sorting-type) ?f)
7052 (setq getkey-func
7053 (org-icompleting-read "Sort using function: "
7054 obarray 'fboundp t nil nil))
7055 (setq getkey-func (intern getkey-func)))
7057 (and (= (downcase sorting-type) ?r)
7058 (setq property
7059 (org-icompleting-read "Property: "
7060 (mapcar 'list (org-buffer-property-keys t))
7061 nil t))))
7063 (message "Sorting entries...")
7065 (save-restriction
7066 (narrow-to-region start end)
7068 (let ((dcst (downcase sorting-type))
7069 (case-fold-search nil)
7070 (now (current-time)))
7071 (sort-subr
7072 (/= dcst sorting-type)
7073 ;; This function moves to the beginning character of the "record" to
7074 ;; be sorted.
7075 (if plain-list-p
7076 (lambda nil
7077 (if (org-at-item-p) t (goto-char (point-max))))
7078 (lambda nil
7079 (if (re-search-forward re nil t)
7080 (goto-char (match-beginning 0))
7081 (goto-char (point-max)))))
7082 ;; This function moves to the last character of the "record" being
7083 ;; sorted.
7084 (if plain-list-p
7085 'org-end-of-item
7086 (lambda nil
7087 (save-match-data
7088 (condition-case nil
7089 (outline-forward-same-level 1)
7090 (error
7091 (goto-char (point-max)))))))
7093 ;; This function returns the value that gets sorted against.
7094 (if plain-list-p
7095 (lambda nil
7096 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7097 (cond
7098 ((= dcst ?n)
7099 (string-to-number (buffer-substring (match-end 0)
7100 (point-at-eol))))
7101 ((= dcst ?a)
7102 (buffer-substring (match-end 0) (point-at-eol)))
7103 ((= dcst ?t)
7104 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7105 (re-search-forward org-ts-regexp-both
7106 (point-at-eol) t))
7107 (org-time-string-to-seconds (match-string 0))
7108 (org-float-time now)))
7109 ((= dcst ?f)
7110 (if getkey-func
7111 (progn
7112 (setq tmp (funcall getkey-func))
7113 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7114 tmp)
7115 (error "Invalid key function `%s'" getkey-func)))
7116 (t (error "Invalid sorting type `%c'" sorting-type)))))
7117 (lambda nil
7118 (cond
7119 ((= dcst ?n)
7120 (if (looking-at org-complex-heading-regexp)
7121 (string-to-number (match-string 4))
7122 nil))
7123 ((= dcst ?a)
7124 (if (looking-at org-complex-heading-regexp)
7125 (funcall case-func (match-string 4))
7126 nil))
7127 ((= dcst ?t)
7128 (let ((end (save-excursion (outline-next-heading) (point))))
7129 (if (or (re-search-forward org-ts-regexp end t)
7130 (re-search-forward org-ts-regexp-both end t))
7131 (org-time-string-to-seconds (match-string 0))
7132 (org-float-time now))))
7133 ((= dcst ?c)
7134 (let ((end (save-excursion (outline-next-heading) (point))))
7135 (if (re-search-forward
7136 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7137 end t)
7138 (org-time-string-to-seconds (match-string 0))
7139 (org-float-time now))))
7140 ((= dcst ?s)
7141 (let ((end (save-excursion (outline-next-heading) (point))))
7142 (if (re-search-forward org-scheduled-time-regexp end t)
7143 (org-time-string-to-seconds (match-string 1))
7144 (org-float-time now))))
7145 ((= dcst ?d)
7146 (let ((end (save-excursion (outline-next-heading) (point))))
7147 (if (re-search-forward org-deadline-time-regexp end t)
7148 (org-time-string-to-seconds (match-string 1))
7149 (org-float-time now))))
7150 ((= dcst ?p)
7151 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7152 (string-to-char (match-string 2))
7153 org-default-priority))
7154 ((= dcst ?r)
7155 (or (org-entry-get nil property) ""))
7156 ((= dcst ?o)
7157 (if (looking-at org-complex-heading-regexp)
7158 (- 9999 (length (member (match-string 2)
7159 org-todo-keywords-1)))))
7160 ((= dcst ?f)
7161 (if getkey-func
7162 (progn
7163 (setq tmp (funcall getkey-func))
7164 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7165 tmp)
7166 (error "Invalid key function `%s'" getkey-func)))
7167 (t (error "Invalid sorting type `%c'" sorting-type)))))
7169 (cond
7170 ((= dcst ?a) 'string<)
7171 ((= dcst ?f) compare-func)
7172 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7173 (t nil)))))
7174 (run-hooks 'org-after-sorting-entries-or-items-hook)
7175 (message "Sorting entries...done")))
7177 (defun org-do-sort (table what &optional with-case sorting-type)
7178 "Sort TABLE of WHAT according to SORTING-TYPE.
7179 The user will be prompted for the SORTING-TYPE if the call to this
7180 function does not specify it. WHAT is only for the prompt, to indicate
7181 what is being sorted. The sorting key will be extracted from
7182 the car of the elements of the table.
7183 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7184 (unless sorting-type
7185 (message
7186 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7187 what)
7188 (setq sorting-type (read-char-exclusive)))
7189 (let ((dcst (downcase sorting-type))
7190 extractfun comparefun)
7191 ;; Define the appropriate functions
7192 (cond
7193 ((= dcst ?n)
7194 (setq extractfun 'string-to-number
7195 comparefun (if (= dcst sorting-type) '< '>)))
7196 ((= dcst ?a)
7197 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7198 (lambda(x) (downcase (org-sort-remove-invisible x))))
7199 comparefun (if (= dcst sorting-type)
7200 'string<
7201 (lambda (a b) (and (not (string< a b))
7202 (not (string= a b)))))))
7203 ((= dcst ?t)
7204 (setq extractfun
7205 (lambda (x)
7206 (if (or (string-match org-ts-regexp x)
7207 (string-match org-ts-regexp-both x))
7208 (org-float-time
7209 (org-time-string-to-time (match-string 0 x)))
7211 comparefun (if (= dcst sorting-type) '< '>)))
7212 (t (error "Invalid sorting type `%c'" sorting-type)))
7214 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7215 table)
7216 (lambda (a b) (funcall comparefun (car a) (car b))))))
7219 ;;; The orgstruct minor mode
7221 ;; Define a minor mode which can be used in other modes in order to
7222 ;; integrate the org-mode structure editing commands.
7224 ;; This is really a hack, because the org-mode structure commands use
7225 ;; keys which normally belong to the major mode. Here is how it
7226 ;; works: The minor mode defines all the keys necessary to operate the
7227 ;; structure commands, but wraps the commands into a function which
7228 ;; tests if the cursor is currently at a headline or a plain list
7229 ;; item. If that is the case, the structure command is used,
7230 ;; temporarily setting many Org-mode variables like regular
7231 ;; expressions for filling etc. However, when any of those keys is
7232 ;; used at a different location, function uses `key-binding' to look
7233 ;; up if the key has an associated command in another currently active
7234 ;; keymap (minor modes, major mode, global), and executes that
7235 ;; command. There might be problems if any of the keys is otherwise
7236 ;; used as a prefix key.
7238 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7239 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7240 ;; addresses this by checking explicitly for both bindings.
7242 (defvar orgstruct-mode-map (make-sparse-keymap)
7243 "Keymap for the minor `orgstruct-mode'.")
7245 (defvar org-local-vars nil
7246 "List of local variables, for use by `orgstruct-mode'")
7248 ;;;###autoload
7249 (define-minor-mode orgstruct-mode
7250 "Toggle the minor more `orgstruct-mode'.
7251 This mode is for using Org-mode structure commands in other modes.
7252 The following key behave as if Org-mode was active, if the cursor
7253 is on a headline, or on a plain list item (both in the definition
7254 of Org-mode).
7256 M-up Move entry/item up
7257 M-down Move entry/item down
7258 M-left Promote
7259 M-right Demote
7260 M-S-up Move entry/item up
7261 M-S-down Move entry/item down
7262 M-S-left Promote subtree
7263 M-S-right Demote subtree
7264 M-q Fill paragraph and items like in Org-mode
7265 C-c ^ Sort entries
7266 C-c - Cycle list bullet
7267 TAB Cycle item visibility
7268 M-RET Insert new heading/item
7269 S-M-RET Insert new TODO heading / Checkbox item
7270 C-c C-c Set tags / toggle checkbox"
7271 nil " OrgStruct" nil
7272 (org-load-modules-maybe)
7273 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7275 ;;;###autoload
7276 (defun turn-on-orgstruct ()
7277 "Unconditionally turn on `orgstruct-mode'."
7278 (orgstruct-mode 1))
7280 (defun orgstruct++-mode (&optional arg)
7281 "Toggle `orgstruct-mode', the enhanced version of it.
7282 In addition to setting orgstruct-mode, this also exports all indentation
7283 and autofilling variables from org-mode into the buffer. It will also
7284 recognize item context in multiline items.
7285 Note that turning off orgstruct-mode will *not* remove the
7286 indentation/paragraph settings. This can only be done by refreshing the
7287 major mode, for example with \\[normal-mode]."
7288 (interactive "P")
7289 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7290 (if (< arg 1)
7291 (orgstruct-mode -1)
7292 (orgstruct-mode 1)
7293 (let (var val)
7294 (mapc
7295 (lambda (x)
7296 (when (string-match
7297 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7298 (symbol-name (car x)))
7299 (setq var (car x) val (nth 1 x))
7300 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7301 org-local-vars)
7302 (org-set-local 'orgstruct-is-++ t))))
7304 (defvar orgstruct-is-++ nil
7305 "Is orgstruct-mode in ++ version in the current-buffer?")
7306 (make-variable-buffer-local 'orgstruct-is-++)
7308 ;;;###autoload
7309 (defun turn-on-orgstruct++ ()
7310 "Unconditionally turn on `orgstruct++-mode'."
7311 (orgstruct++-mode 1))
7313 (defun orgstruct-error ()
7314 "Error when there is no default binding for a structure key."
7315 (interactive)
7316 (error "This key has no function outside structure elements"))
7318 (defun orgstruct-setup ()
7319 "Setup orgstruct keymaps."
7320 (let ((nfunc 0)
7321 (bindings
7322 (list
7323 '([(meta up)] org-metaup)
7324 '([(meta down)] org-metadown)
7325 '([(meta left)] org-metaleft)
7326 '([(meta right)] org-metaright)
7327 '([(meta shift up)] org-shiftmetaup)
7328 '([(meta shift down)] org-shiftmetadown)
7329 '([(meta shift left)] org-shiftmetaleft)
7330 '([(meta shift right)] org-shiftmetaright)
7331 '([?\e (up)] org-metaup)
7332 '([?\e (down)] org-metadown)
7333 '([?\e (left)] org-metaleft)
7334 '([?\e (right)] org-metaright)
7335 '([?\e (shift up)] org-shiftmetaup)
7336 '([?\e (shift down)] org-shiftmetadown)
7337 '([?\e (shift left)] org-shiftmetaleft)
7338 '([?\e (shift right)] org-shiftmetaright)
7339 '([(shift up)] org-shiftup)
7340 '([(shift down)] org-shiftdown)
7341 '([(shift left)] org-shiftleft)
7342 '([(shift right)] org-shiftright)
7343 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7344 '("\M-q" fill-paragraph)
7345 '("\C-c^" org-sort)
7346 '("\C-c-" org-cycle-list-bullet)))
7347 elt key fun cmd)
7348 (while (setq elt (pop bindings))
7349 (setq nfunc (1+ nfunc))
7350 (setq key (org-key (car elt))
7351 fun (nth 1 elt)
7352 cmd (orgstruct-make-binding fun nfunc key))
7353 (org-defkey orgstruct-mode-map key cmd))
7355 ;; Special treatment needed for TAB and RET
7356 (org-defkey orgstruct-mode-map [(tab)]
7357 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7358 (org-defkey orgstruct-mode-map "\C-i"
7359 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7361 (org-defkey orgstruct-mode-map "\M-\C-m"
7362 (orgstruct-make-binding 'org-insert-heading 105
7363 "\M-\C-m" [(meta return)]))
7364 (org-defkey orgstruct-mode-map [(meta return)]
7365 (orgstruct-make-binding 'org-insert-heading 106
7366 [(meta return)] "\M-\C-m"))
7368 (org-defkey orgstruct-mode-map [(shift meta return)]
7369 (orgstruct-make-binding 'org-insert-todo-heading 107
7370 [(meta return)] "\M-\C-m"))
7372 (org-defkey orgstruct-mode-map "\e\C-m"
7373 (orgstruct-make-binding 'org-insert-heading 108
7374 "\e\C-m" [?\e (return)]))
7375 (org-defkey orgstruct-mode-map [?\e (return)]
7376 (orgstruct-make-binding 'org-insert-heading 109
7377 [?\e (return)] "\e\C-m"))
7378 (org-defkey orgstruct-mode-map [?\e (shift return)]
7379 (orgstruct-make-binding 'org-insert-todo-heading 110
7380 [?\e (return)] "\e\C-m"))
7382 (unless org-local-vars
7383 (setq org-local-vars (org-get-local-variables)))
7387 (defun orgstruct-make-binding (fun n &rest keys)
7388 "Create a function for binding in the structure minor mode.
7389 FUN is the command to call inside a table. N is used to create a unique
7390 command name. KEYS are keys that should be checked in for a command
7391 to execute outside of tables."
7392 (eval
7393 (list 'defun
7394 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7395 '(arg)
7396 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7397 "Outside of structure, run the binding of `"
7398 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7399 "'.")
7400 '(interactive "p")
7401 (list 'if
7402 `(org-context-p 'headline 'item
7403 (and orgstruct-is-++
7404 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7405 'item-body))
7406 (list 'org-run-like-in-org-mode (list 'quote fun))
7407 (list 'let '(orgstruct-mode)
7408 (list 'call-interactively
7409 (append '(or)
7410 (mapcar (lambda (k)
7411 (list 'key-binding k))
7412 keys)
7413 '('orgstruct-error))))))))
7415 (defun org-context-p (&rest contexts)
7416 "Check if local context is any of CONTEXTS.
7417 Possible values in the list of contexts are `table', `headline', and `item'."
7418 (let ((pos (point)))
7419 (goto-char (point-at-bol))
7420 (prog1 (or (and (memq 'table contexts)
7421 (looking-at "[ \t]*|"))
7422 (and (memq 'headline contexts)
7423 ;;????????? (looking-at "\\*+"))
7424 (looking-at outline-regexp))
7425 (and (memq 'item contexts)
7426 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7427 (and (memq 'item-body contexts)
7428 (org-in-item-p)))
7429 (goto-char pos))))
7431 (defun org-get-local-variables ()
7432 "Return a list of all local variables in an org-mode buffer."
7433 (let (varlist)
7434 (with-current-buffer (get-buffer-create "*Org tmp*")
7435 (erase-buffer)
7436 (org-mode)
7437 (setq varlist (buffer-local-variables)))
7438 (kill-buffer "*Org tmp*")
7439 (delq nil
7440 (mapcar
7441 (lambda (x)
7442 (setq x
7443 (if (symbolp x)
7444 (list x)
7445 (list (car x) (list 'quote (cdr x)))))
7446 (if (string-match
7447 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7448 (symbol-name (car x)))
7449 x nil))
7450 varlist))))
7452 ;;;###autoload
7453 (defun org-run-like-in-org-mode (cmd)
7454 "Run a command, pretending that the current buffer is in Org-mode.
7455 This will temporarily bind local variables that are typically bound in
7456 Org-mode to the values they have in Org-mode, and then interactively
7457 call CMD."
7458 (org-load-modules-maybe)
7459 (unless org-local-vars
7460 (setq org-local-vars (org-get-local-variables)))
7461 (eval (list 'let org-local-vars
7462 (list 'call-interactively (list 'quote cmd)))))
7464 ;;;; Archiving
7466 (defun org-get-category (&optional pos)
7467 "Get the category applying to position POS."
7468 (get-text-property (or pos (point)) 'org-category))
7470 (defun org-refresh-category-properties ()
7471 "Refresh category text properties in the buffer."
7472 (let ((def-cat (cond
7473 ((null org-category)
7474 (if buffer-file-name
7475 (file-name-sans-extension
7476 (file-name-nondirectory buffer-file-name))
7477 "???"))
7478 ((symbolp org-category) (symbol-name org-category))
7479 (t org-category)))
7480 beg end cat pos optionp)
7481 (org-unmodified
7482 (save-excursion
7483 (save-restriction
7484 (widen)
7485 (goto-char (point-min))
7486 (put-text-property (point) (point-max) 'org-category def-cat)
7487 (while (re-search-forward
7488 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7489 (setq pos (match-end 0)
7490 optionp (equal (char-after (match-beginning 0)) ?#)
7491 cat (org-trim (match-string 2)))
7492 (if optionp
7493 (setq beg (point-at-bol) end (point-max))
7494 (org-back-to-heading t)
7495 (setq beg (point) end (org-end-of-subtree t t)))
7496 (put-text-property beg end 'org-category cat)
7497 (goto-char pos)))))))
7500 ;;;; Link Stuff
7502 ;;; Link abbreviations
7504 (defun org-link-expand-abbrev (link)
7505 "Apply replacements as defined in `org-link-abbrev-alist."
7506 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7507 (let* ((key (match-string 1 link))
7508 (as (or (assoc key org-link-abbrev-alist-local)
7509 (assoc key org-link-abbrev-alist)))
7510 (tag (and (match-end 2) (match-string 3 link)))
7511 rpl)
7512 (if (not as)
7513 link
7514 (setq rpl (cdr as))
7515 (cond
7516 ((symbolp rpl) (funcall rpl tag))
7517 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7518 ((string-match "%h" rpl)
7519 (replace-match (url-hexify-string (or tag "")) t t rpl))
7520 (t (concat rpl tag)))))
7521 link))
7523 ;;; Storing and inserting links
7525 (defvar org-insert-link-history nil
7526 "Minibuffer history for links inserted with `org-insert-link'.")
7528 (defvar org-stored-links nil
7529 "Contains the links stored with `org-store-link'.")
7531 (defvar org-store-link-plist nil
7532 "Plist with info about the most recently link created with `org-store-link'.")
7534 (defvar org-link-protocols nil
7535 "Link protocols added to Org-mode using `org-add-link-type'.")
7537 (defvar org-store-link-functions nil
7538 "List of functions that are called to create and store a link.
7539 Each function will be called in turn until one returns a non-nil
7540 value. Each function should check if it is responsible for creating
7541 this link (for example by looking at the major mode).
7542 If not, it must exit and return nil.
7543 If yes, it should return a non-nil value after a calling
7544 `org-store-link-props' with a list of properties and values.
7545 Special properties are:
7547 :type The link prefix. like \"http\". This must be given.
7548 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7549 This is obligatory as well.
7550 :description Optional default description for the second pair
7551 of brackets in an Org-mode link. The user can still change
7552 this when inserting this link into an Org-mode buffer.
7554 In addition to these, any additional properties can be specified
7555 and then used in remember templates.")
7557 (defun org-add-link-type (type &optional follow export)
7558 "Add TYPE to the list of `org-link-types'.
7559 Re-compute all regular expressions depending on `org-link-types'
7561 FOLLOW and EXPORT are two functions.
7563 FOLLOW should take the link path as the single argument and do whatever
7564 is necessary to follow the link, for example find a file or display
7565 a mail message.
7567 EXPORT should format the link path for export to one of the export formats.
7568 It should be a function accepting three arguments:
7570 path the path of the link, the text after the prefix (like \"http:\")
7571 desc the description of the link, if any, nil if there was no description
7572 format the export format, a symbol like `html' or `latex'.
7574 The function may use the FORMAT information to return different values
7575 depending on the format. The return value will be put literally into
7576 the exported file.
7577 Org-mode has a built-in default for exporting links. If you are happy with
7578 this default, there is no need to define an export function for the link
7579 type. For a simple example of an export function, see `org-bbdb.el'."
7580 (add-to-list 'org-link-types type t)
7581 (org-make-link-regexps)
7582 (if (assoc type org-link-protocols)
7583 (setcdr (assoc type org-link-protocols) (list follow export))
7584 (push (list type follow export) org-link-protocols)))
7586 (defvar org-agenda-buffer-name)
7588 ;;;###autoload
7589 (defun org-store-link (arg)
7590 "\\<org-mode-map>Store an org-link to the current location.
7591 This link is added to `org-stored-links' and can later be inserted
7592 into an org-buffer with \\[org-insert-link].
7594 For some link types, a prefix arg is interpreted:
7595 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7596 For file links, arg negates `org-context-in-file-links'."
7597 (interactive "P")
7598 (org-load-modules-maybe)
7599 (setq org-store-link-plist nil) ; reset
7600 (let ((outline-regexp (org-get-limited-outline-regexp))
7601 link cpltxt desc description search txt custom-id)
7602 (cond
7604 ((run-hook-with-args-until-success 'org-store-link-functions)
7605 (setq link (plist-get org-store-link-plist :link)
7606 desc (or (plist-get org-store-link-plist :description) link)))
7608 ((equal (buffer-name) "*Org Edit Src Example*")
7609 (let (label gc)
7610 (while (or (not label)
7611 (save-excursion
7612 (save-restriction
7613 (widen)
7614 (goto-char (point-min))
7615 (re-search-forward
7616 (regexp-quote (format org-coderef-label-format label))
7617 nil t))))
7618 (when label (message "Label exists already") (sit-for 2))
7619 (setq label (read-string "Code line label: " label)))
7620 (end-of-line 1)
7621 (setq link (format org-coderef-label-format label))
7622 (setq gc (- 79 (length link)))
7623 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7624 (insert link)
7625 (setq link (concat "(" label ")") desc nil)))
7627 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7628 ;; We are in the agenda, link to referenced location
7629 (let ((m (or (get-text-property (point) 'org-hd-marker)
7630 (get-text-property (point) 'org-marker))))
7631 (when m
7632 (org-with-point-at m
7633 (call-interactively 'org-store-link)))))
7635 ((eq major-mode 'calendar-mode)
7636 (let ((cd (calendar-cursor-to-date)))
7637 (setq link
7638 (format-time-string
7639 (car org-time-stamp-formats)
7640 (apply 'encode-time
7641 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7642 nil nil nil))))
7643 (org-store-link-props :type "calendar" :date cd)))
7645 ((eq major-mode 'w3-mode)
7646 (setq cpltxt (if (and (buffer-name)
7647 (not (string-match "Untitled" (buffer-name))))
7648 (buffer-name)
7649 (url-view-url t))
7650 link (org-make-link (url-view-url t)))
7651 (org-store-link-props :type "w3" :url (url-view-url t)))
7653 ((eq major-mode 'w3m-mode)
7654 (setq cpltxt (or w3m-current-title w3m-current-url)
7655 link (org-make-link w3m-current-url))
7656 (org-store-link-props :type "w3m" :url (url-view-url t)))
7658 ((setq search (run-hook-with-args-until-success
7659 'org-create-file-search-functions))
7660 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7661 "::" search))
7662 (setq cpltxt (or description link)))
7664 ((eq major-mode 'image-mode)
7665 (setq cpltxt (concat "file:"
7666 (abbreviate-file-name buffer-file-name))
7667 link (org-make-link cpltxt))
7668 (org-store-link-props :type "image" :file buffer-file-name))
7670 ((eq major-mode 'dired-mode)
7671 ;; link to the file in the current line
7672 (let ((file (dired-get-filename nil t)))
7673 (setq file (if file
7674 (abbreviate-file-name
7675 (expand-file-name (dired-get-filename nil t)))
7676 ;; otherwise, no file so use current directory.
7677 default-directory))
7678 (setq cpltxt (concat "file:" file)
7679 link (org-make-link cpltxt))))
7681 ((and buffer-file-name (org-mode-p))
7682 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7683 (cond
7684 ((org-in-regexp "<<\\(.*?\\)>>")
7685 (setq cpltxt
7686 (concat "file:"
7687 (abbreviate-file-name buffer-file-name)
7688 "::" (match-string 1))
7689 link (org-make-link cpltxt)))
7690 ((and (featurep 'org-id)
7691 (or (eq org-link-to-org-use-id t)
7692 (and (eq org-link-to-org-use-id 'create-if-interactive)
7693 (interactive-p))
7694 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7695 (interactive-p)
7696 (not custom-id))
7697 (and org-link-to-org-use-id
7698 (condition-case nil
7699 (org-entry-get nil "ID")
7700 (error nil)))))
7701 ;; We can make a link using the ID.
7702 (setq link (condition-case nil
7703 (prog1 (org-id-store-link)
7704 (setq desc (plist-get org-store-link-plist
7705 :description)))
7706 (error
7707 ;; probably before first headline, link to file only
7708 (concat "file:"
7709 (abbreviate-file-name buffer-file-name))))))
7711 ;; Just link to current headline
7712 (setq cpltxt (concat "file:"
7713 (abbreviate-file-name buffer-file-name)))
7714 ;; Add a context search string
7715 (when (org-xor org-context-in-file-links arg)
7716 (setq txt (cond
7717 ((org-on-heading-p) nil)
7718 ((org-region-active-p)
7719 (buffer-substring (region-beginning) (region-end)))
7720 (t nil)))
7721 (when (or (null txt) (string-match "\\S-" txt))
7722 (setq cpltxt
7723 (concat cpltxt "::"
7724 (condition-case nil
7725 (org-make-org-heading-search-string txt)
7726 (error "")))
7727 desc (or (nth 4 (ignore-errors
7728 (org-heading-components))) "NONE"))))
7729 (if (string-match "::\\'" cpltxt)
7730 (setq cpltxt (substring cpltxt 0 -2)))
7731 (setq link (org-make-link cpltxt)))))
7733 ((buffer-file-name (buffer-base-buffer))
7734 ;; Just link to this file here.
7735 (setq cpltxt (concat "file:"
7736 (abbreviate-file-name
7737 (buffer-file-name (buffer-base-buffer)))))
7738 ;; Add a context string
7739 (when (org-xor org-context-in-file-links arg)
7740 (setq txt (if (org-region-active-p)
7741 (buffer-substring (region-beginning) (region-end))
7742 (buffer-substring (point-at-bol) (point-at-eol))))
7743 ;; Only use search option if there is some text.
7744 (when (string-match "\\S-" txt)
7745 (setq cpltxt
7746 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7747 desc "NONE")))
7748 (setq link (org-make-link cpltxt)))
7750 ((interactive-p)
7751 (error "Cannot link to a buffer which is not visiting a file"))
7753 (t (setq link nil)))
7755 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7756 (setq link (or link cpltxt)
7757 desc (or desc cpltxt))
7758 (if (equal desc "NONE") (setq desc nil))
7760 (if (and (or (interactive-p) executing-kbd-macro) link)
7761 (progn
7762 (setq org-stored-links
7763 (cons (list link desc) org-stored-links))
7764 (message "Stored: %s" (or desc link))
7765 (when custom-id
7766 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7767 "::#" custom-id))
7768 (setq org-stored-links
7769 (cons (list link desc) org-stored-links))))
7770 (and link (org-make-link-string link desc)))))
7772 (defun org-store-link-props (&rest plist)
7773 "Store link properties, extract names and addresses."
7774 (let (x adr)
7775 (when (setq x (plist-get plist :from))
7776 (setq adr (mail-extract-address-components x))
7777 (setq plist (plist-put plist :fromname (car adr)))
7778 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7779 (when (setq x (plist-get plist :to))
7780 (setq adr (mail-extract-address-components x))
7781 (setq plist (plist-put plist :toname (car adr)))
7782 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7783 (let ((from (plist-get plist :from))
7784 (to (plist-get plist :to)))
7785 (when (and from to org-from-is-user-regexp)
7786 (setq plist
7787 (plist-put plist :fromto
7788 (if (string-match org-from-is-user-regexp from)
7789 (concat "to %t")
7790 (concat "from %f"))))))
7791 (setq org-store-link-plist plist))
7793 (defun org-add-link-props (&rest plist)
7794 "Add these properties to the link property list."
7795 (let (key value)
7796 (while plist
7797 (setq key (pop plist) value (pop plist))
7798 (setq org-store-link-plist
7799 (plist-put org-store-link-plist key value)))))
7801 (defun org-email-link-description (&optional fmt)
7802 "Return the description part of an email link.
7803 This takes information from `org-store-link-plist' and formats it
7804 according to FMT (default from `org-email-link-description-format')."
7805 (setq fmt (or fmt org-email-link-description-format))
7806 (let* ((p org-store-link-plist)
7807 (to (plist-get p :toaddress))
7808 (from (plist-get p :fromaddress))
7809 (table
7810 (list
7811 (cons "%c" (plist-get p :fromto))
7812 (cons "%F" (plist-get p :from))
7813 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7814 (cons "%T" (plist-get p :to))
7815 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7816 (cons "%s" (plist-get p :subject))
7817 (cons "%m" (plist-get p :message-id)))))
7818 (when (string-match "%c" fmt)
7819 ;; Check if the user wrote this message
7820 (if (and org-from-is-user-regexp from to
7821 (save-match-data (string-match org-from-is-user-regexp from)))
7822 (setq fmt (replace-match "to %t" t t fmt))
7823 (setq fmt (replace-match "from %f" t t fmt))))
7824 (org-replace-escapes fmt table)))
7826 (defun org-make-org-heading-search-string (&optional string heading)
7827 "Make search string for STRING or current headline."
7828 (interactive)
7829 (let ((s (or string (org-get-heading))))
7830 (unless (and string (not heading))
7831 ;; We are using a headline, clean up garbage in there.
7832 (if (string-match org-todo-regexp s)
7833 (setq s (replace-match "" t t s)))
7834 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7835 (setq s (replace-match "" t t s)))
7836 (setq s (org-trim s))
7837 (if (string-match (concat "^\\(" org-quote-string "\\|"
7838 org-comment-string "\\)") s)
7839 (setq s (replace-match "" t t s)))
7840 (while (string-match org-ts-regexp s)
7841 (setq s (replace-match "" t t s))))
7842 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7843 (setq s (replace-match " " t t s)))
7844 (or string (setq s (concat "*" s))) ; Add * for headlines
7845 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7847 (defun org-make-link (&rest strings)
7848 "Concatenate STRINGS."
7849 (apply 'concat strings))
7851 (defun org-make-link-string (link &optional description)
7852 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7853 (unless (string-match "\\S-" link)
7854 (error "Empty link"))
7855 (when (and description
7856 (stringp description)
7857 (not (string-match "\\S-" description)))
7858 (setq description nil))
7859 (when (stringp description)
7860 ;; Remove brackets from the description, they are fatal.
7861 (while (string-match "\\[" description)
7862 (setq description (replace-match "{" t t description)))
7863 (while (string-match "\\]" description)
7864 (setq description (replace-match "}" t t description))))
7865 (when (equal (org-link-escape link) description)
7866 ;; No description needed, it is identical
7867 (setq description nil))
7868 (when (and (not description)
7869 (not (equal link (org-link-escape link))))
7870 (setq description (org-extract-attributes link)))
7871 (concat "[[" (org-link-escape link) "]"
7872 (if description (concat "[" description "]") "")
7873 "]"))
7875 (defconst org-link-escape-chars
7876 '((?\ . "%20")
7877 (?\[ . "%5B")
7878 (?\] . "%5D")
7879 (?\340 . "%E0") ; `a
7880 (?\342 . "%E2") ; ^a
7881 (?\347 . "%E7") ; ,c
7882 (?\350 . "%E8") ; `e
7883 (?\351 . "%E9") ; 'e
7884 (?\352 . "%EA") ; ^e
7885 (?\356 . "%EE") ; ^i
7886 (?\364 . "%F4") ; ^o
7887 (?\371 . "%F9") ; `u
7888 (?\373 . "%FB") ; ^u
7889 (?\; . "%3B")
7890 (?? . "%3F")
7891 (?= . "%3D")
7892 (?+ . "%2B")
7894 "Association list of escapes for some characters problematic in links.
7895 This is the list that is used for internal purposes.")
7897 (defvar org-url-encoding-use-url-hexify nil)
7899 (defconst org-link-escape-chars-browser
7900 '((?\ . "%20")) ; 32 for the SPC char
7901 "Association list of escapes for some characters problematic in links.
7902 This is the list that is used before handing over to the browser.")
7904 (defun org-link-escape (text &optional table)
7905 "Escape characters in TEXT that are problematic for links."
7906 (if (and org-url-encoding-use-url-hexify (not table))
7907 (url-hexify-string text)
7908 (setq table (or table org-link-escape-chars))
7909 (when text
7910 (let ((re (mapconcat (lambda (x) (regexp-quote
7911 (char-to-string (car x))))
7912 table "\\|")))
7913 (while (string-match re text)
7914 (setq text
7915 (replace-match
7916 (cdr (assoc (string-to-char (match-string 0 text))
7917 table))
7918 t t text)))
7919 text))))
7921 (defun org-link-unescape (text &optional table)
7922 "Reverse the action of `org-link-escape'."
7923 (if (and org-url-encoding-use-url-hexify (not table))
7924 (url-unhex-string text)
7925 (setq table (or table org-link-escape-chars))
7926 (when text
7927 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7928 table "\\|")))
7929 (while (string-match re text)
7930 (setq text
7931 (replace-match
7932 (char-to-string (car (rassoc (match-string 0 text) table)))
7933 t t text)))
7934 text))))
7936 (defun org-xor (a b)
7937 "Exclusive or."
7938 (if a (not b) b))
7940 (defun org-fixup-message-id-for-http (s)
7941 "Replace special characters in a message id, so it can be used in an http query."
7942 (while (string-match "<" s)
7943 (setq s (replace-match "%3C" t t s)))
7944 (while (string-match ">" s)
7945 (setq s (replace-match "%3E" t t s)))
7946 (while (string-match "@" s)
7947 (setq s (replace-match "%40" t t s)))
7950 ;;;###autoload
7951 (defun org-insert-link-global ()
7952 "Insert a link like Org-mode does.
7953 This command can be called in any mode to insert a link in Org-mode syntax."
7954 (interactive)
7955 (org-load-modules-maybe)
7956 (org-run-like-in-org-mode 'org-insert-link))
7958 (defun org-insert-link (&optional complete-file link-location)
7959 "Insert a link. At the prompt, enter the link.
7961 Completion can be used to insert any of the link protocol prefixes like
7962 http or ftp in use.
7964 The history can be used to select a link previously stored with
7965 `org-store-link'. When the empty string is entered (i.e. if you just
7966 press RET at the prompt), the link defaults to the most recently
7967 stored link. As SPC triggers completion in the minibuffer, you need to
7968 use M-SPC or C-q SPC to force the insertion of a space character.
7970 You will also be prompted for a description, and if one is given, it will
7971 be displayed in the buffer instead of the link.
7973 If there is already a link at point, this command will allow you to edit link
7974 and description parts.
7976 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7977 be selected using completion. The path to the file will be relative to the
7978 current directory if the file is in the current directory or a subdirectory.
7979 Otherwise, the link will be the absolute path as completed in the minibuffer
7980 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7981 option `org-link-file-path-type'.
7983 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7984 the current directory or below.
7986 With three \\[universal-argument] prefixes, negate the meaning of
7987 `org-keep-stored-link-after-insertion'.
7989 If `org-make-link-description-function' is non-nil, this function will be
7990 called with the link target, and the result will be the default
7991 link description.
7993 If the LINK-LOCATION parameter is non-nil, this value will be
7994 used as the link location instead of reading one interactively."
7995 (interactive "P")
7996 (let* ((wcf (current-window-configuration))
7997 (region (if (org-region-active-p)
7998 (buffer-substring (region-beginning) (region-end))))
7999 (remove (and region (list (region-beginning) (region-end))))
8000 (desc region)
8001 tmphist ; byte-compile incorrectly complains about this
8002 (link link-location)
8003 entry file all-prefixes)
8004 (cond
8005 (link-location) ; specified by arg, just use it.
8006 ((org-in-regexp org-bracket-link-regexp 1)
8007 ;; We do have a link at point, and we are going to edit it.
8008 (setq remove (list (match-beginning 0) (match-end 0)))
8009 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8010 (setq link (read-string "Link: "
8011 (org-link-unescape
8012 (org-match-string-no-properties 1)))))
8013 ((or (org-in-regexp org-angle-link-re)
8014 (org-in-regexp org-plain-link-re))
8015 ;; Convert to bracket link
8016 (setq remove (list (match-beginning 0) (match-end 0))
8017 link (read-string "Link: "
8018 (org-remove-angle-brackets (match-string 0)))))
8019 ((member complete-file '((4) (16)))
8020 ;; Completing read for file names.
8021 (setq link (org-file-complete-link complete-file)))
8023 ;; Read link, with completion for stored links.
8024 (with-output-to-temp-buffer "*Org Links*"
8025 (princ "Insert a link.
8026 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8027 (when org-stored-links
8028 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8029 (princ (mapconcat
8030 (lambda (x)
8031 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8032 (reverse org-stored-links) "\n"))))
8033 (let ((cw (selected-window)))
8034 (select-window (get-buffer-window "*Org Links*"))
8035 (setq truncate-lines t)
8036 (unless (pos-visible-in-window-p (point-max))
8037 (org-fit-window-to-buffer))
8038 (and (window-live-p cw) (select-window cw)))
8039 ;; Fake a link history, containing the stored links.
8040 (setq tmphist (append (mapcar 'car org-stored-links)
8041 org-insert-link-history))
8042 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8043 (mapcar 'car org-link-abbrev-alist)
8044 org-link-types))
8045 (unwind-protect
8046 (progn
8047 (setq link
8048 (let ((org-completion-use-ido nil)
8049 (org-completion-use-iswitchb nil))
8050 (org-completing-read
8051 "Link: "
8052 (append
8053 (mapcar (lambda (x) (list (concat x ":")))
8054 all-prefixes)
8055 (mapcar 'car org-stored-links))
8056 nil nil nil
8057 'tmphist
8058 (car (car org-stored-links)))))
8059 (if (not (string-match "\\S-" link))
8060 (error "No link selected"))
8061 (if (or (member link all-prefixes)
8062 (and (equal ":" (substring link -1))
8063 (member (substring link 0 -1) all-prefixes)
8064 (setq link (substring link 0 -1))))
8065 (setq link (org-link-try-special-completion link))))
8066 (set-window-configuration wcf)
8067 (kill-buffer "*Org Links*"))
8068 (setq entry (assoc link org-stored-links))
8069 (or entry (push link org-insert-link-history))
8070 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8071 (not org-keep-stored-link-after-insertion))
8072 (setq org-stored-links (delq (assoc link org-stored-links)
8073 org-stored-links)))
8074 (setq desc (or desc (nth 1 entry)))))
8076 (if (string-match org-plain-link-re link)
8077 ;; URL-like link, normalize the use of angular brackets.
8078 (setq link (org-make-link (org-remove-angle-brackets link))))
8080 ;; Check if we are linking to the current file with a search option
8081 ;; If yes, simplify the link by using only the search option.
8082 (when (and buffer-file-name
8083 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8084 (let* ((path (match-string 1 link))
8085 (case-fold-search nil)
8086 (search (match-string 2 link)))
8087 (save-match-data
8088 (if (equal (file-truename buffer-file-name) (file-truename path))
8089 ;; We are linking to this same file, with a search option
8090 (setq link search)))))
8092 ;; Check if we can/should use a relative path. If yes, simplify the link
8093 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8094 (let* ((type (match-string 1 link))
8095 (path (match-string 2 link))
8096 (origpath path)
8097 (case-fold-search nil))
8098 (cond
8099 ((or (eq org-link-file-path-type 'absolute)
8100 (equal complete-file '(16)))
8101 (setq path (abbreviate-file-name (expand-file-name path))))
8102 ((eq org-link-file-path-type 'noabbrev)
8103 (setq path (expand-file-name path)))
8104 ((eq org-link-file-path-type 'relative)
8105 (setq path (file-relative-name path)))
8107 (save-match-data
8108 (if (string-match (concat "^" (regexp-quote
8109 (file-name-as-directory
8110 (expand-file-name "."))))
8111 (expand-file-name path))
8112 ;; We are linking a file with relative path name.
8113 (setq path (substring (expand-file-name path)
8114 (match-end 0)))
8115 (setq path (abbreviate-file-name (expand-file-name path)))))))
8116 (setq link (concat type path))
8117 (if (equal desc origpath)
8118 (setq desc path))))
8120 (if org-make-link-description-function
8121 (setq desc (funcall org-make-link-description-function link desc)))
8123 (setq desc (read-string "Description: " desc))
8124 (unless (string-match "\\S-" desc) (setq desc nil))
8125 (if remove (apply 'delete-region remove))
8126 (insert (org-make-link-string link desc))))
8128 (defun org-link-try-special-completion (type)
8129 "If there is completion support for link type TYPE, offer it."
8130 (let ((fun (intern (concat "org-" type "-complete-link"))))
8131 (if (functionp fun)
8132 (funcall fun)
8133 (read-string "Link (no completion support): " (concat type ":")))))
8135 (defun org-file-complete-link (&optional arg)
8136 "Create a file link using completion."
8137 (let (file link)
8138 (setq file (read-file-name "File: "))
8139 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8140 (pwd1 (file-name-as-directory (abbreviate-file-name
8141 (expand-file-name ".")))))
8142 (cond
8143 ((equal arg '(16))
8144 (setq link (org-make-link
8145 "file:"
8146 (abbreviate-file-name (expand-file-name file)))))
8147 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8148 (setq link (org-make-link "file:" (match-string 1 file))))
8149 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8150 (expand-file-name file))
8151 (setq link (org-make-link
8152 "file:" (match-string 1 (expand-file-name file)))))
8153 (t (setq link (org-make-link "file:" file)))))
8154 link))
8156 (defun org-completing-read (&rest args)
8157 "Completing-read with SPACE being a normal character."
8158 (let ((minibuffer-local-completion-map
8159 (copy-keymap minibuffer-local-completion-map)))
8160 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8161 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8162 (apply 'org-icompleting-read args)))
8164 (defun org-completing-read-no-i (&rest args)
8165 (let (org-completion-use-ido org-completion-use-iswitchb)
8166 (apply 'org-completing-read args)))
8168 (defun org-iswitchb-completing-read (prompt choices &rest args)
8169 "Use iswitch as a completing-read replacement to choose from choices.
8170 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8171 from."
8172 (let* ((iswitchb-use-virtual-buffers nil)
8173 (iswitchb-make-buflist-hook
8174 (lambda ()
8175 (setq iswitchb-temp-buflist choices))))
8176 (iswitchb-read-buffer prompt)))
8178 (defun org-icompleting-read (&rest args)
8179 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8180 (org-without-partial-completion
8181 (if (and org-completion-use-ido
8182 (fboundp 'ido-completing-read)
8183 (boundp 'ido-mode) ido-mode
8184 (listp (second args)))
8185 (let ((ido-enter-matching-directory nil))
8186 (apply 'ido-completing-read (concat (car args))
8187 (if (consp (car (nth 1 args)))
8188 (mapcar (lambda (x) (car x)) (nth 1 args))
8189 (nth 1 args))
8190 (cddr args)))
8191 (if (and org-completion-use-iswitchb
8192 (boundp 'iswitchb-mode) iswitchb-mode
8193 (listp (second args)))
8194 (apply 'org-iswitchb-completing-read (concat (car args))
8195 (if (consp (car (nth 1 args)))
8196 (mapcar (lambda (x) (car x)) (nth 1 args))
8197 (nth 1 args))
8198 (cddr args))
8199 (apply 'completing-read args)))))
8201 (defun org-extract-attributes (s)
8202 "Extract the attributes cookie from a string and set as text property."
8203 (let (a attr (start 0) key value)
8204 (save-match-data
8205 (when (string-match "{{\\([^}]+\\)}}$" s)
8206 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8207 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8208 (setq key (match-string 1 a) value (match-string 2 a)
8209 start (match-end 0)
8210 attr (plist-put attr (intern key) value))))
8211 (org-add-props s nil 'org-attr attr))
8214 (defun org-extract-attributes-from-string (tag)
8215 (let (key value attr)
8216 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8217 (setq key (match-string 1 tag) value (match-string 2 tag)
8218 tag (replace-match "" t t tag)
8219 attr (plist-put attr (intern key) value)))
8220 (cons tag attr)))
8222 (defun org-attributes-to-string (plist)
8223 "Format a property list into an HTML attribute list."
8224 (let ((s "") key value)
8225 (while plist
8226 (setq key (pop plist) value (pop plist))
8227 (and value
8228 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8231 ;;; Opening/following a link
8233 (defvar org-link-search-failed nil)
8235 (defvar org-open-link-functions nil
8236 "Hook for functions finding a plain text link.
8237 These functions must take a single argument, the link content.
8238 They will be called for links that look like [[link text][description]]
8239 when LINK TEXT does not have a protocol like \"http:\" and does not look
8240 like a filename (e.g. \"./blue.png\").
8242 These functions will be called *before* Org attempts to resolve the
8243 link by doing text searches in the current buffer - so if you want a
8244 link \"[[target]]\" to still find \"<<target>>\", your function should
8245 handle this as a special case.
8247 When the function does handle the link, it must return a non-nil value.
8248 If it decides that it is not responsible for this link, it must return
8249 nil to indicate that that Org-mode can continue with other options
8250 like exact and fuzzy text search.")
8252 (defun org-next-link ()
8253 "Move forward to the next link.
8254 If the link is in hidden text, expose it."
8255 (interactive)
8256 (when (and org-link-search-failed (eq this-command last-command))
8257 (goto-char (point-min))
8258 (message "Link search wrapped back to beginning of buffer"))
8259 (setq org-link-search-failed nil)
8260 (let* ((pos (point))
8261 (ct (org-context))
8262 (a (assoc :link ct)))
8263 (if a (goto-char (nth 2 a)))
8264 (if (re-search-forward org-any-link-re nil t)
8265 (progn
8266 (goto-char (match-beginning 0))
8267 (if (org-invisible-p) (org-show-context)))
8268 (goto-char pos)
8269 (setq org-link-search-failed t)
8270 (error "No further link found"))))
8272 (defun org-previous-link ()
8273 "Move backward to the previous link.
8274 If the link is in hidden text, expose it."
8275 (interactive)
8276 (when (and org-link-search-failed (eq this-command last-command))
8277 (goto-char (point-max))
8278 (message "Link search wrapped back to end of buffer"))
8279 (setq org-link-search-failed nil)
8280 (let* ((pos (point))
8281 (ct (org-context))
8282 (a (assoc :link ct)))
8283 (if a (goto-char (nth 1 a)))
8284 (if (re-search-backward org-any-link-re nil t)
8285 (progn
8286 (goto-char (match-beginning 0))
8287 (if (org-invisible-p) (org-show-context)))
8288 (goto-char pos)
8289 (setq org-link-search-failed t)
8290 (error "No further link found"))))
8292 (defun org-translate-link (s)
8293 "Translate a link string if a translation function has been defined."
8294 (if (and org-link-translation-function
8295 (fboundp org-link-translation-function)
8296 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8297 (progn
8298 (setq s (funcall org-link-translation-function
8299 (match-string 1) (match-string 2)))
8300 (concat (car s) ":" (cdr s)))
8303 (defun org-translate-link-from-planner (type path)
8304 "Translate a link from Emacs Planner syntax so that Org can follow it.
8305 This is still an experimental function, your mileage may vary."
8306 (cond
8307 ((member type '("http" "https" "news" "ftp"))
8308 ;; standard Internet links are the same.
8309 nil)
8310 ((and (equal type "irc") (string-match "^//" path))
8311 ;; Planner has two / at the beginning of an irc link, we have 1.
8312 ;; We should have zero, actually....
8313 (setq path (substring path 1)))
8314 ((and (equal type "lisp") (string-match "^/" path))
8315 ;; Planner has a slash, we do not.
8316 (setq type "elisp" path (substring path 1)))
8317 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8318 ;; A typical message link. Planner has the id after the final slash,
8319 ;; we separate it with a hash mark
8320 (setq path (concat (match-string 1 path) "#"
8321 (org-remove-angle-brackets (match-string 2 path)))))
8323 (cons type path))
8325 (defun org-find-file-at-mouse (ev)
8326 "Open file link or URL at mouse."
8327 (interactive "e")
8328 (mouse-set-point ev)
8329 (org-open-at-point 'in-emacs))
8331 (defun org-open-at-mouse (ev)
8332 "Open file link or URL at mouse."
8333 (interactive "e")
8334 (mouse-set-point ev)
8335 (if (eq major-mode 'org-agenda-mode)
8336 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8337 (org-open-at-point))
8339 (defvar org-window-config-before-follow-link nil
8340 "The window configuration before following a link.
8341 This is saved in case the need arises to restore it.")
8343 (defvar org-open-link-marker (make-marker)
8344 "Marker pointing to the location where `org-open-at-point; was called.")
8346 ;;;###autoload
8347 (defun org-open-at-point-global ()
8348 "Follow a link like Org-mode does.
8349 This command can be called in any mode to follow a link that has
8350 Org-mode syntax."
8351 (interactive)
8352 (org-run-like-in-org-mode 'org-open-at-point))
8354 ;;;###autoload
8355 (defun org-open-link-from-string (s &optional arg reference-buffer)
8356 "Open a link in the string S, as if it was in Org-mode."
8357 (interactive "sLink: \nP")
8358 (let ((reference-buffer (or reference-buffer (current-buffer))))
8359 (with-temp-buffer
8360 (let ((org-inhibit-startup t))
8361 (org-mode)
8362 (insert s)
8363 (goto-char (point-min))
8364 (org-open-at-point arg reference-buffer)))))
8366 (defun org-open-at-point (&optional in-emacs reference-buffer)
8367 "Open link at or after point.
8368 If there is no link at point, this function will search forward up to
8369 the end of the current line.
8370 Normally, files will be opened by an appropriate application. If the
8371 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8372 With a double prefix argument, try to open outside of Emacs, in the
8373 application the system uses for this file type."
8374 (interactive "P")
8375 (org-load-modules-maybe)
8376 (move-marker org-open-link-marker (point))
8377 (setq org-window-config-before-follow-link (current-window-configuration))
8378 (org-remove-occur-highlights nil nil t)
8379 (cond
8380 ((and (org-on-heading-p)
8381 (not (org-in-regexp
8382 (concat org-plain-link-re "\\|"
8383 org-bracket-link-regexp "\\|"
8384 org-angle-link-re "\\|"
8385 "[ \t]:[^ \t\n]+:[ \t]*$"))))
8386 (or (org-offer-links-in-entry in-emacs)
8387 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8388 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8389 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8390 (org-footnote-action))
8392 (let (type path link line search (pos (point)))
8393 (catch 'match
8394 (save-excursion
8395 (skip-chars-forward "^]\n\r")
8396 (when (org-in-regexp org-bracket-link-regexp 1)
8397 (setq link (org-extract-attributes
8398 (org-link-unescape (org-match-string-no-properties 1))))
8399 (while (string-match " *\n *" link)
8400 (setq link (replace-match " " t t link)))
8401 (setq link (org-link-expand-abbrev link))
8402 (cond
8403 ((or (file-name-absolute-p link)
8404 (string-match "^\\.\\.?/" link))
8405 (setq type "file" path link))
8406 ((string-match org-link-re-with-space3 link)
8407 (setq type (match-string 1 link) path (match-string 2 link)))
8408 (t (setq type "thisfile" path link)))
8409 (throw 'match t)))
8411 (when (get-text-property (point) 'org-linked-text)
8412 (setq type "thisfile"
8413 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8414 (1+ (point)) (point))
8415 path (buffer-substring
8416 (previous-single-property-change pos 'org-linked-text)
8417 (next-single-property-change pos 'org-linked-text)))
8418 (throw 'match t))
8420 (save-excursion
8421 (when (or (org-in-regexp org-angle-link-re)
8422 (org-in-regexp org-plain-link-re))
8423 (setq type (match-string 1) path (match-string 2))
8424 (throw 'match t)))
8425 (save-excursion
8426 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8427 (setq type "tags"
8428 path (match-string 1))
8429 (while (string-match ":" path)
8430 (setq path (replace-match "+" t t path)))
8431 (throw 'match t)))
8432 (when (org-in-regexp "<\\([^><\n]+\\)>")
8433 (setq type "tree-match"
8434 path (match-string 1))
8435 (throw 'match t)))
8436 (unless path
8437 (error "No link found"))
8439 ;; switch back to reference buffer
8440 ;; needed when if called in a temporary buffer through
8441 ;; org-open-link-from-string
8442 (with-current-buffer (or reference-buffer (current-buffer))
8444 ;; Remove any trailing spaces in path
8445 (if (string-match " +\\'" path)
8446 (setq path (replace-match "" t t path)))
8447 (if (and org-link-translation-function
8448 (fboundp org-link-translation-function))
8449 ;; Check if we need to translate the link
8450 (let ((tmp (funcall org-link-translation-function type path)))
8451 (setq type (car tmp) path (cdr tmp))))
8453 (cond
8455 ((assoc type org-link-protocols)
8456 (funcall (nth 1 (assoc type org-link-protocols)) path))
8458 ((equal type "mailto")
8459 (let ((cmd (car org-link-mailto-program))
8460 (args (cdr org-link-mailto-program)) args1
8461 (address path) (subject "") a)
8462 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8463 (setq address (match-string 1 path)
8464 subject (org-link-escape (match-string 2 path))))
8465 (while args
8466 (cond
8467 ((not (stringp (car args))) (push (pop args) args1))
8468 (t (setq a (pop args))
8469 (if (string-match "%a" a)
8470 (setq a (replace-match address t t a)))
8471 (if (string-match "%s" a)
8472 (setq a (replace-match subject t t a)))
8473 (push a args1))))
8474 (apply cmd (nreverse args1))))
8476 ((member type '("http" "https" "ftp" "news"))
8477 (browse-url (concat type ":" (org-link-escape
8478 path org-link-escape-chars-browser))))
8480 ((member type '("message"))
8481 (browse-url (concat type ":" path)))
8483 ((string= type "tags")
8484 (org-tags-view in-emacs path))
8486 ((string= type "tree-match")
8487 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8489 ((string= type "file")
8490 (if (string-match "::\\([0-9]+\\)\\'" path)
8491 (setq line (string-to-number (match-string 1 path))
8492 path (substring path 0 (match-beginning 0)))
8493 (if (string-match "::\\(.+\\)\\'" path)
8494 (setq search (match-string 1 path)
8495 path (substring path 0 (match-beginning 0)))))
8496 (if (string-match "[*?{]" (file-name-nondirectory path))
8497 (dired path)
8498 (org-open-file path in-emacs line search)))
8500 ((string= type "news")
8501 (require 'org-gnus)
8502 (org-gnus-follow-link path))
8504 ((string= type "shell")
8505 (let ((cmd path))
8506 (if (or (not org-confirm-shell-link-function)
8507 (funcall org-confirm-shell-link-function
8508 (format "Execute \"%s\" in shell? "
8509 (org-add-props cmd nil
8510 'face 'org-warning))))
8511 (progn
8512 (message "Executing %s" cmd)
8513 (shell-command cmd))
8514 (error "Abort"))))
8516 ((string= type "elisp")
8517 (let ((cmd path))
8518 (if (or (not org-confirm-elisp-link-function)
8519 (funcall org-confirm-elisp-link-function
8520 (format "Execute \"%s\" as elisp? "
8521 (org-add-props cmd nil
8522 'face 'org-warning))))
8523 (message "%s => %s" cmd
8524 (if (equal (string-to-char cmd) ?\()
8525 (eval (read cmd))
8526 (call-interactively (read cmd))))
8527 (error "Abort"))))
8529 ((and (string= type "thisfile")
8530 (run-hook-with-args-until-success
8531 'org-open-link-functions path)))
8533 ((string= type "thisfile")
8534 (if in-emacs
8535 (switch-to-buffer-other-window
8536 (org-get-buffer-for-internal-link (current-buffer)))
8537 (org-mark-ring-push))
8538 (let ((cmd `(org-link-search
8539 ,path
8540 ,(cond ((equal in-emacs '(4)) 'occur)
8541 ((equal in-emacs '(16)) 'org-occur)
8542 (t nil))
8543 ,pos)))
8544 (condition-case nil (eval cmd)
8545 (error (progn (widen) (eval cmd))))))
8548 (browse-url-at-point)))))))
8549 (move-marker org-open-link-marker nil)
8550 (run-hook-with-args 'org-follow-link-hook))
8552 (defun org-offer-links-in-entry (&optional nth zero)
8553 "Offer links in the current entry and follow the selected link.
8554 If there is only one link, follow it immediately as well.
8555 If NTH is an integer, immediately pick the NTH link found.
8556 If ZERO is a string, check also this string for a link, and if
8557 there is one, offer it as link number zero."
8558 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8559 "\\(" org-angle-link-re "\\)\\|"
8560 "\\(" org-plain-link-re "\\)"))
8561 (cnt ?0)
8562 (in-emacs (if (integerp nth) nil nth))
8563 have-zero end links link c)
8564 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8565 (push (match-string 0 zero) links)
8566 (setq cnt (1- cnt) have-zero t))
8567 (save-excursion
8568 (org-back-to-heading t)
8569 (setq end (save-excursion (outline-next-heading) (point)))
8570 (while (re-search-forward re end t)
8571 (push (match-string 0) links))
8572 (setq links (org-uniquify (reverse links))))
8574 (cond
8575 ((null links)
8576 (message "No links"))
8577 ((equal (length links) 1)
8578 (setq link (list (car links))))
8579 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8580 (setq link (nth (if have-zero nth (1- nth)) links)))
8581 (t ; we have to select a link
8582 (save-excursion
8583 (save-window-excursion
8584 (delete-other-windows)
8585 (with-output-to-temp-buffer "*Select Link*"
8586 (mapc (lambda (l)
8587 (if (not (string-match org-bracket-link-regexp l))
8588 (princ (format "[%c] %s\n" (incf cnt)
8589 (org-remove-angle-brackets l)))
8590 (if (match-end 3)
8591 (princ (format "[%c] %s (%s)\n" (incf cnt)
8592 (match-string 3 l) (match-string 1 l)))
8593 (princ (format "[%c] %s\n" (incf cnt)
8594 (match-string 1 l))))))
8595 links))
8596 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8597 (message "Select link to open, RET to open all:")
8598 (setq c (read-char-exclusive))
8599 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8600 (when (equal c ?q) (error "Abort"))
8601 (if (equal c ?\C-m)
8602 (setq link links)
8603 (setq nth (- c ?0))
8604 (if have-zero (setq nth (1+ nth)))
8605 (unless (and (integerp nth) (>= (length links) nth))
8606 (error "Invalid link selection"))
8607 (setq link (list (nth (1- nth) links))))))
8608 (if link
8609 (let ((buf (current-buffer)))
8610 (dolist (l link)
8611 (org-open-link-from-string l in-emacs buf))
8613 nil)))
8615 ;; Add special file links that specify the way of opening
8617 (org-add-link-type "file+sys" 'org-open-file-with-system)
8618 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
8619 (defun org-open-file-with-system (path)
8620 "Open file at PATH using the system way of opeing it."
8621 (org-open-file path 'system))
8622 (defun org-open-file-with-emacs (path)
8623 "Open file at PATH in emacs."
8624 (org-open-file path 'emacs))
8625 (defun org-remove-file-link-modifiers ()
8626 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
8627 (goto-char (point-min))
8628 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
8629 (org-if-unprotected
8630 (replace-match "file:" t t))))
8631 (eval-after-load "org-exp"
8632 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
8633 'org-remove-file-link-modifiers))
8635 ;;;; Time estimates
8637 (defun org-get-effort (&optional pom)
8638 "Get the effort estimate for the current entry."
8639 (org-entry-get pom org-effort-property))
8641 ;;; File search
8643 (defvar org-create-file-search-functions nil
8644 "List of functions to construct the right search string for a file link.
8645 These functions are called in turn with point at the location to
8646 which the link should point.
8648 A function in the hook should first test if it would like to
8649 handle this file type, for example by checking the major-mode or
8650 the file extension. If it decides not to handle this file, it
8651 should just return nil to give other functions a chance. If it
8652 does handle the file, it must return the search string to be used
8653 when following the link. The search string will be part of the
8654 file link, given after a double colon, and `org-open-at-point'
8655 will automatically search for it. If special measures must be
8656 taken to make the search successful, another function should be
8657 added to the companion hook `org-execute-file-search-functions',
8658 which see.
8660 A function in this hook may also use `setq' to set the variable
8661 `description' to provide a suggestion for the descriptive text to
8662 be used for this link when it gets inserted into an Org-mode
8663 buffer with \\[org-insert-link].")
8665 (defvar org-execute-file-search-functions nil
8666 "List of functions to execute a file search triggered by a link.
8668 Functions added to this hook must accept a single argument, the
8669 search string that was part of the file link, the part after the
8670 double colon. The function must first check if it would like to
8671 handle this search, for example by checking the major-mode or the
8672 file extension. If it decides not to handle this search, it
8673 should just return nil to give other functions a chance. If it
8674 does handle the search, it must return a non-nil value to keep
8675 other functions from trying.
8677 Each function can access the current prefix argument through the
8678 variable `current-prefix-argument'. Note that a single prefix is
8679 used to force opening a link in Emacs, so it may be good to only
8680 use a numeric or double prefix to guide the search function.
8682 In case this is needed, a function in this hook can also restore
8683 the window configuration before `org-open-at-point' was called using:
8685 (set-window-configuration org-window-config-before-follow-link)")
8687 (defun org-link-search (s &optional type avoid-pos)
8688 "Search for a link search option.
8689 If S is surrounded by forward slashes, it is interpreted as a
8690 regular expression. In org-mode files, this will create an `org-occur'
8691 sparse tree. In ordinary files, `occur' will be used to list matches.
8692 If the current buffer is in `dired-mode', grep will be used to search
8693 in all files. If AVOID-POS is given, ignore matches near that position."
8694 (let ((case-fold-search t)
8695 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8696 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8697 (append '(("") (" ") ("\t") ("\n"))
8698 org-emphasis-alist)
8699 "\\|") "\\)"))
8700 (pos (point))
8701 (pre nil) (post nil)
8702 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8703 (cond
8704 ;; First check if there are any special
8705 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8706 ;; Now try the builtin stuff
8707 ((and (equal (string-to-char s0) ?#)
8708 (> (length s0) 1)
8709 (save-excursion
8710 (goto-char (point-min))
8711 (and
8712 (re-search-forward
8713 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8714 (setq type 'dedicated
8715 pos (match-beginning 0))))
8716 ;; There is an exact target for this
8717 (goto-char pos)
8718 (org-back-to-heading t)))
8719 ((save-excursion
8720 (goto-char (point-min))
8721 (and
8722 (re-search-forward
8723 (concat "<<" (regexp-quote s0) ">>") nil t)
8724 (setq type 'dedicated
8725 pos (match-beginning 0))))
8726 ;; There is an exact target for this
8727 (goto-char pos))
8728 ((and (string-match "^(\\(.*\\))$" s0)
8729 (save-excursion
8730 (goto-char (point-min))
8731 (and
8732 (re-search-forward
8733 (concat "[^[]" (regexp-quote
8734 (format org-coderef-label-format
8735 (match-string 1 s0))))
8736 nil t)
8737 (setq type 'dedicated
8738 pos (1+ (match-beginning 0))))))
8739 ;; There is a coderef target for this
8740 (goto-char pos))
8741 ((string-match "^/\\(.*\\)/$" s)
8742 ;; A regular expression
8743 (cond
8744 ((org-mode-p)
8745 (org-occur (match-string 1 s)))
8746 ;;((eq major-mode 'dired-mode)
8747 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8748 (t (org-do-occur (match-string 1 s)))))
8750 ;; A normal search strings
8751 (when (equal (string-to-char s) ?*)
8752 ;; Anchor on headlines, post may include tags.
8753 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8754 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8755 s (substring s 1)))
8756 (remove-text-properties
8757 0 (length s)
8758 '(face nil mouse-face nil keymap nil fontified nil) s)
8759 ;; Make a series of regular expressions to find a match
8760 (setq words (org-split-string s "[ \n\r\t]+")
8762 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8763 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8764 "\\)" markers)
8765 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8766 re2a (concat "[ \t\r\n]" re2a_)
8767 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8768 re4 (concat "[^a-zA-Z_]" re4_)
8770 re1 (concat pre re2 post)
8771 re3 (concat pre (if pre re4_ re4) post)
8772 re5 (concat pre ".*" re4)
8773 re2 (concat pre re2)
8774 re2a (concat pre (if pre re2a_ re2a))
8775 re4 (concat pre (if pre re4_ re4))
8776 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8777 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8778 re5 "\\)"
8780 (cond
8781 ((eq type 'org-occur) (org-occur reall))
8782 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8783 (t (goto-char (point-min))
8784 (setq type 'fuzzy)
8785 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8786 (org-search-not-self 1 re1 nil t)
8787 (org-search-not-self 1 re2 nil t)
8788 (org-search-not-self 1 re2a nil t)
8789 (org-search-not-self 1 re3 nil t)
8790 (org-search-not-self 1 re4 nil t)
8791 (org-search-not-self 1 re5 nil t)
8793 (goto-char (match-beginning 1))
8794 (goto-char pos)
8795 (error "No match")))))
8797 ;; Normal string-search
8798 (goto-char (point-min))
8799 (if (search-forward s nil t)
8800 (goto-char (match-beginning 0))
8801 (error "No match"))))
8802 (and (org-mode-p) (org-show-context 'link-search))
8803 type))
8805 (defun org-search-not-self (group &rest args)
8806 "Execute `re-search-forward', but only accept matches that do not
8807 enclose the position of `org-open-link-marker'."
8808 (let ((m org-open-link-marker))
8809 (catch 'exit
8810 (while (apply 're-search-forward args)
8811 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8812 (goto-char (match-end group))
8813 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8814 (> (match-beginning 0) (marker-position m))
8815 (< (match-end 0) (marker-position m)))
8816 (save-match-data
8817 (or (not (org-in-regexp
8818 org-bracket-link-analytic-regexp 1))
8819 (not (match-end 4)) ; no description
8820 (and (<= (match-beginning 4) (point))
8821 (>= (match-end 4) (point))))))
8822 (throw 'exit (point))))))))
8824 (defun org-get-buffer-for-internal-link (buffer)
8825 "Return a buffer to be used for displaying the link target of internal links."
8826 (cond
8827 ((not org-display-internal-link-with-indirect-buffer)
8828 buffer)
8829 ((string-match "(Clone)$" (buffer-name buffer))
8830 (message "Buffer is already a clone, not making another one")
8831 ;; we also do not modify visibility in this case
8832 buffer)
8833 (t ; make a new indirect buffer for displaying the link
8834 (let* ((bn (buffer-name buffer))
8835 (ibn (concat bn "(Clone)"))
8836 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8837 (with-current-buffer ib (org-overview))
8838 ib))))
8840 (defun org-do-occur (regexp &optional cleanup)
8841 "Call the Emacs command `occur'.
8842 If CLEANUP is non-nil, remove the printout of the regular expression
8843 in the *Occur* buffer. This is useful if the regex is long and not useful
8844 to read."
8845 (occur regexp)
8846 (when cleanup
8847 (let ((cwin (selected-window)) win beg end)
8848 (when (setq win (get-buffer-window "*Occur*"))
8849 (select-window win))
8850 (goto-char (point-min))
8851 (when (re-search-forward "match[a-z]+" nil t)
8852 (setq beg (match-end 0))
8853 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8854 (setq end (1- (match-beginning 0)))))
8855 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8856 (goto-char (point-min))
8857 (select-window cwin))))
8859 ;;; The mark ring for links jumps
8861 (defvar org-mark-ring nil
8862 "Mark ring for positions before jumps in Org-mode.")
8863 (defvar org-mark-ring-last-goto nil
8864 "Last position in the mark ring used to go back.")
8865 ;; Fill and close the ring
8866 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8867 (loop for i from 1 to org-mark-ring-length do
8868 (push (make-marker) org-mark-ring))
8869 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8870 org-mark-ring)
8872 (defun org-mark-ring-push (&optional pos buffer)
8873 "Put the current position or POS into the mark ring and rotate it."
8874 (interactive)
8875 (setq pos (or pos (point)))
8876 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8877 (move-marker (car org-mark-ring)
8878 (or pos (point))
8879 (or buffer (current-buffer)))
8880 (message "%s"
8881 (substitute-command-keys
8882 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8884 (defun org-mark-ring-goto (&optional n)
8885 "Jump to the previous position in the mark ring.
8886 With prefix arg N, jump back that many stored positions. When
8887 called several times in succession, walk through the entire ring.
8888 Org-mode commands jumping to a different position in the current file,
8889 or to another Org-mode file, automatically push the old position
8890 onto the ring."
8891 (interactive "p")
8892 (let (p m)
8893 (if (eq last-command this-command)
8894 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8895 (setq p org-mark-ring))
8896 (setq org-mark-ring-last-goto p)
8897 (setq m (car p))
8898 (switch-to-buffer (marker-buffer m))
8899 (goto-char m)
8900 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8902 (defun org-remove-angle-brackets (s)
8903 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8904 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8906 (defun org-add-angle-brackets (s)
8907 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8908 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8910 (defun org-remove-double-quotes (s)
8911 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8912 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8915 ;;; Following specific links
8917 (defun org-follow-timestamp-link ()
8918 (cond
8919 ((org-at-date-range-p t)
8920 (let ((org-agenda-start-on-weekday)
8921 (t1 (match-string 1))
8922 (t2 (match-string 2)))
8923 (setq t1 (time-to-days (org-time-string-to-time t1))
8924 t2 (time-to-days (org-time-string-to-time t2)))
8925 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8926 ((org-at-timestamp-p t)
8927 (org-agenda-list nil (time-to-days (org-time-string-to-time
8928 (substring (match-string 1) 0 10)))
8930 (t (error "This should not happen"))))
8933 ;;; Following file links
8934 (defvar org-wait nil)
8935 (defun org-open-file (path &optional in-emacs line search)
8936 "Open the file at PATH.
8937 First, this expands any special file name abbreviations. Then the
8938 configuration variable `org-file-apps' is checked if it contains an
8939 entry for this file type, and if yes, the corresponding command is launched.
8941 If no application is found, Emacs simply visits the file.
8943 With optional prefix argument IN-EMACS, Emacs will visit the file.
8944 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8945 and to use an external application to visit the file.
8947 Optional LINE specifies a line to go to, optional SEARCH a string to
8948 search for. If LINE or SEARCH is given, the file will always be
8949 opened in Emacs.
8950 If the file does not exist, an error is thrown."
8951 (setq in-emacs (or in-emacs line search))
8952 (let* ((file (if (equal path "")
8953 buffer-file-name
8954 (substitute-in-file-name (expand-file-name path))))
8955 (apps (append org-file-apps (org-default-apps)))
8956 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8957 (dirp (if remp nil (file-directory-p file)))
8958 (file (if (and dirp org-open-directory-means-index-dot-org)
8959 (concat (file-name-as-directory file) "index.org")
8960 file))
8961 (a-m-a-p (assq 'auto-mode apps))
8962 (dfile (downcase file))
8963 (old-buffer (current-buffer))
8964 (old-pos (point))
8965 (old-mode major-mode)
8966 ext cmd)
8967 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8968 (setq ext (match-string 1 dfile))
8969 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8970 (setq ext (match-string 1 dfile))))
8971 (cond
8972 ((member in-emacs '((16) system))
8973 (setq cmd (cdr (assoc 'system apps))))
8974 (in-emacs (setq cmd 'emacs))
8976 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8977 (and dirp (cdr (assoc 'directory apps)))
8978 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8979 'string-match)
8980 (cdr (assoc ext apps))
8981 (cdr (assoc t apps))))))
8982 (when (eq cmd 'system)
8983 (setq cmd (cdr (assoc 'system apps))))
8984 (when (eq cmd 'default)
8985 (setq cmd (cdr (assoc t apps))))
8986 (when (eq cmd 'mailcap)
8987 (require 'mailcap)
8988 (mailcap-parse-mailcaps)
8989 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8990 (command (mailcap-mime-info mime-type)))
8991 (if (stringp command)
8992 (setq cmd command)
8993 (setq cmd 'emacs))))
8994 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8995 (not (file-exists-p file))
8996 (not org-open-non-existing-files))
8997 (error "No such file: %s" file))
8998 (cond
8999 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9000 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9001 (while (string-match "['\"]%s['\"]" cmd)
9002 (setq cmd (replace-match "%s" t t cmd)))
9003 (while (string-match "%s" cmd)
9004 (setq cmd (replace-match
9005 (save-match-data
9006 (shell-quote-argument
9007 (convert-standard-filename file)))
9008 t t cmd)))
9009 (save-window-excursion
9010 (start-process-shell-command cmd nil cmd)
9011 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9013 ((or (stringp cmd)
9014 (eq cmd 'emacs))
9015 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9016 (widen)
9017 (if line (org-goto-line line)
9018 (if search (org-link-search search))))
9019 ((consp cmd)
9020 (let ((file (convert-standard-filename file)))
9021 (eval cmd)))
9022 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9023 (and (org-mode-p) (eq old-mode 'org-mode)
9024 (or (not (equal old-buffer (current-buffer)))
9025 (not (equal old-pos (point))))
9026 (org-mark-ring-push old-pos old-buffer))))
9028 (defun org-default-apps ()
9029 "Return the default applications for this operating system."
9030 (cond
9031 ((eq system-type 'darwin)
9032 org-file-apps-defaults-macosx)
9033 ((eq system-type 'windows-nt)
9034 org-file-apps-defaults-windowsnt)
9035 (t org-file-apps-defaults-gnu)))
9037 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9038 "Convert extensions to regular expressions in the cars of LIST.
9039 Also, weed out any non-string entries, because the return value is used
9040 only for regexp matching.
9041 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9042 point to the symbol `emacs', indicating that the file should
9043 be opened in Emacs."
9044 (append
9045 (delq nil
9046 (mapcar (lambda (x)
9047 (if (not (stringp (car x)))
9049 (if (string-match "\\W" (car x))
9051 (cons (concat "\\." (car x) "\\'") (cdr x)))))
9052 list))
9053 (if add-auto-mode
9054 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9056 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9057 (defun org-file-remote-p (file)
9058 "Test whether FILE specifies a location on a remote system.
9059 Return non-nil if the location is indeed remote.
9061 For example, the filename \"/user@host:/foo\" specifies a location
9062 on the system \"/user@host:\"."
9063 (cond ((fboundp 'file-remote-p)
9064 (file-remote-p file))
9065 ((fboundp 'tramp-handle-file-remote-p)
9066 (tramp-handle-file-remote-p file))
9067 ((and (boundp 'ange-ftp-name-format)
9068 (string-match (car ange-ftp-name-format) file))
9070 (t nil)))
9073 ;;;; Refiling
9075 (defun org-get-org-file ()
9076 "Read a filename, with default directory `org-directory'."
9077 (let ((default (or org-default-notes-file remember-data-file)))
9078 (read-file-name (format "File name [%s]: " default)
9079 (file-name-as-directory org-directory)
9080 default)))
9082 (defun org-notes-order-reversed-p ()
9083 "Check if the current file should receive notes in reversed order."
9084 (cond
9085 ((not org-reverse-note-order) nil)
9086 ((eq t org-reverse-note-order) t)
9087 ((not (listp org-reverse-note-order)) nil)
9088 (t (catch 'exit
9089 (let ((all org-reverse-note-order)
9090 entry)
9091 (while (setq entry (pop all))
9092 (if (string-match (car entry) buffer-file-name)
9093 (throw 'exit (cdr entry))))
9094 nil)))))
9096 (defvar org-refile-target-table nil
9097 "The list of refile targets, created by `org-refile'.")
9099 (defvar org-agenda-new-buffers nil
9100 "Buffers created to visit agenda files.")
9102 (defun org-get-refile-targets (&optional default-buffer)
9103 "Produce a table with refile targets."
9104 (let ((case-fold-search nil)
9105 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9106 (entries (or org-refile-targets '((nil . (:level . 1)))))
9107 targets txt re files f desc descre fast-path-p level pos0)
9108 (message "Getting targets...")
9109 (with-current-buffer (or default-buffer (current-buffer))
9110 (while (setq entry (pop entries))
9111 (setq files (car entry) desc (cdr entry))
9112 (setq fast-path-p nil)
9113 (cond
9114 ((null files) (setq files (list (current-buffer))))
9115 ((eq files 'org-agenda-files)
9116 (setq files (org-agenda-files 'unrestricted)))
9117 ((and (symbolp files) (fboundp files))
9118 (setq files (funcall files)))
9119 ((and (symbolp files) (boundp files))
9120 (setq files (symbol-value files))))
9121 (if (stringp files) (setq files (list files)))
9122 (cond
9123 ((eq (car desc) :tag)
9124 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9125 ((eq (car desc) :todo)
9126 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9127 ((eq (car desc) :regexp)
9128 (setq descre (cdr desc)))
9129 ((eq (car desc) :level)
9130 (setq descre (concat "^\\*\\{" (number-to-string
9131 (if org-odd-levels-only
9132 (1- (* 2 (cdr desc)))
9133 (cdr desc)))
9134 "\\}[ \t]")))
9135 ((eq (car desc) :maxlevel)
9136 (setq fast-path-p t)
9137 (setq descre (concat "^\\*\\{1," (number-to-string
9138 (if org-odd-levels-only
9139 (1- (* 2 (cdr desc)))
9140 (cdr desc)))
9141 "\\}[ \t]")))
9142 (t (error "Bad refiling target description %s" desc)))
9143 (while (setq f (pop files))
9144 (with-current-buffer
9145 (if (bufferp f) f (org-get-agenda-file-buffer f))
9146 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
9147 (setq f (and f (expand-file-name f)))
9148 (if (eq org-refile-use-outline-path 'file)
9149 (push (list (file-name-nondirectory f) f nil nil) targets))
9150 (save-excursion
9151 (save-restriction
9152 (widen)
9153 (goto-char (point-min))
9154 (while (re-search-forward descre nil t)
9155 (goto-char (setq pos0 (point-at-bol)))
9156 (catch 'next
9157 (when org-refile-target-verify-function
9158 (save-match-data
9159 (or (funcall org-refile-target-verify-function)
9160 (throw 'next t))))
9161 (when (looking-at org-complex-heading-regexp)
9162 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
9163 txt (org-link-display-format (match-string 4))
9164 re (concat "^" (regexp-quote
9165 (buffer-substring (match-beginning 1)
9166 (match-end 4)))))
9167 (if (match-end 5) (setq re (concat re "[ \t]+"
9168 (regexp-quote
9169 (match-string 5)))))
9170 (setq re (concat re "[ \t]*$"))
9171 (when org-refile-use-outline-path
9172 (setq txt (mapconcat 'org-protect-slash
9173 (append
9174 (if (eq org-refile-use-outline-path 'file)
9175 (list (file-name-nondirectory
9176 (buffer-file-name (buffer-base-buffer))))
9177 (if (eq org-refile-use-outline-path 'full-file-path)
9178 (list (buffer-file-name (buffer-base-buffer)))))
9179 (org-get-outline-path fast-path-p level txt)
9180 (list txt))
9181 "/")))
9182 (push (list txt f re (point)) targets)))
9183 (when (= (point) pos0)
9184 ;; verification function has not moved point
9185 (goto-char (point-at-eol))))))))))
9186 (message "Getting targets...done")
9187 (nreverse targets)))
9189 (defun org-protect-slash (s)
9190 (while (string-match "/" s)
9191 (setq s (replace-match "\\" t t s)))
9194 (defvar org-olpa (make-vector 20 nil))
9196 (defun org-get-outline-path (&optional fastp level heading)
9197 "Return the outline path to the current entry, as a list.
9198 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9199 routine which makes outline path derivations for an entire file,
9200 avoiding backtracing."
9201 (if fastp
9202 (progn
9203 (if (> level 19)
9204 (error "Outline path failure, more than 19 levels."))
9205 (loop for i from level upto 19 do
9206 (aset org-olpa i nil))
9207 (prog1
9208 (delq nil (append org-olpa nil))
9209 (aset org-olpa level heading)))
9210 (let (rtn case-fold-search)
9211 (save-excursion
9212 (save-restriction
9213 (widen)
9214 (while (org-up-heading-safe)
9215 (when (looking-at org-complex-heading-regexp)
9216 (push (org-match-string-no-properties 4) rtn)))
9217 rtn)))))
9219 (defun org-format-outline-path (path &optional width prefix)
9220 "Format the outlie path PATH for display.
9221 Width is the maximum number of characters that is available.
9222 Prefix is a prefix to be included in the returned string,
9223 such as the file name."
9224 (setq width (or width 79))
9225 (if prefix (setq width (- width (length prefix))))
9226 (if (not path)
9227 (or prefix "")
9228 (let* ((nsteps (length path))
9229 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9230 (maxwidth (if (<= total-width width)
9231 10000 ;; everything fits
9232 ;; we need to shorten the level headings
9233 (/ (- width nsteps) nsteps)))
9234 (org-odd-levels-only nil)
9235 (n 0)
9236 (total (1+ (length prefix))))
9237 (setq maxwidth (max maxwidth 10))
9238 (concat prefix
9239 (mapconcat
9240 (lambda (h)
9241 (setq n (1+ n))
9242 (if (and (= n nsteps) (< maxwidth 10000))
9243 (setq maxwidth (- total-width total)))
9244 (if (< (length h) maxwidth)
9245 (progn (setq total (+ total (length h) 1)) h)
9246 (setq h (substring h 0 (- maxwidth 2))
9247 total (+ total maxwidth 1))
9248 (if (string-match "[ \t]+\\'" h)
9249 (setq h (substring h 0 (match-beginning 0))))
9250 (setq h (concat h "..")))
9251 (org-add-props h nil 'face
9252 (nth (% (1- n) org-n-level-faces)
9253 org-level-faces))
9255 path "/")))))
9257 (defun org-display-outline-path (&optional file current)
9258 "Display the current outline path in the echo area."
9259 (interactive "P")
9260 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
9261 (case-fold-search nil)
9262 (path (and (org-mode-p) (org-get-outline-path))))
9263 (if current (setq path (append path
9264 (save-excursion
9265 (org-back-to-heading t)
9266 (if (looking-at org-complex-heading-regexp)
9267 (list (match-string 4)))))))
9268 (message "%s"
9269 (org-format-outline-path
9270 path
9271 (1- (frame-width))
9272 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9274 (defvar org-refile-history nil
9275 "History for refiling operations.")
9277 (defvar org-after-refile-insert-hook nil
9278 "Hook run after `org-refile' has inserted its stuff at the new location.
9279 Note that this is still *before* the stuff will be removed from
9280 the *old* location.")
9282 (defun org-refile (&optional goto default-buffer rfloc)
9283 "Move the entry at point to another heading.
9284 The list of target headings is compiled using the information in
9285 `org-refile-targets', which see. This list is created before each use
9286 and will therefore always be up-to-date.
9288 At the target location, the entry is filed as a subitem of the target heading.
9289 Depending on `org-reverse-note-order', the new subitem will either be the
9290 first or the last subitem.
9292 If there is an active region, all entries in that region will be moved.
9293 However, the region must fulfil the requirement that the first heading
9294 is the first one sets the top-level of the moved text - at most siblings
9295 below it are allowed.
9297 With prefix arg GOTO, the command will only visit the target location,
9298 not actually move anything.
9299 With a double prefix `C-u C-u', go to the location where the last refiling
9300 operation has put the subtree.
9301 With a prefix argument of `2', refile to the running clock.
9303 RFLOC can be a refile location obtained in a different way.
9305 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9306 (interactive "P")
9307 (let* ((cbuf (current-buffer))
9308 (regionp (org-region-active-p))
9309 (region-start (and regionp (region-beginning)))
9310 (region-end (and regionp (region-end)))
9311 (region-length (and regionp (- region-end region-start)))
9312 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9313 pos it nbuf file re level reversed)
9314 (setq last-command nil)
9315 (when regionp
9316 (goto-char region-start)
9317 (or (bolp) (goto-char (point-at-bol)))
9318 (setq region-start (point))
9319 (unless (org-kill-is-subtree-p
9320 (buffer-substring region-start region-end))
9321 (error "The region is not a (sequence of) subtree(s)")))
9322 (if (equal goto '(16))
9323 (org-refile-goto-last-stored)
9324 (when (or
9325 (and (equal goto 2)
9326 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9327 (prog1
9328 (setq it (list (or org-clock-heading "running clock")
9329 (buffer-file-name
9330 (marker-buffer org-clock-hd-marker))
9332 (marker-position org-clock-hd-marker)))
9333 (setq goto nil)))
9334 (setq it (or rfloc
9335 (save-excursion
9336 (org-refile-get-location
9337 (if goto "Goto: " "Refile to: ") default-buffer
9338 org-refile-allow-creating-parent-nodes)))))
9339 (setq file (nth 1 it)
9340 re (nth 2 it)
9341 pos (nth 3 it))
9342 (if (and (not goto)
9344 (equal (buffer-file-name) file)
9345 (if regionp
9346 (and (>= pos region-start)
9347 (<= pos region-end))
9348 (and (>= pos (point))
9349 (< pos (save-excursion
9350 (org-end-of-subtree t t))))))
9351 (error "Cannot refile to position inside the tree or region"))
9353 (setq nbuf (or (find-buffer-visiting file)
9354 (find-file-noselect file)))
9355 (if goto
9356 (progn
9357 (switch-to-buffer nbuf)
9358 (goto-char pos)
9359 (org-show-context 'org-goto))
9360 (if regionp
9361 (progn
9362 (org-kill-new (buffer-substring region-start region-end))
9363 (org-save-markers-in-region region-start region-end))
9364 (org-copy-subtree 1 nil t))
9365 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9366 (find-file-noselect file)))
9367 (setq reversed (org-notes-order-reversed-p))
9368 (save-excursion
9369 (save-restriction
9370 (widen)
9371 (if pos
9372 (progn
9373 (goto-char pos)
9374 (looking-at outline-regexp)
9375 (setq level (org-get-valid-level (funcall outline-level) 1))
9376 (goto-char
9377 (if reversed
9378 (or (outline-next-heading) (point-max))
9379 (or (save-excursion (org-get-next-sibling))
9380 (org-end-of-subtree t t)
9381 (point-max)))))
9382 (setq level 1)
9383 (if (not reversed)
9384 (goto-char (point-max))
9385 (goto-char (point-min))
9386 (or (outline-next-heading) (goto-char (point-max)))))
9387 (if (not (bolp)) (newline))
9388 (bookmark-set "org-refile-last-stored")
9389 (org-paste-subtree level)
9390 (if (fboundp 'deactivate-mark) (deactivate-mark))
9391 (run-hooks 'org-after-refile-insert-hook))))
9392 (if regionp
9393 (delete-region (point) (+ (point) region-length))
9394 (org-cut-subtree))
9395 (when (featurep 'org-inlinetask)
9396 (org-inlinetask-remove-END-maybe))
9397 (setq org-markers-to-move nil)
9398 (message "Refiled to \"%s\"" (car it))))))
9399 (org-reveal))
9401 (defun org-refile-goto-last-stored ()
9402 "Go to the location where the last refile was stored."
9403 (interactive)
9404 (bookmark-jump "org-refile-last-stored")
9405 (message "This is the location of the last refile"))
9407 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9408 "Prompt the user for a refile location, using PROMPT."
9409 (let ((org-refile-targets org-refile-targets)
9410 (org-refile-use-outline-path org-refile-use-outline-path))
9411 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9412 (unless org-refile-target-table
9413 (error "No refile targets"))
9414 (let* ((cbuf (current-buffer))
9415 (partial-completion-mode nil)
9416 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9417 (cfunc (if (and org-refile-use-outline-path
9418 org-outline-path-complete-in-steps)
9419 'org-olpath-completing-read
9420 'org-icompleting-read))
9421 (extra (if org-refile-use-outline-path "/" ""))
9422 (filename (and cfn (expand-file-name cfn)))
9423 (tbl (mapcar
9424 (lambda (x)
9425 (if (and (not (member org-refile-use-outline-path
9426 '(file full-file-path)))
9427 (not (equal filename (nth 1 x))))
9428 (cons (concat (car x) extra " ("
9429 (file-name-nondirectory (nth 1 x)) ")")
9430 (cdr x))
9431 (cons (concat (car x) extra) (cdr x))))
9432 org-refile-target-table))
9433 (completion-ignore-case t)
9434 pa answ parent-target child parent old-hist)
9435 (setq old-hist org-refile-history)
9436 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9437 nil 'org-refile-history))
9438 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9439 (if pa
9440 (progn
9441 (when (or (not org-refile-history)
9442 (not (eq old-hist org-refile-history))
9443 (not (equal (car pa) (car org-refile-history))))
9444 (setq org-refile-history
9445 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9446 org-refile-history
9447 (cdr org-refile-history))))
9448 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9449 (pop org-refile-history)))
9451 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9452 (setq parent (match-string 1 answ)
9453 child (match-string 2 answ))
9454 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
9455 (when (and parent-target
9456 (or (eq new-nodes t)
9457 (and (eq new-nodes 'confirm)
9458 (y-or-n-p (format "Create new node \"%s\"? " child)))))
9459 (org-refile-new-child parent-target child))))))
9461 (defun org-refile-new-child (parent-target child)
9462 "Use refile target PARENT-TARGET to add new CHILD below it."
9463 (unless parent-target
9464 (error "Cannot find parent for new node"))
9465 (let ((file (nth 1 parent-target))
9466 (pos (nth 3 parent-target))
9467 level)
9468 (with-current-buffer (or (find-buffer-visiting file)
9469 (find-file-noselect file))
9470 (save-excursion
9471 (save-restriction
9472 (widen)
9473 (if pos
9474 (goto-char pos)
9475 (goto-char (point-max))
9476 (if (not (bolp)) (newline)))
9477 (when (looking-at outline-regexp)
9478 (setq level (funcall outline-level))
9479 (org-end-of-subtree t t))
9480 (org-back-over-empty-lines)
9481 (insert "\n" (make-string
9482 (if pos (org-get-valid-level level 1) 1) ?*)
9483 " " child "\n")
9484 (beginning-of-line 0)
9485 (list (concat (car parent-target) "/" child) file "" (point)))))))
9487 (defun org-olpath-completing-read (prompt collection &rest args)
9488 "Read an outline path like a file name."
9489 (let ((thetable collection)
9490 (org-completion-use-ido nil) ; does not work with ido.
9491 (org-completion-use-iswitchb nil)) ; or iswitchb
9492 (apply
9493 'org-icompleting-read prompt
9494 (lambda (string predicate &optional flag)
9495 (let (rtn r f (l (length string)))
9496 (cond
9497 ((eq flag nil)
9498 ;; try completion
9499 (try-completion string thetable))
9500 ((eq flag t)
9501 ;; all-completions
9502 (setq rtn (all-completions string thetable predicate))
9503 (mapcar
9504 (lambda (x)
9505 (setq r (substring x l))
9506 (if (string-match " ([^)]*)$" x)
9507 (setq f (match-string 0 x))
9508 (setq f ""))
9509 (if (string-match "/" r)
9510 (concat string (substring r 0 (match-end 0)) f)
9512 rtn))
9513 ((eq flag 'lambda)
9514 ;; exact match?
9515 (assoc string thetable)))
9517 args)))
9519 ;;;; Dynamic blocks
9521 (defun org-find-dblock (name)
9522 "Find the first dynamic block with name NAME in the buffer.
9523 If not found, stay at current position and return nil."
9524 (let (pos)
9525 (save-excursion
9526 (goto-char (point-min))
9527 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9528 nil t)
9529 (match-beginning 0))))
9530 (if pos (goto-char pos))
9531 pos))
9533 (defconst org-dblock-start-re
9534 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9535 "Matches the start line of a dynamic block, with parameters.")
9537 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9538 "Matches the end of a dynamic block.")
9540 (defun org-create-dblock (plist)
9541 "Create a dynamic block section, with parameters taken from PLIST.
9542 PLIST must contain a :name entry which is used as name of the block."
9543 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9544 (end-of-line 1)
9545 (newline))
9546 (let ((col (current-column))
9547 (name (plist-get plist :name)))
9548 (insert "#+BEGIN: " name)
9549 (while plist
9550 (if (eq (car plist) :name)
9551 (setq plist (cddr plist))
9552 (insert " " (prin1-to-string (pop plist)))))
9553 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9554 (beginning-of-line -2)))
9556 (defun org-prepare-dblock ()
9557 "Prepare dynamic block for refresh.
9558 This empties the block, puts the cursor at the insert position and returns
9559 the property list including an extra property :name with the block name."
9560 (unless (looking-at org-dblock-start-re)
9561 (error "Not at a dynamic block"))
9562 (let* ((begdel (1+ (match-end 0)))
9563 (name (org-no-properties (match-string 1)))
9564 (params (append (list :name name)
9565 (read (concat "(" (match-string 3) ")")))))
9566 (save-excursion
9567 (beginning-of-line 1)
9568 (skip-chars-forward " \t")
9569 (setq params (plist-put params :indentation-column (current-column))))
9570 (unless (re-search-forward org-dblock-end-re nil t)
9571 (error "Dynamic block not terminated"))
9572 (setq params
9573 (append params
9574 (list :content (buffer-substring
9575 begdel (match-beginning 0)))))
9576 (delete-region begdel (match-beginning 0))
9577 (goto-char begdel)
9578 (open-line 1)
9579 params))
9581 (defun org-map-dblocks (&optional command)
9582 "Apply COMMAND to all dynamic blocks in the current buffer.
9583 If COMMAND is not given, use `org-update-dblock'."
9584 (let ((cmd (or command 'org-update-dblock))
9585 pos)
9586 (save-excursion
9587 (goto-char (point-min))
9588 (while (re-search-forward org-dblock-start-re nil t)
9589 (goto-char (setq pos (match-beginning 0)))
9590 (condition-case nil
9591 (funcall cmd)
9592 (error (message "Error during update of dynamic block")))
9593 (goto-char pos)
9594 (unless (re-search-forward org-dblock-end-re nil t)
9595 (error "Dynamic block not terminated"))))))
9597 (defun org-dblock-update (&optional arg)
9598 "User command for updating dynamic blocks.
9599 Update the dynamic block at point. With prefix ARG, update all dynamic
9600 blocks in the buffer."
9601 (interactive "P")
9602 (if arg
9603 (org-update-all-dblocks)
9604 (or (looking-at org-dblock-start-re)
9605 (org-beginning-of-dblock))
9606 (org-update-dblock)))
9608 (defun org-update-dblock ()
9609 "Update the dynamic block at point
9610 This means to empty the block, parse for parameters and then call
9611 the correct writing function."
9612 (save-window-excursion
9613 (let* ((pos (point))
9614 (line (org-current-line))
9615 (params (org-prepare-dblock))
9616 (name (plist-get params :name))
9617 (indent (plist-get params :indentation-column))
9618 (cmd (intern (concat "org-dblock-write:" name))))
9619 (message "Updating dynamic block `%s' at line %d..." name line)
9620 (funcall cmd params)
9621 (message "Updating dynamic block `%s' at line %d...done" name line)
9622 (goto-char pos)
9623 (when (and indent (> indent 0))
9624 (setq indent (make-string indent ?\ ))
9625 (save-excursion
9626 (org-beginning-of-dblock)
9627 (forward-line 1)
9628 (while (not (looking-at org-dblock-end-re))
9629 (insert indent)
9630 (beginning-of-line 2))
9631 (when (looking-at org-dblock-end-re)
9632 (and (looking-at "[ \t]+")
9633 (replace-match ""))
9634 (insert indent)))))))
9636 (defun org-beginning-of-dblock ()
9637 "Find the beginning of the dynamic block at point.
9638 Error if there is no such block at point."
9639 (let ((pos (point))
9640 beg)
9641 (end-of-line 1)
9642 (if (and (re-search-backward org-dblock-start-re nil t)
9643 (setq beg (match-beginning 0))
9644 (re-search-forward org-dblock-end-re nil t)
9645 (> (match-end 0) pos))
9646 (goto-char beg)
9647 (goto-char pos)
9648 (error "Not in a dynamic block"))))
9650 (defun org-update-all-dblocks ()
9651 "Update all dynamic blocks in the buffer.
9652 This function can be used in a hook."
9653 (when (org-mode-p)
9654 (org-map-dblocks 'org-update-dblock)))
9657 ;;;; Completion
9659 (defconst org-additional-option-like-keywords
9660 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9661 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9662 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
9663 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
9664 "BEGIN:" "END:"
9665 "ORGTBL" "TBLFM:" "TBLNAME:"
9666 "BEGIN_EXAMPLE" "END_EXAMPLE"
9667 "BEGIN_QUOTE" "END_QUOTE"
9668 "BEGIN_VERSE" "END_VERSE"
9669 "BEGIN_CENTER" "END_CENTER"
9670 "BEGIN_SRC" "END_SRC"
9671 "CATEGORY" "COLUMNS"
9672 "CAPTION" "LABEL"
9673 "SETUPFILE"
9674 "BIND"
9675 "MACRO"))
9677 (defcustom org-structure-template-alist
9679 ("s" "#+begin_src ?\n\n#+end_src"
9680 "<src lang=\"?\">\n\n</src>")
9681 ("e" "#+begin_example\n?\n#+end_example"
9682 "<example>\n?\n</example>")
9683 ("q" "#+begin_quote\n?\n#+end_quote"
9684 "<quote>\n?\n</quote>")
9685 ("v" "#+begin_verse\n?\n#+end_verse"
9686 "<verse>\n?\n/verse>")
9687 ("c" "#+begin_center\n?\n#+end_center"
9688 "<center>\n?\n/center>")
9689 ("l" "#+begin_latex\n?\n#+end_latex"
9690 "<literal style=\"latex\">\n?\n</literal>")
9691 ("L" "#+latex: "
9692 "<literal style=\"latex\">?</literal>")
9693 ("h" "#+begin_html\n?\n#+end_html"
9694 "<literal style=\"html\">\n?\n</literal>")
9695 ("H" "#+html: "
9696 "<literal style=\"html\">?</literal>")
9697 ("a" "#+begin_ascii\n?\n#+end_ascii")
9698 ("A" "#+ascii: ")
9699 ("i" "#+include %file ?"
9700 "<include file=%file markup=\"?\">")
9702 "Structure completion elements.
9703 This is a list of abbreviation keys and values. The value gets inserted
9704 it you type @samp{.} followed by the key and then the completion key,
9705 usually `M-TAB'. %file will be replaced by a file name after prompting
9706 for the file using completion.
9707 There are two templates for each key, the first uses the original Org syntax,
9708 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9709 the default when the /org-mtags.el/ module has been loaded. See also the
9710 variable `org-mtags-prefer-muse-templates'.
9711 This is an experimental feature, it is undecided if it is going to stay in."
9712 :group 'org-completion
9713 :type '(repeat
9714 (string :tag "Key")
9715 (string :tag "Template")
9716 (string :tag "Muse Template")))
9718 (defun org-try-structure-completion ()
9719 "Try to complete a structure template before point.
9720 This looks for strings like \"<e\" on an otherwise empty line and
9721 expands them."
9722 (let ((l (buffer-substring (point-at-bol) (point)))
9724 (when (and (looking-at "[ \t]*$")
9725 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9726 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9727 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9728 (match-beginning 1)) a)
9729 t)))
9731 (defun org-complete-expand-structure-template (start cell)
9732 "Expand a structure template."
9733 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9734 (rpl (nth (if musep 2 1) cell))
9735 (ind ""))
9736 (delete-region start (point))
9737 (when (string-match "\\`#\\+" rpl)
9738 (cond
9739 ((bolp))
9740 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9741 (setq ind (buffer-substring (point-at-bol) (point))))
9742 (t (newline))))
9743 (setq start (point))
9744 (if (string-match "%file" rpl)
9745 (setq rpl (replace-match
9746 (concat
9747 "\""
9748 (save-match-data
9749 (abbreviate-file-name (read-file-name "Include file: ")))
9750 "\"")
9751 t t rpl)))
9752 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9753 (concat "\n" ind)))
9754 (insert rpl)
9755 (if (re-search-backward "\\?" start t) (delete-char 1))))
9758 (defun org-complete (&optional arg)
9759 "Perform completion on word at point.
9760 At the beginning of a headline, this completes TODO keywords as given in
9761 `org-todo-keywords'.
9762 If the current word is preceded by a backslash, completes the TeX symbols
9763 that are supported for HTML support.
9764 If the current word is preceded by \"#+\", completes special words for
9765 setting file options.
9766 In the line after \"#+STARTUP:, complete valid keywords.\"
9767 At all other locations, this simply calls the value of
9768 `org-completion-fallback-command'."
9769 (interactive "P")
9770 (org-without-partial-completion
9771 (catch 'exit
9772 (let* ((a nil)
9773 (end (point))
9774 (beg1 (save-excursion
9775 (skip-chars-backward (org-re "[:alnum:]_@"))
9776 (point)))
9777 (beg (save-excursion
9778 (skip-chars-backward "a-zA-Z0-9_:$")
9779 (point)))
9780 (confirm (lambda (x) (stringp (car x))))
9781 (searchhead (equal (char-before beg) ?*))
9782 (struct
9783 (when (and (member (char-before beg1) '(?. ?<))
9784 (setq a (assoc (buffer-substring beg1 (point))
9785 org-structure-template-alist)))
9786 (org-complete-expand-structure-template (1- beg1) a)
9787 (throw 'exit t)))
9788 (tag (and (equal (char-before beg1) ?:)
9789 (equal (char-after (point-at-bol)) ?*)))
9790 (prop (and (equal (char-before beg1) ?:)
9791 (not (equal (char-after (point-at-bol)) ?*))))
9792 (texp (equal (char-before beg) ?\\))
9793 (link (equal (char-before beg) ?\[))
9794 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9795 beg)
9796 "#+"))
9797 (startup (string-match "^#\\+STARTUP:.*"
9798 (buffer-substring (point-at-bol) (point))))
9799 (completion-ignore-case opt)
9800 (type nil)
9801 (tbl nil)
9802 (table (cond
9803 (opt
9804 (setq type :opt)
9805 (require 'org-exp)
9806 (append
9807 (delq nil
9808 (mapcar
9809 (lambda (x)
9810 (if (string-match
9811 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9812 (cons (match-string 2 x)
9813 (match-string 1 x))))
9814 (org-split-string (org-get-current-options) "\n")))
9815 (mapcar 'list org-additional-option-like-keywords)))
9816 (startup
9817 (setq type :startup)
9818 org-startup-options)
9819 (link (append org-link-abbrev-alist-local
9820 org-link-abbrev-alist))
9821 (texp
9822 (setq type :tex)
9823 org-html-entities)
9824 ((string-match "\\`\\*+[ \t]+\\'"
9825 (buffer-substring (point-at-bol) beg))
9826 (setq type :todo)
9827 (mapcar 'list org-todo-keywords-1))
9828 (searchhead
9829 (setq type :searchhead)
9830 (save-excursion
9831 (goto-char (point-min))
9832 (while (re-search-forward org-todo-line-regexp nil t)
9833 (push (list
9834 (org-make-org-heading-search-string
9835 (match-string 3) t))
9836 tbl)))
9837 tbl)
9838 (tag (setq type :tag beg beg1)
9839 (or org-tag-alist (org-get-buffer-tags)))
9840 (prop (setq type :prop beg beg1)
9841 (mapcar 'list (org-buffer-property-keys nil t t)))
9842 (t (progn
9843 (call-interactively org-completion-fallback-command)
9844 (throw 'exit nil)))))
9845 (pattern (buffer-substring-no-properties beg end))
9846 (completion (try-completion pattern table confirm)))
9847 (cond ((eq completion t)
9848 (if (not (assoc (upcase pattern) table))
9849 (message "Already complete")
9850 (if (and (equal type :opt)
9851 (not (member (car (assoc (upcase pattern) table))
9852 org-additional-option-like-keywords)))
9853 (insert (substring (cdr (assoc (upcase pattern) table))
9854 (length pattern)))
9855 (if (memq type '(:tag :prop)) (insert ":")))))
9856 ((null completion)
9857 (message "Can't find completion for \"%s\"" pattern)
9858 (ding))
9859 ((not (string= pattern completion))
9860 (delete-region beg end)
9861 (if (string-match " +$" completion)
9862 (setq completion (replace-match "" t t completion)))
9863 (insert completion)
9864 (if (get-buffer-window "*Completions*")
9865 (delete-window (get-buffer-window "*Completions*")))
9866 (if (assoc completion table)
9867 (if (eq type :todo) (insert " ")
9868 (if (memq type '(:tag :prop)) (insert ":"))))
9869 (if (and (equal type :opt) (assoc completion table))
9870 (message "%s" (substitute-command-keys
9871 "Press \\[org-complete] again to insert example settings"))))
9873 (message "Making completion list...")
9874 (let ((list (sort (all-completions pattern table confirm)
9875 'string<)))
9876 (with-output-to-temp-buffer "*Completions*"
9877 (condition-case nil
9878 ;; Protection needed for XEmacs and emacs 21
9879 (display-completion-list list pattern)
9880 (error (display-completion-list list)))))
9881 (message "Making completion list...%s" "done")))))))
9883 ;;;; TODO, DEADLINE, Comments
9885 (defun org-toggle-comment ()
9886 "Change the COMMENT state of an entry."
9887 (interactive)
9888 (save-excursion
9889 (org-back-to-heading)
9890 (let (case-fold-search)
9891 (if (looking-at (concat outline-regexp
9892 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9893 (replace-match "" t t nil 1)
9894 (if (looking-at outline-regexp)
9895 (progn
9896 (goto-char (match-end 0))
9897 (insert org-comment-string " ")))))))
9899 (defvar org-last-todo-state-is-todo nil
9900 "This is non-nil when the last TODO state change led to a TODO state.
9901 If the last change removed the TODO tag or switched to DONE, then
9902 this is nil.")
9904 (defvar org-setting-tags nil) ; dynamically skipped
9906 (defun org-parse-local-options (string var)
9907 "Parse STRING for startup setting relevant for variable VAR."
9908 (let ((rtn (symbol-value var))
9909 e opts)
9910 (save-match-data
9911 (if (or (not string) (not (string-match "\\S-" string)))
9913 (setq opts (delq nil (mapcar (lambda (x)
9914 (setq e (assoc x org-startup-options))
9915 (if (eq (nth 1 e) var) e nil))
9916 (org-split-string string "[ \t]+"))))
9917 (if (not opts)
9919 (setq rtn nil)
9920 (while (setq e (pop opts))
9921 (if (not (nth 3 e))
9922 (setq rtn (nth 2 e))
9923 (if (not (listp rtn)) (setq rtn nil))
9924 (push (nth 2 e) rtn)))
9925 rtn)))))
9927 (defvar org-todo-setup-filter-hook nil
9928 "Hook for functions that pre-filter todo specs.
9930 Each function takes a todo spec and returns either `nil' or the spec
9931 transformed into canonical form." )
9933 (defvar org-todo-get-default-hook nil
9934 "Hook for functions that get a default item for todo.
9936 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9937 `nil' or a string to be used for the todo mark." )
9939 (defvar org-agenda-headline-snapshot-before-repeat)
9941 (defun org-todo (&optional arg)
9942 "Change the TODO state of an item.
9943 The state of an item is given by a keyword at the start of the heading,
9944 like
9945 *** TODO Write paper
9946 *** DONE Call mom
9948 The different keywords are specified in the variable `org-todo-keywords'.
9949 By default the available states are \"TODO\" and \"DONE\".
9950 So for this example: when the item starts with TODO, it is changed to DONE.
9951 When it starts with DONE, the DONE is removed. And when neither TODO nor
9952 DONE are present, add TODO at the beginning of the heading.
9954 With C-u prefix arg, use completion to determine the new state.
9955 With numeric prefix arg, switch to that state.
9956 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9957 With a triple C-u prefix, circumvent any state blocking.
9959 For calling through lisp, arg is also interpreted in the following way:
9960 'none -> empty state
9961 \"\"(empty string) -> switch to empty state
9962 'done -> switch to DONE
9963 'nextset -> switch to the next set of keywords
9964 'previousset -> switch to the previous set of keywords
9965 \"WAITING\" -> switch to the specified keyword, but only if it
9966 really is a member of `org-todo-keywords'."
9967 (interactive "P")
9968 (if (equal arg '(16)) (setq arg 'nextset))
9969 (let ((org-blocker-hook org-blocker-hook)
9970 (case-fold-search nil))
9971 (when (equal arg '(64))
9972 (setq arg nil org-blocker-hook nil))
9973 (when (and org-blocker-hook
9974 (or org-inhibit-blocking
9975 (org-entry-get nil "NOBLOCKING")))
9976 (setq org-blocker-hook nil))
9977 (save-excursion
9978 (catch 'exit
9979 (org-back-to-heading t)
9980 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9981 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9982 (looking-at " *"))
9983 (let* ((match-data (match-data))
9984 (startpos (point-at-bol))
9985 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9986 (org-log-done org-log-done)
9987 (org-log-repeat org-log-repeat)
9988 (org-todo-log-states org-todo-log-states)
9989 (this (match-string 1))
9990 (hl-pos (match-beginning 0))
9991 (head (org-get-todo-sequence-head this))
9992 (ass (assoc head org-todo-kwd-alist))
9993 (interpret (nth 1 ass))
9994 (done-word (nth 3 ass))
9995 (final-done-word (nth 4 ass))
9996 (last-state (or this ""))
9997 (completion-ignore-case t)
9998 (member (member this org-todo-keywords-1))
9999 (tail (cdr member))
10000 (state (cond
10001 ((and org-todo-key-trigger
10002 (or (and (equal arg '(4))
10003 (eq org-use-fast-todo-selection 'prefix))
10004 (and (not arg) org-use-fast-todo-selection
10005 (not (eq org-use-fast-todo-selection
10006 'prefix)))))
10007 ;; Use fast selection
10008 (org-fast-todo-selection))
10009 ((and (equal arg '(4))
10010 (or (not org-use-fast-todo-selection)
10011 (not org-todo-key-trigger)))
10012 ;; Read a state with completion
10013 (org-icompleting-read
10014 "State: " (mapcar (lambda(x) (list x))
10015 org-todo-keywords-1)
10016 nil t))
10017 ((eq arg 'right)
10018 (if this
10019 (if tail (car tail) nil)
10020 (car org-todo-keywords-1)))
10021 ((eq arg 'left)
10022 (if (equal member org-todo-keywords-1)
10024 (if this
10025 (nth (- (length org-todo-keywords-1)
10026 (length tail) 2)
10027 org-todo-keywords-1)
10028 (org-last org-todo-keywords-1))))
10029 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10030 (setq arg nil))) ; hack to fall back to cycling
10031 (arg
10032 ;; user or caller requests a specific state
10033 (cond
10034 ((equal arg "") nil)
10035 ((eq arg 'none) nil)
10036 ((eq arg 'done) (or done-word (car org-done-keywords)))
10037 ((eq arg 'nextset)
10038 (or (car (cdr (member head org-todo-heads)))
10039 (car org-todo-heads)))
10040 ((eq arg 'previousset)
10041 (let ((org-todo-heads (reverse org-todo-heads)))
10042 (or (car (cdr (member head org-todo-heads)))
10043 (car org-todo-heads))))
10044 ((car (member arg org-todo-keywords-1)))
10045 ((stringp arg)
10046 (error "State `%s' not valid in this file" arg))
10047 ((nth (1- (prefix-numeric-value arg))
10048 org-todo-keywords-1))))
10049 ((null member) (or head (car org-todo-keywords-1)))
10050 ((equal this final-done-word) nil) ;; -> make empty
10051 ((null tail) nil) ;; -> first entry
10052 ((memq interpret '(type priority))
10053 (if (eq this-command last-command)
10054 (car tail)
10055 (if (> (length tail) 0)
10056 (or done-word (car org-done-keywords))
10057 nil)))
10059 (car tail))))
10060 (state (or
10061 (run-hook-with-args-until-success
10062 'org-todo-get-default-hook state last-state)
10063 state))
10064 (next (if state (concat " " state " ") " "))
10065 (change-plist (list :type 'todo-state-change :from this :to state
10066 :position startpos))
10067 dolog now-done-p)
10068 (when org-blocker-hook
10069 (setq org-last-todo-state-is-todo
10070 (not (member this org-done-keywords)))
10071 (unless (save-excursion
10072 (save-match-data
10073 (run-hook-with-args-until-failure
10074 'org-blocker-hook change-plist)))
10075 (if (interactive-p)
10076 (error "TODO state change from %s to %s blocked" this state)
10077 ;; fail silently
10078 (message "TODO state change from %s to %s blocked" this state)
10079 (throw 'exit nil))))
10080 (store-match-data match-data)
10081 (replace-match next t t)
10082 (unless (pos-visible-in-window-p hl-pos)
10083 (message "TODO state changed to %s" (org-trim next)))
10084 (unless head
10085 (setq head (org-get-todo-sequence-head state)
10086 ass (assoc head org-todo-kwd-alist)
10087 interpret (nth 1 ass)
10088 done-word (nth 3 ass)
10089 final-done-word (nth 4 ass)))
10090 (when (memq arg '(nextset previousset))
10091 (message "Keyword-Set %d/%d: %s"
10092 (- (length org-todo-sets) -1
10093 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10094 (length org-todo-sets)
10095 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10096 (setq org-last-todo-state-is-todo
10097 (not (member state org-done-keywords)))
10098 (setq now-done-p (and (member state org-done-keywords)
10099 (not (member this org-done-keywords))))
10100 (and logging (org-local-logging logging))
10101 (when (and (or org-todo-log-states org-log-done)
10102 (not (eq org-inhibit-logging t))
10103 (not (memq arg '(nextset previousset))))
10104 ;; we need to look at recording a time and note
10105 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10106 (nth 2 (assoc this org-todo-log-states))))
10107 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10108 (setq dolog 'time))
10109 (when (and state
10110 (member state org-not-done-keywords)
10111 (not (member this org-not-done-keywords)))
10112 ;; This is now a todo state and was not one before
10113 ;; If there was a CLOSED time stamp, get rid of it.
10114 (org-add-planning-info nil nil 'closed))
10115 (when (and now-done-p org-log-done)
10116 ;; It is now done, and it was not done before
10117 (org-add-planning-info 'closed (org-current-time))
10118 (if (and (not dolog) (eq 'note org-log-done))
10119 (org-add-log-setup 'done state this 'findpos 'note)))
10120 (when (and state dolog)
10121 ;; This is a non-nil state, and we need to log it
10122 (org-add-log-setup 'state state this 'findpos dolog)))
10123 ;; Fixup tag positioning
10124 (org-todo-trigger-tag-changes state)
10125 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10126 (when org-provide-todo-statistics
10127 (org-update-parent-todo-statistics))
10128 (run-hooks 'org-after-todo-state-change-hook)
10129 (if (and arg (not (member state org-done-keywords)))
10130 (setq head (org-get-todo-sequence-head state)))
10131 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10132 ;; Do we need to trigger a repeat?
10133 (when now-done-p
10134 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10135 ;; This is for the agenda, take a snapshot of the headline.
10136 (save-match-data
10137 (setq org-agenda-headline-snapshot-before-repeat
10138 (org-get-heading))))
10139 (org-auto-repeat-maybe state))
10140 ;; Fixup cursor location if close to the keyword
10141 (if (and (outline-on-heading-p)
10142 (not (bolp))
10143 (save-excursion (beginning-of-line 1)
10144 (looking-at org-todo-line-regexp))
10145 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10146 (progn
10147 (goto-char (or (match-end 2) (match-end 1)))
10148 (and (looking-at " ") (just-one-space))))
10149 (when org-trigger-hook
10150 (save-excursion
10151 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10153 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10154 "Block turning an entry into a TODO, using the hierarchy.
10155 This checks whether the current task should be blocked from state
10156 changes. Such blocking occurs when:
10158 1. The task has children which are not all in a completed state.
10160 2. A task has a parent with the property :ORDERED:, and there
10161 are siblings prior to the current task with incomplete
10162 status.
10164 3. The parent of the task is blocked because it has siblings that should
10165 be done first, or is child of a block grandparent TODO entry."
10167 (if (not org-enforce-todo-dependencies)
10168 t ; if locally turned off don't block
10169 (catch 'dont-block
10170 ;; If this is not a todo state change, or if this entry is already DONE,
10171 ;; do not block
10172 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10173 (member (plist-get change-plist :from)
10174 (cons 'done org-done-keywords))
10175 (member (plist-get change-plist :to)
10176 (cons 'todo org-not-done-keywords))
10177 (not (plist-get change-plist :to)))
10178 (throw 'dont-block t))
10179 ;; If this task has children, and any are undone, it's blocked
10180 (save-excursion
10181 (org-back-to-heading t)
10182 (let ((this-level (funcall outline-level)))
10183 (outline-next-heading)
10184 (let ((child-level (funcall outline-level)))
10185 (while (and (not (eobp))
10186 (> child-level this-level))
10187 ;; this todo has children, check whether they are all
10188 ;; completed
10189 (if (and (not (org-entry-is-done-p))
10190 (org-entry-is-todo-p))
10191 (throw 'dont-block nil))
10192 (outline-next-heading)
10193 (setq child-level (funcall outline-level))))))
10194 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10195 ;; any previous siblings are undone, it's blocked
10196 (save-excursion
10197 (org-back-to-heading t)
10198 (let* ((pos (point))
10199 (parent-pos (and (org-up-heading-safe) (point))))
10200 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10201 (when (and (org-entry-get (point) "ORDERED")
10202 (forward-line 1)
10203 (re-search-forward org-not-done-heading-regexp pos t))
10204 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10205 ;; Search further up the hierarchy, to see if an anchestor is blocked
10206 (while t
10207 (goto-char parent-pos)
10208 (if (not (looking-at org-not-done-heading-regexp))
10209 (throw 'dont-block t)) ; do not block, parent is not a TODO
10210 (setq pos (point))
10211 (setq parent-pos (and (org-up-heading-safe) (point)))
10212 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10213 (when (and (org-entry-get (point) "ORDERED")
10214 (forward-line 1)
10215 (re-search-forward org-not-done-heading-regexp pos t))
10216 (throw 'dont-block nil)))))))) ; block, older sibling not done.
10218 (defcustom org-track-ordered-property-with-tag nil
10219 "Should the ORDERED property also be shown as a tag?
10220 The ORDERED property decides if an entry should require subtasks to be
10221 completed in sequence. Since a property is not very visible, setting
10222 this option means that toggling the ORDERED property with the command
10223 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10224 not relevant for the behavior, but it makes things more visible.
10226 Note that toggling the tag with tags commands will not change the property
10227 and therefore not influence behavior!
10229 This can be t, meaning the tag ORDERED should be used, It can also be a
10230 string to select a different tag for this task."
10231 :group 'org-todo
10232 :type '(choice
10233 (const :tag "No tracking" nil)
10234 (const :tag "Track with ORDERED tag" t)
10235 (string :tag "Use other tag")))
10237 (defun org-toggle-ordered-property ()
10238 "Toggle the ORDERED property of the current entry.
10239 For better visibility, you can track the value of this property with a tag.
10240 See variable `org-track-ordered-property-with-tag'."
10241 (interactive)
10242 (let* ((t1 org-track-ordered-property-with-tag)
10243 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10244 (save-excursion
10245 (org-back-to-heading)
10246 (if (org-entry-get nil "ORDERED")
10247 (progn
10248 (org-delete-property "ORDERED")
10249 (and tag (org-toggle-tag tag 'off))
10250 (message "Subtasks can be completed in arbitrary order"))
10251 (org-entry-put nil "ORDERED" "t")
10252 (and tag (org-toggle-tag tag 'on))
10253 (message "Subtasks must be completed in sequence")))))
10255 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10256 (defun org-block-todo-from-checkboxes (change-plist)
10257 "Block turning an entry into a TODO, using checkboxes.
10258 This checks whether the current task should be blocked from state
10259 changes because there are unchecked boxes in this entry."
10260 (if (not org-enforce-todo-checkbox-dependencies)
10261 t ; if locally turned off don't block
10262 (catch 'dont-block
10263 ;; If this is not a todo state change, or if this entry is already DONE,
10264 ;; do not block
10265 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10266 (member (plist-get change-plist :from)
10267 (cons 'done org-done-keywords))
10268 (member (plist-get change-plist :to)
10269 (cons 'todo org-not-done-keywords))
10270 (not (plist-get change-plist :to)))
10271 (throw 'dont-block t))
10272 ;; If this task has checkboxes that are not checked, it's blocked
10273 (save-excursion
10274 (org-back-to-heading t)
10275 (let ((beg (point)) end)
10276 (outline-next-heading)
10277 (setq end (point))
10278 (goto-char beg)
10279 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10280 end t)
10281 (progn
10282 (if (boundp 'org-blocked-by-checkboxes)
10283 (setq org-blocked-by-checkboxes t))
10284 (throw 'dont-block nil)))))
10285 t))) ; do not block
10287 (defun org-entry-blocked-p ()
10288 "Is the current entry blocked?"
10289 (if (org-entry-get nil "NOBLOCKING")
10290 nil ;; Never block this entry
10291 (not
10292 (run-hook-with-args-until-failure
10293 'org-blocker-hook
10294 (list :type 'todo-state-change
10295 :position (point)
10296 :from 'todo
10297 :to 'done)))))
10299 (defun org-update-statistics-cookies (all)
10300 "Update the statistics cookie, either from TODO or from checkboxes.
10301 This should be called with the cursor in a line with a statistics cookie."
10302 (interactive "P")
10303 (if all
10304 (progn
10305 (org-update-checkbox-count 'all)
10306 (org-map-entries 'org-update-parent-todo-statistics))
10307 (if (not (org-on-heading-p))
10308 (org-update-checkbox-count)
10309 (let ((pos (move-marker (make-marker) (point)))
10310 end l1 l2)
10311 (ignore-errors (org-back-to-heading t))
10312 (if (not (org-on-heading-p))
10313 (org-update-checkbox-count)
10314 (setq l1 (org-outline-level))
10315 (setq end (save-excursion
10316 (outline-next-heading)
10317 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10318 (point)))
10319 (if (and (save-excursion
10320 (re-search-forward
10321 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
10322 (not (save-excursion (re-search-forward
10323 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10324 (org-update-checkbox-count)
10325 (if (and l2 (> l2 l1))
10326 (progn
10327 (goto-char end)
10328 (org-update-parent-todo-statistics))
10329 (goto-char pos)
10330 (beginning-of-line 1)
10331 (while (re-search-forward
10332 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
10333 (point-at-eol) t)
10334 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
10335 (goto-char pos)
10336 (move-marker pos nil)))))
10338 (defvar org-entry-property-inherited-from) ;; defined below
10339 (defun org-update-parent-todo-statistics ()
10340 "Update any statistics cookie in the parent of the current headline.
10341 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10342 the entire subtree and this will travel up the hierarchy and update
10343 statistics everywhere."
10344 (interactive)
10345 (let* ((lim 0) prop
10346 (recursive (or (not org-hierarchical-todo-statistics)
10347 (string-match
10348 "\\<recursive\\>"
10349 (or (setq prop (org-entry-get
10350 nil "COOKIE_DATA" 'inherit)) ""))))
10351 (lim (or (and prop (marker-position
10352 org-entry-property-inherited-from))
10353 lim))
10354 (first t)
10355 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10356 level ltoggle l1 new ndel
10357 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10358 (catch 'exit
10359 (save-excursion
10360 (beginning-of-line 1)
10361 (if (org-at-heading-p)
10362 (setq ltoggle (funcall outline-level))
10363 (error "This should not happen"))
10364 (while (and (setq level (org-up-heading-safe))
10365 (or recursive first)
10366 (>= (point) lim))
10367 (setq first nil cookie-present nil)
10368 (unless (and level
10369 (not (string-match
10370 "\\<checkbox\\>"
10371 (downcase
10372 (or (org-entry-get
10373 nil "COOKIE_DATA")
10374 "")))))
10375 (throw 'exit nil))
10376 (while (re-search-forward box-re (point-at-eol) t)
10377 (setq cnt-all 0 cnt-done 0 cookie-present t)
10378 (setq is-percent (match-end 2))
10379 (save-match-data
10380 (unless (outline-next-heading) (throw 'exit nil))
10381 (while (and (looking-at org-complex-heading-regexp)
10382 (> (setq l1 (length (match-string 1))) level))
10383 (setq kwd (and (or recursive (= l1 ltoggle))
10384 (match-string 2)))
10385 (if (or (eq org-provide-todo-statistics 'all-headlines)
10386 (and (listp org-provide-todo-statistics)
10387 (or (member kwd org-provide-todo-statistics)
10388 (member kwd org-done-keywords))))
10389 (setq cnt-all (1+ cnt-all))
10390 (if (eq org-provide-todo-statistics t)
10391 (and kwd (setq cnt-all (1+ cnt-all)))))
10392 (and (member kwd org-done-keywords)
10393 (setq cnt-done (1+ cnt-done)))
10394 (outline-next-heading)))
10395 (setq new
10396 (if is-percent
10397 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10398 (format "[%d/%d]" cnt-done cnt-all))
10399 ndel (- (match-end 0) (match-beginning 0)))
10400 (goto-char (match-beginning 0))
10401 (insert new)
10402 (delete-region (point) (+ (point) ndel)))
10403 (when cookie-present
10404 (run-hook-with-args 'org-after-todo-statistics-hook
10405 cnt-done (- cnt-all cnt-done))))))
10406 (run-hooks 'org-todo-statistics-hook)))
10408 (defvar org-after-todo-statistics-hook nil
10409 "Hook that is called after a TODO statistics cookie has been updated.
10410 Each function is called with two arguments: the number of not-done entries
10411 and the number of done entries.
10413 For example, the following function, when added to this hook, will switch
10414 an entry to DONE when all children are done, and back to TODO when new
10415 entries are set to a TODO status. Note that this hook is only called
10416 when there is a statistics cookie in the headline!
10418 (defun org-summary-todo (n-done n-not-done)
10419 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10420 (let (org-log-done org-log-states) ; turn off logging
10421 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10424 (defvar org-todo-statistics-hook nil
10425 "Hook that is run whenever Org thinks TODO statistics should be updated.
10426 This hook runs even if there is no statistics cookie present, in which case
10427 `org-after-todo-statistics-hook' would not run.")
10429 (defun org-todo-trigger-tag-changes (state)
10430 "Apply the changes defined in `org-todo-state-tags-triggers'."
10431 (let ((l org-todo-state-tags-triggers)
10432 changes)
10433 (when (or (not state) (equal state ""))
10434 (setq changes (append changes (cdr (assoc "" l)))))
10435 (when (and (stringp state) (> (length state) 0))
10436 (setq changes (append changes (cdr (assoc state l)))))
10437 (when (member state org-not-done-keywords)
10438 (setq changes (append changes (cdr (assoc 'todo l)))))
10439 (when (member state org-done-keywords)
10440 (setq changes (append changes (cdr (assoc 'done l)))))
10441 (dolist (c changes)
10442 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10444 (defun org-local-logging (value)
10445 "Get logging settings from a property VALUE."
10446 (let* (words w a)
10447 ;; directly set the variables, they are already local.
10448 (setq org-log-done nil
10449 org-log-repeat nil
10450 org-todo-log-states nil)
10451 (setq words (org-split-string value))
10452 (while (setq w (pop words))
10453 (cond
10454 ((setq a (assoc w org-startup-options))
10455 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10456 (set (nth 1 a) (nth 2 a))))
10457 ((setq a (org-extract-log-state-settings w))
10458 (and (member (car a) org-todo-keywords-1)
10459 (push a org-todo-log-states)))))))
10461 (defun org-get-todo-sequence-head (kwd)
10462 "Return the head of the TODO sequence to which KWD belongs.
10463 If KWD is not set, check if there is a text property remembering the
10464 right sequence."
10465 (let (p)
10466 (cond
10467 ((not kwd)
10468 (or (get-text-property (point-at-bol) 'org-todo-head)
10469 (progn
10470 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10471 nil (point-at-eol)))
10472 (get-text-property p 'org-todo-head))))
10473 ((not (member kwd org-todo-keywords-1))
10474 (car org-todo-keywords-1))
10475 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10477 (defun org-fast-todo-selection ()
10478 "Fast TODO keyword selection with single keys.
10479 Returns the new TODO keyword, or nil if no state change should occur."
10480 (let* ((fulltable org-todo-key-alist)
10481 (done-keywords org-done-keywords) ;; needed for the faces.
10482 (maxlen (apply 'max (mapcar
10483 (lambda (x)
10484 (if (stringp (car x)) (string-width (car x)) 0))
10485 fulltable)))
10486 (expert nil)
10487 (fwidth (+ maxlen 3 1 3))
10488 (ncol (/ (- (window-width) 4) fwidth))
10489 tg cnt e c tbl
10490 groups ingroup)
10491 (save-excursion
10492 (save-window-excursion
10493 (if expert
10494 (set-buffer (get-buffer-create " *Org todo*"))
10495 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10496 (erase-buffer)
10497 (org-set-local 'org-done-keywords done-keywords)
10498 (setq tbl fulltable cnt 0)
10499 (while (setq e (pop tbl))
10500 (cond
10501 ((equal e '(:startgroup))
10502 (push '() groups) (setq ingroup t)
10503 (when (not (= cnt 0))
10504 (setq cnt 0)
10505 (insert "\n"))
10506 (insert "{ "))
10507 ((equal e '(:endgroup))
10508 (setq ingroup nil cnt 0)
10509 (insert "}\n"))
10510 ((equal e '(:newline))
10511 (when (not (= cnt 0))
10512 (setq cnt 0)
10513 (insert "\n")
10514 (setq e (car tbl))
10515 (while (equal (car tbl) '(:newline))
10516 (insert "\n")
10517 (setq tbl (cdr tbl)))))
10519 (setq tg (car e) c (cdr e))
10520 (if ingroup (push tg (car groups)))
10521 (setq tg (org-add-props tg nil 'face
10522 (org-get-todo-face tg)))
10523 (if (and (= cnt 0) (not ingroup)) (insert " "))
10524 (insert "[" c "] " tg (make-string
10525 (- fwidth 4 (length tg)) ?\ ))
10526 (when (= (setq cnt (1+ cnt)) ncol)
10527 (insert "\n")
10528 (if ingroup (insert " "))
10529 (setq cnt 0)))))
10530 (insert "\n")
10531 (goto-char (point-min))
10532 (if (not expert) (org-fit-window-to-buffer))
10533 (message "[a-z..]:Set [SPC]:clear")
10534 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10535 (cond
10536 ((or (= c ?\C-g)
10537 (and (= c ?q) (not (rassoc c fulltable))))
10538 (setq quit-flag t))
10539 ((= c ?\ ) nil)
10540 ((setq e (rassoc c fulltable) tg (car e))
10542 (t (setq quit-flag t)))))))
10544 (defun org-entry-is-todo-p ()
10545 (member (org-get-todo-state) org-not-done-keywords))
10547 (defun org-entry-is-done-p ()
10548 (member (org-get-todo-state) org-done-keywords))
10550 (defun org-get-todo-state ()
10551 (save-excursion
10552 (org-back-to-heading t)
10553 (and (looking-at org-todo-line-regexp)
10554 (match-end 2)
10555 (match-string 2))))
10557 (defun org-at-date-range-p (&optional inactive-ok)
10558 "Is the cursor inside a date range?"
10559 (interactive)
10560 (save-excursion
10561 (catch 'exit
10562 (let ((pos (point)))
10563 (skip-chars-backward "^[<\r\n")
10564 (skip-chars-backward "<[")
10565 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10566 (>= (match-end 0) pos)
10567 (throw 'exit t))
10568 (skip-chars-backward "^<[\r\n")
10569 (skip-chars-backward "<[")
10570 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10571 (>= (match-end 0) pos)
10572 (throw 'exit t)))
10573 nil)))
10575 (defun org-get-repeat (&optional tagline)
10576 "Check if there is a deadline/schedule with repeater in this entry."
10577 (save-match-data
10578 (save-excursion
10579 (org-back-to-heading t)
10580 (and (re-search-forward (if tagline
10581 (concat tagline "\\s-*" org-repeat-re)
10582 org-repeat-re)
10583 (org-entry-end-position) t)
10584 (match-string-no-properties 1)))))
10586 (defvar org-last-changed-timestamp)
10587 (defvar org-last-inserted-timestamp)
10588 (defvar org-log-post-message)
10589 (defvar org-log-note-purpose)
10590 (defvar org-log-note-how)
10591 (defvar org-log-note-extra)
10592 (defun org-auto-repeat-maybe (done-word)
10593 "Check if the current headline contains a repeated deadline/schedule.
10594 If yes, set TODO state back to what it was and change the base date
10595 of repeating deadline/scheduled time stamps to new date.
10596 This function is run automatically after each state change to a DONE state."
10597 ;; last-state is dynamically scoped into this function
10598 (let* ((repeat (org-get-repeat))
10599 (aa (assoc last-state org-todo-kwd-alist))
10600 (interpret (nth 1 aa))
10601 (head (nth 2 aa))
10602 (whata '(("d" . day) ("m" . month) ("y" . year)))
10603 (msg "Entry repeats: ")
10604 (org-log-done nil)
10605 (org-todo-log-states nil)
10606 (nshiftmax 10) (nshift 0)
10607 re type n what ts time)
10608 (when repeat
10609 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10610 (org-todo (if (eq interpret 'type) last-state head))
10611 (org-entry-put nil "LAST_REPEAT" (format-time-string
10612 (org-time-stamp-format t t)))
10613 (when org-log-repeat
10614 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10615 (memq 'org-add-log-note post-command-hook))
10616 ;; OK, we are already setup for some record
10617 (if (eq org-log-repeat 'note)
10618 ;; make sure we take a note, not only a time stamp
10619 (setq org-log-note-how 'note))
10620 ;; Set up for taking a record
10621 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10622 last-state
10623 'findpos org-log-repeat)))
10624 (org-back-to-heading t)
10625 (org-add-planning-info nil nil 'closed)
10626 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10627 org-deadline-time-regexp "\\)\\|\\("
10628 org-ts-regexp "\\)"))
10629 (while (re-search-forward
10630 re (save-excursion (outline-next-heading) (point)) t)
10631 (setq type (if (match-end 1) org-scheduled-string
10632 (if (match-end 3) org-deadline-string "Plain:"))
10633 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10634 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10635 (setq n (string-to-number (match-string 2 ts))
10636 what (match-string 3 ts))
10637 (if (equal what "w") (setq n (* n 7) what "d"))
10638 ;; Preparation, see if we need to modify the start date for the change
10639 (when (match-end 1)
10640 (setq time (save-match-data (org-time-string-to-time ts)))
10641 (cond
10642 ((equal (match-string 1 ts) ".")
10643 ;; Shift starting date to today
10644 (org-timestamp-change
10645 (- (time-to-days (current-time)) (time-to-days time))
10646 'day))
10647 ((equal (match-string 1 ts) "+")
10648 (while (or (= nshift 0)
10649 (<= (time-to-days time) (time-to-days (current-time))))
10650 (when (= (incf nshift) nshiftmax)
10651 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10652 (error "Abort")))
10653 (org-timestamp-change n (cdr (assoc what whata)))
10654 (org-at-timestamp-p t)
10655 (setq ts (match-string 1))
10656 (setq time (save-match-data (org-time-string-to-time ts))))
10657 (org-timestamp-change (- n) (cdr (assoc what whata)))
10658 ;; rematch, so that we have everything in place for the real shift
10659 (org-at-timestamp-p t)
10660 (setq ts (match-string 1))
10661 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10662 (org-timestamp-change n (cdr (assoc what whata)))
10663 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10664 (setq org-log-post-message msg)
10665 (message "%s" msg))))
10667 (defun org-show-todo-tree (arg)
10668 "Make a compact tree which shows all headlines marked with TODO.
10669 The tree will show the lines where the regexp matches, and all higher
10670 headlines above the match.
10671 With a \\[universal-argument] prefix, prompt for a regexp to match.
10672 With a numeric prefix N, construct a sparse tree for the Nth element
10673 of `org-todo-keywords-1'."
10674 (interactive "P")
10675 (let ((case-fold-search nil)
10676 (kwd-re
10677 (cond ((null arg) org-not-done-regexp)
10678 ((equal arg '(4))
10679 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10680 (mapcar 'list org-todo-keywords-1))))
10681 (concat "\\("
10682 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10683 "\\)\\>")))
10684 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10685 (regexp-quote (nth (1- (prefix-numeric-value arg))
10686 org-todo-keywords-1)))
10687 (t (error "Invalid prefix argument: %s" arg)))))
10688 (message "%d TODO entries found"
10689 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10691 (defun org-deadline (&optional remove time)
10692 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10693 With argument REMOVE, remove any deadline from the item.
10694 When TIME is set, it should be an internal time specification, and the
10695 scheduling will use the corresponding date."
10696 (interactive "P")
10697 (let ((old-date (org-entry-get nil "DEADLINE")))
10698 (if remove
10699 (progn
10700 (when (and old-date org-log-redeadline)
10701 (org-add-log-setup 'deldeadline nil old-date 'findpos
10702 org-log-redeadline))
10703 (org-remove-timestamp-with-keyword org-deadline-string)
10704 (message "Item no longer has a deadline."))
10705 (if (org-get-repeat)
10706 (error "Cannot change deadline on task with repeater, please do that by hand")
10707 (org-add-planning-info 'deadline time 'closed)
10708 (when (and old-date org-log-redeadline
10709 (not (equal old-date
10710 (substring org-last-inserted-timestamp 1 -1))))
10711 (org-add-log-setup 'redeadline nil old-date 'findpos
10712 org-log-redeadline))
10713 (message "Deadline on %s" org-last-inserted-timestamp)))))
10715 (defun org-schedule (&optional remove time)
10716 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10717 With argument REMOVE, remove any scheduling date from the item.
10718 When TIME is set, it should be an internal time specification, and the
10719 scheduling will use the corresponding date."
10720 (interactive "P")
10721 (let ((old-date (org-entry-get nil "SCHEDULED")))
10722 (if remove
10723 (progn
10724 (when (and old-date org-log-reschedule)
10725 (org-add-log-setup 'delschedule nil old-date 'findpos
10726 org-log-reschedule))
10727 (org-remove-timestamp-with-keyword org-scheduled-string)
10728 (message "Item is no longer scheduled."))
10729 (if (org-get-repeat)
10730 (error "Cannot reschedule task with repeater, please do that by hand")
10731 (org-add-planning-info 'scheduled time 'closed)
10732 (when (and old-date org-log-reschedule
10733 (not (equal old-date
10734 (substring org-last-inserted-timestamp 1 -1))))
10735 (org-add-log-setup 'reschedule nil old-date 'findpos
10736 org-log-reschedule))
10737 (message "Scheduled to %s" org-last-inserted-timestamp)))))
10739 (defun org-get-scheduled-time (pom &optional inherit)
10740 "Get the scheduled time as a time tuple, of a format suitable
10741 for calling org-schedule with, or if there is no scheduling,
10742 returns nil."
10743 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10744 (when time
10745 (apply 'encode-time (org-parse-time-string time)))))
10747 (defun org-get-deadline-time (pom &optional inherit)
10748 "Get the deadine as a time tuple, of a format suitable for
10749 calling org-deadline with, or if there is no scheduling, returns
10750 nil."
10751 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10752 (when time
10753 (apply 'encode-time (org-parse-time-string time)))))
10755 (defun org-remove-timestamp-with-keyword (keyword)
10756 "Remove all time stamps with KEYWORD in the current entry."
10757 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10758 beg)
10759 (save-excursion
10760 (org-back-to-heading t)
10761 (setq beg (point))
10762 (outline-next-heading)
10763 (while (re-search-backward re beg t)
10764 (replace-match "")
10765 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10766 (equal (char-before) ?\ ))
10767 (backward-delete-char 1)
10768 (if (string-match "^[ \t]*$" (buffer-substring
10769 (point-at-bol) (point-at-eol)))
10770 (delete-region (point-at-bol)
10771 (min (point-max) (1+ (point-at-eol))))))))))
10773 (defun org-add-planning-info (what &optional time &rest remove)
10774 "Insert new timestamp with keyword in the line directly after the headline.
10775 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10776 If non is given, the user is prompted for a date.
10777 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10778 be removed."
10779 (interactive)
10780 (let (org-time-was-given org-end-time-was-given ts
10781 end default-time default-input)
10783 (catch 'exit
10784 (when (and (not time) (memq what '(scheduled deadline)))
10785 ;; Try to get a default date/time from existing timestamp
10786 (save-excursion
10787 (org-back-to-heading t)
10788 (setq end (save-excursion (outline-next-heading) (point)))
10789 (when (re-search-forward (if (eq what 'scheduled)
10790 org-scheduled-time-regexp
10791 org-deadline-time-regexp)
10792 end t)
10793 (setq ts (match-string 1)
10794 default-time
10795 (apply 'encode-time (org-parse-time-string ts))
10796 default-input (and ts (org-get-compact-tod ts))))))
10797 (when what
10798 ;; If necessary, get the time from the user
10799 (setq time (or time (org-read-date nil 'to-time nil nil
10800 default-time default-input))))
10802 (when (and org-insert-labeled-timestamps-at-point
10803 (member what '(scheduled deadline)))
10804 (insert
10805 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10806 (org-insert-time-stamp time org-time-was-given
10807 nil nil nil (list org-end-time-was-given))
10808 (setq what nil))
10809 (save-excursion
10810 (save-restriction
10811 (let (col list elt ts buffer-invisibility-spec)
10812 (org-back-to-heading t)
10813 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10814 (goto-char (match-end 1))
10815 (setq col (current-column))
10816 (goto-char (match-end 0))
10817 (if (eobp) (insert "\n") (forward-char 1))
10818 (when (and (not what)
10819 (not (looking-at
10820 (concat "[ \t]*"
10821 org-keyword-time-not-clock-regexp))))
10822 ;; Nothing to add, nothing to remove...... :-)
10823 (throw 'exit nil))
10824 (if (and (not (looking-at outline-regexp))
10825 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10826 "[^\r\n]*"))
10827 (not (equal (match-string 1) org-clock-string)))
10828 (narrow-to-region (match-beginning 0) (match-end 0))
10829 (insert-before-markers "\n")
10830 (backward-char 1)
10831 (narrow-to-region (point) (point))
10832 (and org-adapt-indentation (org-indent-to-column col)))
10833 ;; Check if we have to remove something.
10834 (setq list (cons what remove))
10835 (while list
10836 (setq elt (pop list))
10837 (goto-char (point-min))
10838 (when (or (and (eq elt 'scheduled)
10839 (re-search-forward org-scheduled-time-regexp nil t))
10840 (and (eq elt 'deadline)
10841 (re-search-forward org-deadline-time-regexp nil t))
10842 (and (eq elt 'closed)
10843 (re-search-forward org-closed-time-regexp nil t)))
10844 (replace-match "")
10845 (if (looking-at "--+<[^>]+>") (replace-match ""))
10846 (skip-chars-backward " ")
10847 (if (looking-at " +") (replace-match ""))))
10848 (goto-char (point-max))
10849 (and org-adapt-indentation (bolp) (org-indent-to-column col))
10850 (when what
10851 (insert
10852 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10853 (cond ((eq what 'scheduled) org-scheduled-string)
10854 ((eq what 'deadline) org-deadline-string)
10855 ((eq what 'closed) org-closed-string))
10856 " ")
10857 (setq ts (org-insert-time-stamp
10858 time
10859 (or org-time-was-given
10860 (and (eq what 'closed) org-log-done-with-time))
10861 (eq what 'closed)
10862 nil nil (list org-end-time-was-given)))
10863 (end-of-line 1))
10864 (goto-char (point-min))
10865 (widen)
10866 (if (and (looking-at "[ \t]+\n")
10867 (equal (char-before) ?\n))
10868 (delete-region (1- (point)) (point-at-eol)))
10869 ts))))))
10871 (defvar org-log-note-marker (make-marker))
10872 (defvar org-log-note-purpose nil)
10873 (defvar org-log-note-state nil)
10874 (defvar org-log-note-previous-state nil)
10875 (defvar org-log-note-how nil)
10876 (defvar org-log-note-extra nil)
10877 (defvar org-log-note-window-configuration nil)
10878 (defvar org-log-note-return-to (make-marker))
10879 (defvar org-log-post-message nil
10880 "Message to be displayed after a log note has been stored.
10881 The auto-repeater uses this.")
10883 (defun org-add-note ()
10884 "Add a note to the current entry.
10885 This is done in the same way as adding a state change note."
10886 (interactive)
10887 (org-add-log-setup 'note nil nil 'findpos nil))
10889 (defvar org-property-end-re)
10890 (defun org-add-log-setup (&optional purpose state prev-state
10891 findpos how &optional extra)
10892 "Set up the post command hook to take a note.
10893 If this is about to TODO state change, the new state is expected in STATE.
10894 When FINDPOS is non-nil, find the correct position for the note in
10895 the current entry. If not, assume that it can be inserted at point.
10896 HOW is an indicator what kind of note should be created.
10897 EXTRA is additional text that will be inserted into the notes buffer."
10898 (let* ((org-log-into-drawer (org-log-into-drawer))
10899 (drawer (cond ((stringp org-log-into-drawer)
10900 org-log-into-drawer)
10901 (org-log-into-drawer "LOGBOOK")
10902 (t nil))))
10903 (save-restriction
10904 (save-excursion
10905 (when findpos
10906 (org-back-to-heading t)
10907 (narrow-to-region (point) (save-excursion
10908 (outline-next-heading) (point)))
10909 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10910 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10911 "[^\r\n]*\\)?"))
10912 (goto-char (match-end 0))
10913 (cond
10914 (drawer
10915 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10916 nil t)
10917 (progn
10918 (goto-char (match-end 0))
10919 (or org-log-states-order-reversed
10920 (and (re-search-forward org-property-end-re nil t)
10921 (goto-char (1- (match-beginning 0))))))
10922 (insert "\n:" drawer ":\n:END:")
10923 (beginning-of-line 0)
10924 (org-indent-line-function)
10925 (beginning-of-line 2)
10926 (org-indent-line-function)
10927 (end-of-line 0)))
10928 ((and org-log-state-notes-insert-after-drawers
10929 (save-excursion
10930 (forward-line) (looking-at org-drawer-regexp)))
10931 (forward-line)
10932 (while (looking-at org-drawer-regexp)
10933 (goto-char (match-end 0))
10934 (re-search-forward org-property-end-re (point-max) t)
10935 (forward-line))
10936 (forward-line -1)))
10937 (unless org-log-states-order-reversed
10938 (and (= (char-after) ?\n) (forward-char 1))
10939 (org-skip-over-state-notes)
10940 (skip-chars-backward " \t\n\r")))
10941 (move-marker org-log-note-marker (point))
10942 (setq org-log-note-purpose purpose
10943 org-log-note-state state
10944 org-log-note-previous-state prev-state
10945 org-log-note-how how
10946 org-log-note-extra extra)
10947 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10949 (defun org-skip-over-state-notes ()
10950 "Skip past the list of State notes in an entry."
10951 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10952 (while (looking-at "[ \t]*- State")
10953 (condition-case nil
10954 (org-next-item)
10955 (error (org-end-of-item)))))
10957 (defun org-add-log-note (&optional purpose)
10958 "Pop up a window for taking a note, and add this note later at point."
10959 (remove-hook 'post-command-hook 'org-add-log-note)
10960 (setq org-log-note-window-configuration (current-window-configuration))
10961 (delete-other-windows)
10962 (move-marker org-log-note-return-to (point))
10963 (switch-to-buffer (marker-buffer org-log-note-marker))
10964 (goto-char org-log-note-marker)
10965 (org-switch-to-buffer-other-window "*Org Note*")
10966 (erase-buffer)
10967 (if (memq org-log-note-how '(time state))
10968 (let (current-prefix-arg) (org-store-log-note))
10969 (let ((org-inhibit-startup t)) (org-mode))
10970 (insert (format "# Insert note for %s.
10971 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10972 (cond
10973 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10974 ((eq org-log-note-purpose 'done) "closed todo item")
10975 ((eq org-log-note-purpose 'state)
10976 (format "state change from \"%s\" to \"%s\""
10977 (or org-log-note-previous-state "")
10978 (or org-log-note-state "")))
10979 ((eq org-log-note-purpose 'reschedule)
10980 "rescheduling")
10981 ((eq org-log-note-purpose 'delschedule)
10982 "no longer scheduled")
10983 ((eq org-log-note-purpose 'redeadline)
10984 "changing deadline")
10985 ((eq org-log-note-purpose 'deldeadline)
10986 "removing deadline")
10987 ((eq org-log-note-purpose 'note)
10988 "this entry")
10989 (t (error "This should not happen")))))
10990 (if org-log-note-extra (insert org-log-note-extra))
10991 (org-set-local 'org-finish-function 'org-store-log-note)))
10993 (defvar org-note-abort nil) ; dynamically scoped
10994 (defun org-store-log-note ()
10995 "Finish taking a log note, and insert it to where it belongs."
10996 (let ((txt (buffer-string))
10997 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10998 lines ind)
10999 (kill-buffer (current-buffer))
11000 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11001 (setq txt (replace-match "" t t txt)))
11002 (if (string-match "\\s-+\\'" txt)
11003 (setq txt (replace-match "" t t txt)))
11004 (setq lines (org-split-string txt "\n"))
11005 (when (and note (string-match "\\S-" note))
11006 (setq note
11007 (org-replace-escapes
11008 note
11009 (list (cons "%u" (user-login-name))
11010 (cons "%U" user-full-name)
11011 (cons "%t" (format-time-string
11012 (org-time-stamp-format 'long 'inactive)
11013 (current-time)))
11014 (cons "%s" (if org-log-note-state
11015 (concat "\"" org-log-note-state "\"")
11016 ""))
11017 (cons "%S" (if org-log-note-previous-state
11018 (concat "\"" org-log-note-previous-state "\"")
11019 "\"\"")))))
11020 (if lines (setq note (concat note " \\\\")))
11021 (push note lines))
11022 (when (or current-prefix-arg org-note-abort)
11023 (when org-log-into-drawer
11024 (org-remove-empty-drawer-at
11025 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11026 org-log-note-marker))
11027 (setq lines nil))
11028 (when lines
11029 (with-current-buffer (marker-buffer org-log-note-marker)
11030 (save-excursion
11031 (goto-char org-log-note-marker)
11032 (move-marker org-log-note-marker nil)
11033 (end-of-line 1)
11034 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11035 (insert "- " (pop lines))
11036 (org-indent-line-function)
11037 (beginning-of-line 1)
11038 (looking-at "[ \t]*")
11039 (setq ind (concat (match-string 0) " "))
11040 (end-of-line 1)
11041 (while lines (insert "\n" ind (pop lines)))
11042 (message "Note stored")
11043 (org-back-to-heading t)
11044 (org-cycle-hide-drawers 'children)))))
11045 (set-window-configuration org-log-note-window-configuration)
11046 (with-current-buffer (marker-buffer org-log-note-return-to)
11047 (goto-char org-log-note-return-to))
11048 (move-marker org-log-note-return-to nil)
11049 (and org-log-post-message (message "%s" org-log-post-message)))
11051 (defun org-remove-empty-drawer-at (drawer pos)
11052 "Remove an empty drawer DRAWER at position POS.
11053 POS may also be a marker."
11054 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11055 (save-excursion
11056 (save-restriction
11057 (widen)
11058 (goto-char pos)
11059 (if (org-in-regexp
11060 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11061 (replace-match ""))))))
11063 (defun org-sparse-tree (&optional arg)
11064 "Create a sparse tree, prompt for the details.
11065 This command can create sparse trees. You first need to select the type
11066 of match used to create the tree:
11068 t Show entries with a specific TODO keyword.
11069 m Show entries selected by a tags/property match.
11070 p Enter a property name and its value (both with completion on existing
11071 names/values) and show entries with that property.
11072 / Show entries matching a regular expression (`r' can be used as well)
11073 d Show deadlines due within `org-deadline-warning-days'.
11074 b Show deadlines and scheduled items before a date.
11075 a Show deadlines and scheduled items after a date."
11076 (interactive "P")
11077 (let (ans kwd value)
11078 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
11079 (setq ans (read-char-exclusive))
11080 (cond
11081 ((equal ans ?d)
11082 (call-interactively 'org-check-deadlines))
11083 ((equal ans ?b)
11084 (call-interactively 'org-check-before-date))
11085 ((equal ans ?a)
11086 (call-interactively 'org-check-after-date))
11087 ((equal ans ?t)
11088 (org-show-todo-tree '(4)))
11089 ((member ans '(?T ?m))
11090 (call-interactively 'org-match-sparse-tree))
11091 ((member ans '(?p ?P))
11092 (setq kwd (org-icompleting-read "Property: "
11093 (mapcar 'list (org-buffer-property-keys))))
11094 (setq value (org-icompleting-read "Value: "
11095 (mapcar 'list (org-property-values kwd))))
11096 (unless (string-match "\\`{.*}\\'" value)
11097 (setq value (concat "\"" value "\"")))
11098 (org-match-sparse-tree arg (concat kwd "=" value)))
11099 ((member ans '(?r ?R ?/))
11100 (call-interactively 'org-occur))
11101 (t (error "No such sparse tree command \"%c\"" ans)))))
11103 (defvar org-occur-highlights nil
11104 "List of overlays used for occur matches.")
11105 (make-variable-buffer-local 'org-occur-highlights)
11106 (defvar org-occur-parameters nil
11107 "Parameters of the active org-occur calls.
11108 This is a list, each call to org-occur pushes as cons cell,
11109 containing the regular expression and the callback, onto the list.
11110 The list can contain several entries if `org-occur' has been called
11111 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11112 will only contain one set of parameters. When the highlights are
11113 removed (for example with `C-c C-c', or with the next edit (depending
11114 on `org-remove-highlights-with-change'), this variable is emptied
11115 as well.")
11116 (make-variable-buffer-local 'org-occur-parameters)
11118 (defun org-occur (regexp &optional keep-previous callback)
11119 "Make a compact tree which shows all matches of REGEXP.
11120 The tree will show the lines where the regexp matches, and all higher
11121 headlines above the match. It will also show the heading after the match,
11122 to make sure editing the matching entry is easy.
11123 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11124 call to `org-occur' will be kept, to allow stacking of calls to this
11125 command.
11126 If CALLBACK is non-nil, it is a function which is called to confirm
11127 that the match should indeed be shown."
11128 (interactive "sRegexp: \nP")
11129 (when (equal regexp "")
11130 (error "Regexp cannot be empty"))
11131 (unless keep-previous
11132 (org-remove-occur-highlights nil nil t))
11133 (push (cons regexp callback) org-occur-parameters)
11134 (let ((cnt 0))
11135 (save-excursion
11136 (goto-char (point-min))
11137 (if (or (not keep-previous) ; do not want to keep
11138 (not org-occur-highlights)) ; no previous matches
11139 ;; hide everything
11140 (org-overview))
11141 (while (re-search-forward regexp nil t)
11142 (when (or (not callback)
11143 (save-match-data (funcall callback)))
11144 (setq cnt (1+ cnt))
11145 (when org-highlight-sparse-tree-matches
11146 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11147 (org-show-context 'occur-tree))))
11148 (when org-remove-highlights-with-change
11149 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11150 nil 'local))
11151 (unless org-sparse-tree-open-archived-trees
11152 (org-hide-archived-subtrees (point-min) (point-max)))
11153 (run-hooks 'org-occur-hook)
11154 (if (interactive-p)
11155 (message "%d match(es) for regexp %s" cnt regexp))
11156 cnt))
11158 (defun org-show-context (&optional key)
11159 "Make sure point and context and visible.
11160 How much context is shown depends upon the variables
11161 `org-show-hierarchy-above', `org-show-following-heading'. and
11162 `org-show-siblings'."
11163 (let ((heading-p (org-on-heading-p t))
11164 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11165 (following-p (org-get-alist-option org-show-following-heading key))
11166 (entry-p (org-get-alist-option org-show-entry-below key))
11167 (siblings-p (org-get-alist-option org-show-siblings key)))
11168 (catch 'exit
11169 ;; Show heading or entry text
11170 (if (and heading-p (not entry-p))
11171 (org-flag-heading nil) ; only show the heading
11172 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11173 (org-show-hidden-entry))) ; show entire entry
11174 (when following-p
11175 ;; Show next sibling, or heading below text
11176 (save-excursion
11177 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11178 (org-flag-heading nil))))
11179 (when siblings-p (org-show-siblings))
11180 (when hierarchy-p
11181 ;; show all higher headings, possibly with siblings
11182 (save-excursion
11183 (while (and (condition-case nil
11184 (progn (org-up-heading-all 1) t)
11185 (error nil))
11186 (not (bobp)))
11187 (org-flag-heading nil)
11188 (when siblings-p (org-show-siblings))))))))
11190 (defun org-reveal (&optional siblings)
11191 "Show current entry, hierarchy above it, and the following headline.
11192 This can be used to show a consistent set of context around locations
11193 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11194 not t for the search context.
11196 With optional argument SIBLINGS, on each level of the hierarchy all
11197 siblings are shown. This repairs the tree structure to what it would
11198 look like when opened with hierarchical calls to `org-cycle'."
11199 (interactive "P")
11200 (let ((org-show-hierarchy-above t)
11201 (org-show-following-heading t)
11202 (org-show-siblings (if siblings t org-show-siblings)))
11203 (org-show-context nil)))
11205 (defun org-highlight-new-match (beg end)
11206 "Highlight from BEG to END and mark the highlight is an occur headline."
11207 (let ((ov (org-make-overlay beg end)))
11208 (org-overlay-put ov 'face 'secondary-selection)
11209 (push ov org-occur-highlights)))
11211 (defun org-remove-occur-highlights (&optional beg end noremove)
11212 "Remove the occur highlights from the buffer.
11213 BEG and END are ignored. If NOREMOVE is nil, remove this function
11214 from the `before-change-functions' in the current buffer."
11215 (interactive)
11216 (unless org-inhibit-highlight-removal
11217 (mapc 'org-delete-overlay org-occur-highlights)
11218 (setq org-occur-highlights nil)
11219 (setq org-occur-parameters nil)
11220 (unless noremove
11221 (remove-hook 'before-change-functions
11222 'org-remove-occur-highlights 'local))))
11224 ;;;; Priorities
11226 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11227 "Regular expression matching the priority indicator.")
11229 (defvar org-remove-priority-next-time nil)
11231 (defun org-priority-up ()
11232 "Increase the priority of the current item."
11233 (interactive)
11234 (org-priority 'up))
11236 (defun org-priority-down ()
11237 "Decrease the priority of the current item."
11238 (interactive)
11239 (org-priority 'down))
11241 (defun org-priority (&optional action)
11242 "Change the priority of an item by ARG.
11243 ACTION can be `set', `up', `down', or a character."
11244 (interactive)
11245 (unless org-enable-priority-commands
11246 (error "Priority commands are disabled"))
11247 (setq action (or action 'set))
11248 (let (current new news have remove)
11249 (save-excursion
11250 (org-back-to-heading t)
11251 (if (looking-at org-priority-regexp)
11252 (setq current (string-to-char (match-string 2))
11253 have t)
11254 (setq current org-default-priority))
11255 (cond
11256 ((eq action 'remove)
11257 (setq remove t new ?\ ))
11258 ((or (eq action 'set)
11259 (if (featurep 'xemacs) (characterp action) (integerp action)))
11260 (if (not (eq action 'set))
11261 (setq new action)
11262 (message "Priority %c-%c, SPC to remove: "
11263 org-highest-priority org-lowest-priority)
11264 (setq new (read-char-exclusive)))
11265 (if (and (= (upcase org-highest-priority) org-highest-priority)
11266 (= (upcase org-lowest-priority) org-lowest-priority))
11267 (setq new (upcase new)))
11268 (cond ((equal new ?\ ) (setq remove t))
11269 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11270 (error "Priority must be between `%c' and `%c'"
11271 org-highest-priority org-lowest-priority))))
11272 ((eq action 'up)
11273 (if (and (not have) (eq last-command this-command))
11274 (setq new org-lowest-priority)
11275 (setq new (if (and org-priority-start-cycle-with-default (not have))
11276 org-default-priority (1- current)))))
11277 ((eq action 'down)
11278 (if (and (not have) (eq last-command this-command))
11279 (setq new org-highest-priority)
11280 (setq new (if (and org-priority-start-cycle-with-default (not have))
11281 org-default-priority (1+ current)))))
11282 (t (error "Invalid action")))
11283 (if (or (< (upcase new) org-highest-priority)
11284 (> (upcase new) org-lowest-priority))
11285 (setq remove t))
11286 (setq news (format "%c" new))
11287 (if have
11288 (if remove
11289 (replace-match "" t t nil 1)
11290 (replace-match news t t nil 2))
11291 (if remove
11292 (error "No priority cookie found in line")
11293 (let ((case-fold-search nil))
11294 (looking-at org-todo-line-regexp))
11295 (if (match-end 2)
11296 (progn
11297 (goto-char (match-end 2))
11298 (insert " [#" news "]"))
11299 (goto-char (match-beginning 3))
11300 (insert "[#" news "] "))))
11301 (org-preserve-lc (org-set-tags nil 'align)))
11302 (if remove
11303 (message "Priority removed")
11304 (message "Priority of current item set to %s" news))))
11306 (defun org-get-priority (s)
11307 "Find priority cookie and return priority."
11308 (save-match-data
11309 (if (not (string-match org-priority-regexp s))
11310 (* 1000 (- org-lowest-priority org-default-priority))
11311 (* 1000 (- org-lowest-priority
11312 (string-to-char (match-string 2 s)))))))
11314 ;;;; Tags
11316 (defvar org-agenda-archives-mode)
11317 (defvar org-map-continue-from nil
11318 "Position from where mapping should continue.
11319 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11321 (defvar org-scanner-tags nil
11322 "The current tag list while the tags scanner is running.")
11323 (defvar org-trust-scanner-tags nil
11324 "Should `org-get-tags-at' use the tags fro the scanner.
11325 This is for internal dynamical scoping only.
11326 When this is non-nil, the function `org-get-tags-at' will return the value
11327 of `org-scanner-tags' instead of building the list by itself. This
11328 can lead to large speed-ups when the tags scanner is used in a file with
11329 many entries, and when the list of tags is retrieved, for example to
11330 obtain a list of properties. Building the tags list for each entry in such
11331 a file becomes an N^2 operation - but with this variable set, it scales
11332 as N.")
11334 (defun org-scan-tags (action matcher &optional todo-only)
11335 "Scan headline tags with inheritance and produce output ACTION.
11337 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11338 or `agenda' to produce an entry list for an agenda view. It can also be
11339 a Lisp form or a function that should be called at each matched headline, in
11340 this case the return value is a list of all return values from these calls.
11342 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11343 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11344 only lines with a TODO keyword are included in the output."
11345 (require 'org-agenda)
11346 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11347 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11348 (org-re
11349 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11350 (props (list 'face 'default
11351 'done-face 'org-agenda-done
11352 'undone-face 'default
11353 'mouse-face 'highlight
11354 'org-not-done-regexp org-not-done-regexp
11355 'org-todo-regexp org-todo-regexp
11356 'help-echo
11357 (format "mouse-2 or RET jump to org file %s"
11358 (abbreviate-file-name
11359 (or (buffer-file-name (buffer-base-buffer))
11360 (buffer-name (buffer-base-buffer)))))))
11361 (case-fold-search nil)
11362 (org-map-continue-from nil)
11363 lspos tags tags-list
11364 (tags-alist (list (cons 0 org-file-tags)))
11365 (llast 0) rtn rtn1 level category i txt
11366 todo marker entry priority)
11367 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11368 (setq action (list 'lambda nil action)))
11369 (save-excursion
11370 (goto-char (point-min))
11371 (when (eq action 'sparse-tree)
11372 (org-overview)
11373 (org-remove-occur-highlights))
11374 (while (re-search-forward re nil t)
11375 (catch :skip
11376 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11377 tags (if (match-end 4) (org-match-string-no-properties 4)))
11378 (goto-char (setq lspos (match-beginning 0)))
11379 (setq level (org-reduced-level (funcall outline-level))
11380 category (org-get-category))
11381 (setq i llast llast level)
11382 ;; remove tag lists from same and sublevels
11383 (while (>= i level)
11384 (when (setq entry (assoc i tags-alist))
11385 (setq tags-alist (delete entry tags-alist)))
11386 (setq i (1- i)))
11387 ;; add the next tags
11388 (when tags
11389 (setq tags (org-split-string tags ":")
11390 tags-alist
11391 (cons (cons level tags) tags-alist)))
11392 ;; compile tags for current headline
11393 (setq tags-list
11394 (if org-use-tag-inheritance
11395 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11396 tags)
11397 org-scanner-tags tags-list)
11398 (when org-use-tag-inheritance
11399 (setcdr (car tags-alist)
11400 (mapcar (lambda (x)
11401 (setq x (copy-sequence x))
11402 (org-add-prop-inherited x))
11403 (cdar tags-alist))))
11404 (when (and tags org-use-tag-inheritance
11405 (or (not (eq t org-use-tag-inheritance))
11406 org-tags-exclude-from-inheritance))
11407 ;; selective inheritance, remove uninherited ones
11408 (setcdr (car tags-alist)
11409 (org-remove-uniherited-tags (cdar tags-alist))))
11410 (when (and (or (not todo-only)
11411 (and (member todo org-not-done-keywords)
11412 (or (not org-agenda-tags-todo-honor-ignore-options)
11413 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11414 (let ((case-fold-search t)) (eval matcher))
11416 (not (member org-archive-tag tags-list))
11417 ;; we have an archive tag, should we use this anyway?
11418 (or (not org-agenda-skip-archived-trees)
11419 (and (eq action 'agenda) org-agenda-archives-mode))))
11420 (unless (eq action 'sparse-tree) (org-agenda-skip))
11422 ;; select this headline
11424 (cond
11425 ((eq action 'sparse-tree)
11426 (and org-highlight-sparse-tree-matches
11427 (org-get-heading) (match-end 0)
11428 (org-highlight-new-match
11429 (match-beginning 0) (match-beginning 1)))
11430 (org-show-context 'tags-tree))
11431 ((eq action 'agenda)
11432 (setq txt (org-format-agenda-item
11434 (concat
11435 (if (eq org-tags-match-list-sublevels 'indented)
11436 (make-string (1- level) ?.) "")
11437 (org-get-heading))
11438 category
11439 tags-list
11441 priority (org-get-priority txt))
11442 (goto-char lspos)
11443 (setq marker (org-agenda-new-marker))
11444 (org-add-props txt props
11445 'org-marker marker 'org-hd-marker marker 'org-category category
11446 'todo-state todo
11447 'priority priority 'type "tagsmatch")
11448 (push txt rtn))
11449 ((functionp action)
11450 (setq org-map-continue-from nil)
11451 (save-excursion
11452 (setq rtn1 (funcall action))
11453 (push rtn1 rtn)))
11454 (t (error "Invalid action")))
11456 ;; if we are to skip sublevels, jump to end of subtree
11457 (unless org-tags-match-list-sublevels
11458 (org-end-of-subtree t)
11459 (backward-char 1))))
11460 ;; Get the correct position from where to continue
11461 (if org-map-continue-from
11462 (goto-char org-map-continue-from)
11463 (and (= (point) lspos) (end-of-line 1)))))
11464 (when (and (eq action 'sparse-tree)
11465 (not org-sparse-tree-open-archived-trees))
11466 (org-hide-archived-subtrees (point-min) (point-max)))
11467 (nreverse rtn)))
11469 (defun org-remove-uniherited-tags (tags)
11470 "Remove all tags that are not inherited from the list TAGS."
11471 (cond
11472 ((eq org-use-tag-inheritance t)
11473 (if org-tags-exclude-from-inheritance
11474 (org-delete-all org-tags-exclude-from-inheritance tags)
11475 tags))
11476 ((not org-use-tag-inheritance) nil)
11477 ((stringp org-use-tag-inheritance)
11478 (delq nil (mapcar
11479 (lambda (x)
11480 (if (and (string-match org-use-tag-inheritance x)
11481 (not (member x org-tags-exclude-from-inheritance)))
11482 x nil))
11483 tags)))
11484 ((listp org-use-tag-inheritance)
11485 (delq nil (mapcar
11486 (lambda (x)
11487 (if (member x org-use-tag-inheritance) x nil))
11488 tags)))))
11490 (defvar todo-only) ;; dynamically scoped
11492 (defun org-match-sparse-tree (&optional todo-only match)
11493 "Create a sparse tree according to tags string MATCH.
11494 MATCH can contain positive and negative selection of tags, like
11495 \"+WORK+URGENT-WITHBOSS\".
11496 If optional argument TODO-ONLY is non-nil, only select lines that are
11497 also TODO lines."
11498 (interactive "P")
11499 (org-prepare-agenda-buffers (list (current-buffer)))
11500 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11502 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11504 (defvar org-cached-props nil)
11505 (defun org-cached-entry-get (pom property)
11506 (if (or (eq t org-use-property-inheritance)
11507 (and (stringp org-use-property-inheritance)
11508 (string-match org-use-property-inheritance property))
11509 (and (listp org-use-property-inheritance)
11510 (member property org-use-property-inheritance)))
11511 ;; Caching is not possible, check it directly
11512 (org-entry-get pom property 'inherit)
11513 ;; Get all properties, so that we can do complicated checks easily
11514 (cdr (assoc property (or org-cached-props
11515 (setq org-cached-props
11516 (org-entry-properties pom)))))))
11518 (defun org-global-tags-completion-table (&optional files)
11519 "Return the list of all tags in all agenda buffer/files."
11520 (save-excursion
11521 (org-uniquify
11522 (delq nil
11523 (apply 'append
11524 (mapcar
11525 (lambda (file)
11526 (set-buffer (find-file-noselect file))
11527 (append (org-get-buffer-tags)
11528 (mapcar (lambda (x) (if (stringp (car-safe x))
11529 (list (car-safe x)) nil))
11530 org-tag-alist)))
11531 (if (and files (car files))
11532 files
11533 (org-agenda-files))))))))
11535 (defun org-make-tags-matcher (match)
11536 "Create the TAGS//TODO matcher form for the selection string MATCH."
11537 ;; todo-only is scoped dynamically into this function, and the function
11538 ;; may change it if the matcher asks for it.
11539 (unless match
11540 ;; Get a new match request, with completion
11541 (let ((org-last-tags-completion-table
11542 (org-global-tags-completion-table)))
11543 (setq match (org-completing-read-no-i
11544 "Match: " 'org-tags-completion-function nil nil nil
11545 'org-tags-history))))
11547 ;; Parse the string and create a lisp form
11548 (let ((match0 match)
11549 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11550 minus tag mm
11551 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11552 orterms term orlist re-p str-p level-p level-op time-p
11553 prop-p pn pv po cat-p gv rest)
11554 (if (string-match "/+" match)
11555 ;; match contains also a todo-matching request
11556 (progn
11557 (setq tagsmatch (substring match 0 (match-beginning 0))
11558 todomatch (substring match (match-end 0)))
11559 (if (string-match "^!" todomatch)
11560 (setq todo-only t todomatch (substring todomatch 1)))
11561 (if (string-match "^\\s-*$" todomatch)
11562 (setq todomatch nil)))
11563 ;; only matching tags
11564 (setq tagsmatch match todomatch nil))
11566 ;; Make the tags matcher
11567 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11568 (setq tagsmatcher t)
11569 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11570 (while (setq term (pop orterms))
11571 (while (and (equal (substring term -1) "\\") orterms)
11572 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11573 (while (string-match re term)
11574 (setq rest (substring term (match-end 0))
11575 minus (and (match-end 1)
11576 (equal (match-string 1 term) "-"))
11577 tag (match-string 2 term)
11578 re-p (equal (string-to-char tag) ?{)
11579 level-p (match-end 4)
11580 prop-p (match-end 5)
11581 mm (cond
11582 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11583 (level-p
11584 (setq level-op (org-op-to-function (match-string 3 term)))
11585 `(,level-op level ,(string-to-number
11586 (match-string 4 term))))
11587 (prop-p
11588 (setq pn (match-string 5 term)
11589 po (match-string 6 term)
11590 pv (match-string 7 term)
11591 cat-p (equal pn "CATEGORY")
11592 re-p (equal (string-to-char pv) ?{)
11593 str-p (equal (string-to-char pv) ?\")
11594 time-p (save-match-data
11595 (string-match "^\"[[<].*[]>]\"$" pv))
11596 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11597 (if time-p (setq pv (org-matcher-time pv)))
11598 (setq po (org-op-to-function po (if time-p 'time str-p)))
11599 (cond
11600 ((equal pn "CATEGORY")
11601 (setq gv '(get-text-property (point) 'org-category)))
11602 ((equal pn "TODO")
11603 (setq gv 'todo))
11605 (setq gv `(org-cached-entry-get nil ,pn))))
11606 (if re-p
11607 (if (eq po 'org<>)
11608 `(not (string-match ,pv (or ,gv "")))
11609 `(string-match ,pv (or ,gv "")))
11610 (if str-p
11611 `(,po (or ,gv "") ,pv)
11612 `(,po (string-to-number (or ,gv ""))
11613 ,(string-to-number pv) ))))
11614 (t `(member ,tag tags-list)))
11615 mm (if minus (list 'not mm) mm)
11616 term rest)
11617 (push mm tagsmatcher))
11618 (push (if (> (length tagsmatcher) 1)
11619 (cons 'and tagsmatcher)
11620 (car tagsmatcher))
11621 orlist)
11622 (setq tagsmatcher nil))
11623 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11624 (setq tagsmatcher
11625 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11626 ;; Make the todo matcher
11627 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11628 (setq todomatcher t)
11629 (setq orterms (org-split-string todomatch "|") orlist nil)
11630 (while (setq term (pop orterms))
11631 (while (string-match re term)
11632 (setq minus (and (match-end 1)
11633 (equal (match-string 1 term) "-"))
11634 kwd (match-string 2 term)
11635 re-p (equal (string-to-char kwd) ?{)
11636 term (substring term (match-end 0))
11637 mm (if re-p
11638 `(string-match ,(substring kwd 1 -1) todo)
11639 (list 'equal 'todo kwd))
11640 mm (if minus (list 'not mm) mm))
11641 (push mm todomatcher))
11642 (push (if (> (length todomatcher) 1)
11643 (cons 'and todomatcher)
11644 (car todomatcher))
11645 orlist)
11646 (setq todomatcher nil))
11647 (setq todomatcher (if (> (length orlist) 1)
11648 (cons 'or orlist) (car orlist))))
11650 ;; Return the string and lisp forms of the matcher
11651 (setq matcher (if todomatcher
11652 (list 'and tagsmatcher todomatcher)
11653 tagsmatcher))
11654 (cons match0 matcher)))
11656 (defun org-op-to-function (op &optional stringp)
11657 "Turn an operator into the appropriate function."
11658 (setq op
11659 (cond
11660 ((equal op "<" ) '(< string< org-time<))
11661 ((equal op ">" ) '(> org-string> org-time>))
11662 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11663 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11664 ((member op '("=" "==")) '(= string= org-time=))
11665 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11666 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11668 (defun org<> (a b) (not (= a b)))
11669 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11670 (defun org-string>= (a b) (not (string< a b)))
11671 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11672 (defun org-string<> (a b) (not (string= a b)))
11673 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11674 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11675 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11676 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11677 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11678 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11679 (defun org-2ft (s)
11680 "Convert S to a floating point time.
11681 If S is already a number, just return it. If it is a string, parse
11682 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11683 (cond
11684 ((numberp s) s)
11685 ((stringp s)
11686 (condition-case nil
11687 (float-time (apply 'encode-time (org-parse-time-string s)))
11688 (error 0.)))
11689 (t 0.)))
11691 (defun org-time-today ()
11692 "Time in seconds today at 0:00.
11693 Returns the float number of seconds since the beginning of the
11694 epoch to the beginning of today (00:00)."
11695 (float-time (apply 'encode-time
11696 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11698 (defun org-matcher-time (s)
11699 "Interpret a time comparison value."
11700 (save-match-data
11701 (cond
11702 ((string= s "<now>") (float-time))
11703 ((string= s "<today>") (org-time-today))
11704 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11705 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11706 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11707 (+ (org-time-today)
11708 (* (string-to-number (match-string 1 s))
11709 (cdr (assoc (match-string 2 s)
11710 '(("d" . 86400.0) ("w" . 604800.0)
11711 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11712 (t (org-2ft s)))))
11714 (defun org-match-any-p (re list)
11715 "Does re match any element of list?"
11716 (setq list (mapcar (lambda (x) (string-match re x)) list))
11717 (delq nil list))
11719 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11720 (defvar org-tags-overlay (org-make-overlay 1 1))
11721 (org-detach-overlay org-tags-overlay)
11723 (defun org-get-local-tags-at (&optional pos)
11724 "Get a list of tags defined in the current headline."
11725 (org-get-tags-at pos 'local))
11727 (defun org-get-local-tags ()
11728 "Get a list of tags defined in the current headline."
11729 (org-get-tags-at nil 'local))
11731 (defun org-get-tags-at (&optional pos local)
11732 "Get a list of all headline tags applicable at POS.
11733 POS defaults to point. If tags are inherited, the list contains
11734 the targets in the same sequence as the headlines appear, i.e.
11735 the tags of the current headline come last.
11736 When LOCAL is non-nil, only return tags from the current headline,
11737 ignore inherited ones."
11738 (interactive)
11739 (if (and org-trust-scanner-tags
11740 (or (not pos) (equal pos (point)))
11741 (not local))
11742 org-scanner-tags
11743 (let (tags ltags lastpos parent)
11744 (save-excursion
11745 (save-restriction
11746 (widen)
11747 (goto-char (or pos (point)))
11748 (save-match-data
11749 (catch 'done
11750 (condition-case nil
11751 (progn
11752 (org-back-to-heading t)
11753 (while (not (equal lastpos (point)))
11754 (setq lastpos (point))
11755 (when (looking-at
11756 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11757 (setq ltags (org-split-string
11758 (org-match-string-no-properties 1) ":"))
11759 (when parent
11760 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11761 (setq tags (append
11762 (if parent
11763 (org-remove-uniherited-tags ltags)
11764 ltags)
11765 tags)))
11766 (or org-use-tag-inheritance (throw 'done t))
11767 (if local (throw 'done t))
11768 (or (org-up-heading-safe) (error nil))
11769 (setq parent t)))
11770 (error nil)))))
11771 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11773 (defun org-add-prop-inherited (s)
11774 (add-text-properties 0 (length s) '(inherited t) s)
11777 (defun org-toggle-tag (tag &optional onoff)
11778 "Toggle the tag TAG for the current line.
11779 If ONOFF is `on' or `off', don't toggle but set to this state."
11780 (let (res current)
11781 (save-excursion
11782 (org-back-to-heading t)
11783 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11784 (point-at-eol) t)
11785 (progn
11786 (setq current (match-string 1))
11787 (replace-match ""))
11788 (setq current ""))
11789 (setq current (nreverse (org-split-string current ":")))
11790 (cond
11791 ((eq onoff 'on)
11792 (setq res t)
11793 (or (member tag current) (push tag current)))
11794 ((eq onoff 'off)
11795 (or (not (member tag current)) (setq current (delete tag current))))
11796 (t (if (member tag current)
11797 (setq current (delete tag current))
11798 (setq res t)
11799 (push tag current))))
11800 (end-of-line 1)
11801 (if current
11802 (progn
11803 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11804 (org-set-tags nil t))
11805 (delete-horizontal-space))
11806 (run-hooks 'org-after-tags-change-hook))
11807 res))
11809 (defun org-align-tags-here (to-col)
11810 ;; Assumes that this is a headline
11811 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11812 (beginning-of-line 1)
11813 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11814 (< pos (match-beginning 2)))
11815 (progn
11816 (setq tags-l (- (match-end 2) (match-beginning 2)))
11817 (goto-char (match-beginning 1))
11818 (insert " ")
11819 (delete-region (point) (1+ (match-beginning 2)))
11820 (setq ncol (max (1+ (current-column))
11821 (1+ col)
11822 (if (> to-col 0)
11823 to-col
11824 (- (abs to-col) tags-l))))
11825 (setq p (point))
11826 (insert (make-string (- ncol (current-column)) ?\ ))
11827 (setq ncol (current-column))
11828 (when indent-tabs-mode (tabify p (point-at-eol)))
11829 (org-move-to-column (min ncol col) t))
11830 (goto-char pos))))
11832 (defun org-set-tags-command (&optional arg just-align)
11833 "Call the set-tags command for the current entry."
11834 (interactive "P")
11835 (if (org-on-heading-p)
11836 (org-set-tags arg just-align)
11837 (save-excursion
11838 (org-back-to-heading t)
11839 (org-set-tags arg just-align))))
11841 (defun org-set-tags-to (data)
11842 "Set the tags of the current entry to DATA, replacing the current tags.
11843 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11844 If DATA is nil or the empty string, any tags will be removed."
11845 (interactive "sTags: ")
11846 (setq data
11847 (cond
11848 ((eq data nil) "")
11849 ((equal data "") "")
11850 ((stringp data)
11851 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11852 ":"))
11853 ((listp data)
11854 (concat ":" (mapconcat 'identity data ":") ":"))
11855 (t nil)))
11856 (when data
11857 (save-excursion
11858 (org-back-to-heading t)
11859 (when (looking-at org-complex-heading-regexp)
11860 (if (match-end 5)
11861 (progn
11862 (goto-char (match-beginning 5))
11863 (insert data)
11864 (delete-region (point) (point-at-eol))
11865 (org-set-tags nil 'align))
11866 (goto-char (point-at-eol))
11867 (insert " " data)
11868 (org-set-tags nil 'align)))
11869 (beginning-of-line 1)
11870 (if (looking-at ".*?\\([ \t]+\\)$")
11871 (delete-region (match-beginning 1) (match-end 1))))))
11873 (defun org-set-tags (&optional arg just-align)
11874 "Set the tags for the current headline.
11875 With prefix ARG, realign all tags in headings in the current buffer."
11876 (interactive "P")
11877 (let* ((re (concat "^" outline-regexp))
11878 (current (org-get-tags-string))
11879 (col (current-column))
11880 (org-setting-tags t)
11881 table current-tags inherited-tags ; computed below when needed
11882 tags p0 c0 c1 rpl)
11883 (if arg
11884 (save-excursion
11885 (goto-char (point-min))
11886 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11887 (while (re-search-forward re nil t)
11888 (org-set-tags nil t)
11889 (end-of-line 1)))
11890 (message "All tags realigned to column %d" org-tags-column))
11891 (if just-align
11892 (setq tags current)
11893 ;; Get a new set of tags from the user
11894 (save-excursion
11895 (setq table (append org-tag-persistent-alist
11896 (or org-tag-alist (org-get-buffer-tags))
11897 (and org-complete-tags-always-offer-all-agenda-tags
11898 (org-global-tags-completion-table (org-agenda-files))))
11899 org-last-tags-completion-table table
11900 current-tags (org-split-string current ":")
11901 inherited-tags (nreverse
11902 (nthcdr (length current-tags)
11903 (nreverse (org-get-tags-at))))
11904 tags
11905 (if (or (eq t org-use-fast-tag-selection)
11906 (and org-use-fast-tag-selection
11907 (delq nil (mapcar 'cdr table))))
11908 (org-fast-tag-selection
11909 current-tags inherited-tags table
11910 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11911 (let ((org-add-colon-after-tag-completion t))
11912 (org-trim
11913 (org-without-partial-completion
11914 (org-icompleting-read "Tags: " 'org-tags-completion-function
11915 nil nil current 'org-tags-history)))))))
11916 (while (string-match "[-+&]+" tags)
11917 ;; No boolean logic, just a list
11918 (setq tags (replace-match ":" t t tags))))
11920 (if org-tags-sort-function
11921 (setq tags (mapconcat 'identity
11922 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11923 org-tags-sort-function) ":")))
11925 (if (string-match "\\`[\t ]*\\'" tags)
11926 (setq tags "")
11927 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11928 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11930 ;; Insert new tags at the correct column
11931 (beginning-of-line 1)
11932 (cond
11933 ((and (equal current "") (equal tags "")))
11934 ((re-search-forward
11935 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11936 (point-at-eol) t)
11937 (if (equal tags "")
11938 (setq rpl "")
11939 (goto-char (match-beginning 0))
11940 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
11941 (1+ (point)) (point))
11942 c1 (max (1+ c0) (if (> org-tags-column 0)
11943 org-tags-column
11944 (- (- org-tags-column) (length tags))))
11945 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11946 (replace-match rpl t t)
11947 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11948 tags)
11949 (t (error "Tags alignment failed")))
11950 (org-move-to-column col)
11951 (unless just-align
11952 (run-hooks 'org-after-tags-change-hook)))))
11954 (defun org-change-tag-in-region (beg end tag off)
11955 "Add or remove TAG for each entry in the region.
11956 This works in the agenda, and also in an org-mode buffer."
11957 (interactive
11958 (list (region-beginning) (region-end)
11959 (let ((org-last-tags-completion-table
11960 (if (org-mode-p)
11961 (org-get-buffer-tags)
11962 (org-global-tags-completion-table))))
11963 (org-icompleting-read
11964 "Tag: " 'org-tags-completion-function nil nil nil
11965 'org-tags-history))
11966 (progn
11967 (message "[s]et or [r]emove? ")
11968 (equal (read-char-exclusive) ?r))))
11969 (if (fboundp 'deactivate-mark) (deactivate-mark))
11970 (let ((agendap (equal major-mode 'org-agenda-mode))
11971 l1 l2 m buf pos newhead (cnt 0))
11972 (goto-char end)
11973 (setq l2 (1- (org-current-line)))
11974 (goto-char beg)
11975 (setq l1 (org-current-line))
11976 (loop for l from l1 to l2 do
11977 (org-goto-line l)
11978 (setq m (get-text-property (point) 'org-hd-marker))
11979 (when (or (and (org-mode-p) (org-on-heading-p))
11980 (and agendap m))
11981 (setq buf (if agendap (marker-buffer m) (current-buffer))
11982 pos (if agendap m (point)))
11983 (with-current-buffer buf
11984 (save-excursion
11985 (save-restriction
11986 (goto-char pos)
11987 (setq cnt (1+ cnt))
11988 (org-toggle-tag tag (if off 'off 'on))
11989 (setq newhead (org-get-heading)))))
11990 (and agendap (org-agenda-change-all-lines newhead m))))
11991 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11993 (defun org-tags-completion-function (string predicate &optional flag)
11994 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11995 (confirm (lambda (x) (stringp (car x)))))
11996 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11997 (setq s1 (match-string 1 string)
11998 s2 (match-string 2 string))
11999 (setq s1 "" s2 string))
12000 (cond
12001 ((eq flag nil)
12002 ;; try completion
12003 (setq rtn (try-completion s2 ctable confirm))
12004 (if (stringp rtn)
12005 (setq rtn
12006 (concat s1 s2 (substring rtn (length s2))
12007 (if (and org-add-colon-after-tag-completion
12008 (assoc rtn ctable))
12009 ":" ""))))
12010 rtn)
12011 ((eq flag t)
12012 ;; all-completions
12013 (all-completions s2 ctable confirm)
12015 ((eq flag 'lambda)
12016 ;; exact match?
12017 (assoc s2 ctable)))
12020 (defun org-fast-tag-insert (kwd tags face &optional end)
12021 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12022 (insert (format "%-12s" (concat kwd ":"))
12023 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12024 (or end "")))
12026 (defun org-fast-tag-show-exit (flag)
12027 (save-excursion
12028 (org-goto-line 3)
12029 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12030 (replace-match ""))
12031 (when flag
12032 (end-of-line 1)
12033 (org-move-to-column (- (window-width) 19) t)
12034 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12036 (defun org-set-current-tags-overlay (current prefix)
12037 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12038 (if (featurep 'xemacs)
12039 (org-overlay-display org-tags-overlay (concat prefix s)
12040 'secondary-selection)
12041 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12042 (org-overlay-display org-tags-overlay (concat prefix s)))))
12044 (defvar org-last-tag-selection-key nil)
12045 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12046 "Fast tag selection with single keys.
12047 CURRENT is the current list of tags in the headline, INHERITED is the
12048 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12049 possibly with grouping information. TODO-TABLE is a similar table with
12050 TODO keywords, should these have keys assigned to them.
12051 If the keys are nil, a-z are automatically assigned.
12052 Returns the new tags string, or nil to not change the current settings."
12053 (let* ((fulltable (append table todo-table))
12054 (maxlen (apply 'max (mapcar
12055 (lambda (x)
12056 (if (stringp (car x)) (string-width (car x)) 0))
12057 fulltable)))
12058 (buf (current-buffer))
12059 (expert (eq org-fast-tag-selection-single-key 'expert))
12060 (buffer-tags nil)
12061 (fwidth (+ maxlen 3 1 3))
12062 (ncol (/ (- (window-width) 4) fwidth))
12063 (i-face 'org-done)
12064 (c-face 'org-todo)
12065 tg cnt e c char c1 c2 ntable tbl rtn
12066 ov-start ov-end ov-prefix
12067 (exit-after-next org-fast-tag-selection-single-key)
12068 (done-keywords org-done-keywords)
12069 groups ingroup)
12070 (save-excursion
12071 (beginning-of-line 1)
12072 (if (looking-at
12073 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12074 (setq ov-start (match-beginning 1)
12075 ov-end (match-end 1)
12076 ov-prefix "")
12077 (setq ov-start (1- (point-at-eol))
12078 ov-end (1+ ov-start))
12079 (skip-chars-forward "^\n\r")
12080 (setq ov-prefix
12081 (concat
12082 (buffer-substring (1- (point)) (point))
12083 (if (> (current-column) org-tags-column)
12085 (make-string (- org-tags-column (current-column)) ?\ ))))))
12086 (org-move-overlay org-tags-overlay ov-start ov-end)
12087 (save-window-excursion
12088 (if expert
12089 (set-buffer (get-buffer-create " *Org tags*"))
12090 (delete-other-windows)
12091 (split-window-vertically)
12092 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12093 (erase-buffer)
12094 (org-set-local 'org-done-keywords done-keywords)
12095 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12096 (org-fast-tag-insert "Current" current c-face "\n\n")
12097 (org-fast-tag-show-exit exit-after-next)
12098 (org-set-current-tags-overlay current ov-prefix)
12099 (setq tbl fulltable char ?a cnt 0)
12100 (while (setq e (pop tbl))
12101 (cond
12102 ((equal (car e) :startgroup)
12103 (push '() groups) (setq ingroup t)
12104 (when (not (= cnt 0))
12105 (setq cnt 0)
12106 (insert "\n"))
12107 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12108 ((equal (car e) :endgroup)
12109 (setq ingroup nil cnt 0)
12110 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12111 ((equal e '(:newline))
12112 (when (not (= cnt 0))
12113 (setq cnt 0)
12114 (insert "\n")
12115 (setq e (car tbl))
12116 (while (equal (car tbl) '(:newline))
12117 (insert "\n")
12118 (setq tbl (cdr tbl)))))
12120 (setq tg (copy-sequence (car e)) c2 nil)
12121 (if (cdr e)
12122 (setq c (cdr e))
12123 ;; automatically assign a character.
12124 (setq c1 (string-to-char
12125 (downcase (substring
12126 tg (if (= (string-to-char tg) ?@) 1 0)))))
12127 (if (or (rassoc c1 ntable) (rassoc c1 table))
12128 (while (or (rassoc char ntable) (rassoc char table))
12129 (setq char (1+ char)))
12130 (setq c2 c1))
12131 (setq c (or c2 char)))
12132 (if ingroup (push tg (car groups)))
12133 (setq tg (org-add-props tg nil 'face
12134 (cond
12135 ((not (assoc tg table))
12136 (org-get-todo-face tg))
12137 ((member tg current) c-face)
12138 ((member tg inherited) i-face)
12139 (t nil))))
12140 (if (and (= cnt 0) (not ingroup)) (insert " "))
12141 (insert "[" c "] " tg (make-string
12142 (- fwidth 4 (length tg)) ?\ ))
12143 (push (cons tg c) ntable)
12144 (when (= (setq cnt (1+ cnt)) ncol)
12145 (insert "\n")
12146 (if ingroup (insert " "))
12147 (setq cnt 0)))))
12148 (setq ntable (nreverse ntable))
12149 (insert "\n")
12150 (goto-char (point-min))
12151 (if (not expert) (org-fit-window-to-buffer))
12152 (setq rtn
12153 (catch 'exit
12154 (while t
12155 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12156 (if (not groups) "no " "")
12157 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12158 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12159 (setq org-last-tag-selection-key c)
12160 (cond
12161 ((= c ?\r) (throw 'exit t))
12162 ((= c ?!)
12163 (setq groups (not groups))
12164 (goto-char (point-min))
12165 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12166 ((= c ?\C-c)
12167 (if (not expert)
12168 (org-fast-tag-show-exit
12169 (setq exit-after-next (not exit-after-next)))
12170 (setq expert nil)
12171 (delete-other-windows)
12172 (split-window-vertically)
12173 (org-switch-to-buffer-other-window " *Org tags*")
12174 (org-fit-window-to-buffer)))
12175 ((or (= c ?\C-g)
12176 (and (= c ?q) (not (rassoc c ntable))))
12177 (org-detach-overlay org-tags-overlay)
12178 (setq quit-flag t))
12179 ((= c ?\ )
12180 (setq current nil)
12181 (if exit-after-next (setq exit-after-next 'now)))
12182 ((= c ?\t)
12183 (condition-case nil
12184 (setq tg (org-icompleting-read
12185 "Tag: "
12186 (or buffer-tags
12187 (with-current-buffer buf
12188 (org-get-buffer-tags)))))
12189 (quit (setq tg "")))
12190 (when (string-match "\\S-" tg)
12191 (add-to-list 'buffer-tags (list tg))
12192 (if (member tg current)
12193 (setq current (delete tg current))
12194 (push tg current)))
12195 (if exit-after-next (setq exit-after-next 'now)))
12196 ((setq e (rassoc c todo-table) tg (car e))
12197 (with-current-buffer buf
12198 (save-excursion (org-todo tg)))
12199 (if exit-after-next (setq exit-after-next 'now)))
12200 ((setq e (rassoc c ntable) tg (car e))
12201 (if (member tg current)
12202 (setq current (delete tg current))
12203 (loop for g in groups do
12204 (if (member tg g)
12205 (mapc (lambda (x)
12206 (setq current (delete x current)))
12207 g)))
12208 (push tg current))
12209 (if exit-after-next (setq exit-after-next 'now))))
12211 ;; Create a sorted list
12212 (setq current
12213 (sort current
12214 (lambda (a b)
12215 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12216 (if (eq exit-after-next 'now) (throw 'exit t))
12217 (goto-char (point-min))
12218 (beginning-of-line 2)
12219 (delete-region (point) (point-at-eol))
12220 (org-fast-tag-insert "Current" current c-face)
12221 (org-set-current-tags-overlay current ov-prefix)
12222 (while (re-search-forward
12223 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12224 (setq tg (match-string 1))
12225 (add-text-properties
12226 (match-beginning 1) (match-end 1)
12227 (list 'face
12228 (cond
12229 ((member tg current) c-face)
12230 ((member tg inherited) i-face)
12231 (t (get-text-property (match-beginning 1) 'face))))))
12232 (goto-char (point-min)))))
12233 (org-detach-overlay org-tags-overlay)
12234 (if rtn
12235 (mapconcat 'identity current ":")
12236 nil))))
12238 (defun org-get-tags-string ()
12239 "Get the TAGS string in the current headline."
12240 (unless (org-on-heading-p t)
12241 (error "Not on a heading"))
12242 (save-excursion
12243 (beginning-of-line 1)
12244 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12245 (org-match-string-no-properties 1)
12246 "")))
12248 (defun org-get-tags ()
12249 "Get the list of tags specified in the current headline."
12250 (org-split-string (org-get-tags-string) ":"))
12252 (defun org-get-buffer-tags ()
12253 "Get a table of all tags used in the buffer, for completion."
12254 (let (tags)
12255 (save-excursion
12256 (goto-char (point-min))
12257 (while (re-search-forward
12258 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12259 (when (equal (char-after (point-at-bol 0)) ?*)
12260 (mapc (lambda (x) (add-to-list 'tags x))
12261 (org-split-string (org-match-string-no-properties 1) ":")))))
12262 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12263 (mapcar 'list tags)))
12265 ;;;; The mapping API
12267 ;;;###autoload
12268 (defun org-map-entries (func &optional match scope &rest skip)
12269 "Call FUNC at each headline selected by MATCH in SCOPE.
12271 FUNC is a function or a lisp form. The function will be called without
12272 arguments, with the cursor positioned at the beginning of the headline.
12273 The return values of all calls to the function will be collected and
12274 returned as a list.
12276 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12277 does not need to preserve point. After evaluation, the cursor will be
12278 moved to the end of the line (presumably of the headline of the
12279 processed entry) and search continues from there. Under some
12280 circumstances, this may not produce the wanted results. For example,
12281 if you have removed (e.g. archived) the current (sub)tree it could
12282 mean that the next entry will be skipped entirely. In such cases, you
12283 can specify the position from where search should continue by making
12284 FUNC set the variable `org-map-continue-from' to the desired buffer
12285 position.
12287 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12288 Only headlines that are matched by this query will be considered during
12289 the iteration. When MATCH is nil or t, all headlines will be
12290 visited by the iteration.
12292 SCOPE determines the scope of this command. It can be any of:
12294 nil The current buffer, respecting the restriction if any
12295 tree The subtree started with the entry at point
12296 file The current buffer, without restriction
12297 file-with-archives
12298 The current buffer, and any archives associated with it
12299 agenda All agenda files
12300 agenda-with-archives
12301 All agenda files with any archive files associated with them
12302 \(file1 file2 ...)
12303 If this is a list, all files in the list will be scanned
12305 The remaining args are treated as settings for the skipping facilities of
12306 the scanner. The following items can be given here:
12308 archive skip trees with the archive tag.
12309 comment skip trees with the COMMENT keyword
12310 function or Emacs Lisp form:
12311 will be used as value for `org-agenda-skip-function', so whenever
12312 the function returns t, FUNC will not be called for that
12313 entry and search will continue from the point where the
12314 function leaves it.
12316 If your function needs to retrieve the tags including inherited tags
12317 at the *current* entry, you can use the value of the variable
12318 `org-scanner-tags' which will be much faster than getting the value
12319 with `org-get-tags-at'. If your function gets properties with
12320 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12321 to t around the call to `org-entry-properties' to get the same speedup.
12322 Note that if your function moves around to retrieve tags and properties at
12323 a *different* entry, you cannot use these techniques."
12324 (let* ((org-agenda-archives-mode nil) ; just to make sure
12325 (org-agenda-skip-archived-trees (memq 'archive skip))
12326 (org-agenda-skip-comment-trees (memq 'comment skip))
12327 (org-agenda-skip-function
12328 (car (org-delete-all '(comment archive) skip)))
12329 (org-tags-match-list-sublevels t)
12330 matcher file res
12331 org-todo-keywords-for-agenda
12332 org-done-keywords-for-agenda
12333 org-todo-keyword-alist-for-agenda
12334 org-drawers-for-agenda
12335 org-tag-alist-for-agenda)
12337 (cond
12338 ((eq match t) (setq matcher t))
12339 ((eq match nil) (setq matcher t))
12340 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12342 (save-excursion
12343 (save-restriction
12344 (when (eq scope 'tree)
12345 (org-back-to-heading t)
12346 (org-narrow-to-subtree)
12347 (setq scope nil))
12349 (if (not scope)
12350 (progn
12351 (org-prepare-agenda-buffers
12352 (list (buffer-file-name (current-buffer))))
12353 (setq res (org-scan-tags func matcher)))
12354 ;; Get the right scope
12355 (cond
12356 ((and scope (listp scope) (symbolp (car scope)))
12357 (setq scope (eval scope)))
12358 ((eq scope 'agenda)
12359 (setq scope (org-agenda-files t)))
12360 ((eq scope 'agenda-with-archives)
12361 (setq scope (org-agenda-files t))
12362 (setq scope (org-add-archive-files scope)))
12363 ((eq scope 'file)
12364 (setq scope (list (buffer-file-name))))
12365 ((eq scope 'file-with-archives)
12366 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12367 (org-prepare-agenda-buffers scope)
12368 (while (setq file (pop scope))
12369 (with-current-buffer (org-find-base-buffer-visiting file)
12370 (save-excursion
12371 (save-restriction
12372 (widen)
12373 (goto-char (point-min))
12374 (setq res (append res (org-scan-tags func matcher))))))))))
12375 res))
12377 ;;;; Properties
12379 ;;; Setting and retrieving properties
12381 (defconst org-special-properties
12382 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12383 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
12384 "The special properties valid in Org-mode.
12386 These are properties that are not defined in the property drawer,
12387 but in some other way.")
12389 (defconst org-default-properties
12390 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12391 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12392 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12393 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12394 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12395 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
12396 "Some properties that are used by Org-mode for various purposes.
12397 Being in this list makes sure that they are offered for completion.")
12399 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12400 "Regular expression matching the first line of a property drawer.")
12402 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12403 "Regular expression matching the first line of a property drawer.")
12405 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12406 "Regular expression matching the first line of a property drawer.")
12408 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12409 "Regular expression matching the first line of a property drawer.")
12411 (defconst org-property-drawer-re
12412 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12413 org-property-end-re "\\)\n?")
12414 "Matches an entire property drawer.")
12416 (defconst org-clock-drawer-re
12417 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12418 org-property-end-re "\\)\n?")
12419 "Matches an entire clock drawer.")
12421 (defun org-property-action ()
12422 "Do an action on properties."
12423 (interactive)
12424 (let (c)
12425 (org-at-property-p)
12426 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12427 (setq c (read-char-exclusive))
12428 (cond
12429 ((equal c ?s)
12430 (call-interactively 'org-set-property))
12431 ((equal c ?d)
12432 (call-interactively 'org-delete-property))
12433 ((equal c ?D)
12434 (call-interactively 'org-delete-property-globally))
12435 ((equal c ?c)
12436 (call-interactively 'org-compute-property-at-point))
12437 (t (error "No such property action %c" c)))))
12439 (defun org-set-effort (&optional value)
12440 "Set the effort property of the current entry.
12441 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12442 allowed value."
12443 (interactive "P")
12444 (if (equal value 0) (setq value 10))
12445 (let* ((completion-ignore-case t)
12446 (prop org-effort-property)
12447 (cur (org-entry-get nil prop))
12448 (allowed (org-property-get-allowed-values nil prop 'table))
12449 (existing (mapcar 'list (org-property-values prop)))
12451 (val (cond
12452 ((stringp value) value)
12453 ((and allowed (integerp value))
12454 (or (car (nth (1- value) allowed))
12455 (car (org-last allowed))))
12456 (allowed
12457 (message "Select 1-9,0, [RET%s]: %s"
12458 (if cur (concat "=" cur) "")
12459 (mapconcat 'car allowed " "))
12460 (setq rpl (read-char-exclusive))
12461 (if (equal rpl ?\r)
12463 (setq rpl (- rpl ?0))
12464 (if (equal rpl 0) (setq rpl 10))
12465 (if (and (> rpl 0) (<= rpl (length allowed)))
12466 (car (nth (1- rpl) allowed))
12467 (org-completing-read "Effort: " allowed nil))))
12469 (let (org-completion-use-ido org-completion-use-iswitchb)
12470 (org-completing-read
12471 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12472 (concat "[" cur "]") "")
12473 ": ")
12474 existing nil nil "" nil cur))))))
12475 (unless (equal (org-entry-get nil prop) val)
12476 (org-entry-put nil prop val))
12477 (message "%s is now %s" prop val)))
12479 (defun org-at-property-p ()
12480 "Is the cursor in a property line?"
12481 ;; FIXME: Does not check if we are actually in the drawer.
12482 ;; FIXME: also returns true on any drawers.....
12483 ;; This is used by C-c C-c for property action.
12484 (save-excursion
12485 (beginning-of-line 1)
12486 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
12488 (defun org-get-property-block (&optional beg end force)
12489 "Return the (beg . end) range of the body of the property drawer.
12490 BEG and END can be beginning and end of subtree, if not given
12491 they will be found.
12492 If the drawer does not exist and FORCE is non-nil, create the drawer."
12493 (catch 'exit
12494 (save-excursion
12495 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12496 (end (or end (progn (outline-next-heading) (point)))))
12497 (goto-char beg)
12498 (if (re-search-forward org-property-start-re end t)
12499 (setq beg (1+ (match-end 0)))
12500 (if force
12501 (save-excursion
12502 (org-insert-property-drawer)
12503 (setq end (progn (outline-next-heading) (point))))
12504 (throw 'exit nil))
12505 (goto-char beg)
12506 (if (re-search-forward org-property-start-re end t)
12507 (setq beg (1+ (match-end 0)))))
12508 (if (re-search-forward org-property-end-re end t)
12509 (setq end (match-beginning 0))
12510 (or force (throw 'exit nil))
12511 (goto-char beg)
12512 (setq end beg)
12513 (org-indent-line-function)
12514 (insert ":END:\n"))
12515 (cons beg end)))))
12517 (defun org-entry-properties (&optional pom which specific)
12518 "Get all properties of the entry at point-or-marker POM.
12519 This includes the TODO keyword, the tags, time strings for deadline,
12520 scheduled, and clocking, and any additional properties defined in the
12521 entry. The return value is an alist, keys may occur multiple times
12522 if the property key was used several times.
12523 POM may also be nil, in which case the current entry is used.
12524 If WHICH is nil or `all', get all properties. If WHICH is
12525 `special' or `standard', only get that subclass. If WHICH
12526 is a string only get exactly this property. Specific can be a string, the
12527 specific property we are interested in. Specifying it can speed
12528 things up because then unnecessary parsing is avoided."
12529 (setq which (or which 'all))
12530 (org-with-point-at pom
12531 (let ((clockstr (substring org-clock-string 0 -1))
12532 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
12533 (case-fold-search nil)
12534 beg end range props sum-props key value string clocksum)
12535 (save-excursion
12536 (when (condition-case nil
12537 (and (org-mode-p) (org-back-to-heading t))
12538 (error nil))
12539 (setq beg (point))
12540 (setq sum-props (get-text-property (point) 'org-summaries))
12541 (setq clocksum (get-text-property (point) :org-clock-minutes))
12542 (outline-next-heading)
12543 (setq end (point))
12544 (when (memq which '(all special))
12545 ;; Get the special properties, like TODO and tags
12546 (goto-char beg)
12547 (when (and (or (not specific) (string= specific "TODO"))
12548 (looking-at org-todo-line-regexp) (match-end 2))
12549 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12550 (when (and (or (not specific) (string= specific "PRIORITY"))
12551 (looking-at org-priority-regexp))
12552 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12553 (when (and (or (not specific) (string= specific "TAGS"))
12554 (setq value (org-get-tags-string))
12555 (string-match "\\S-" value))
12556 (push (cons "TAGS" value) props))
12557 (when (and (or (not specific) (string= specific "ALLTAGS"))
12558 (setq value (org-get-tags-at)))
12559 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
12560 ":"))
12561 props))
12562 (when (or (not specific) (string= specific "BLOCKED"))
12563 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
12564 (when (or (not specific)
12565 (member specific org-all-time-keywords)
12566 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
12567 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12568 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12569 string (if (equal key clockstr)
12570 (org-no-properties
12571 (org-trim
12572 (buffer-substring
12573 (match-beginning 3) (goto-char (point-at-eol)))))
12574 (substring (org-match-string-no-properties 3) 1 -1)))
12575 (unless key
12576 (if (= (char-after (match-beginning 3)) ?\[)
12577 (setq key "TIMESTAMP_IA")
12578 (setq key "TIMESTAMP")))
12579 (when (or (equal key clockstr) (not (assoc key props)))
12580 (push (cons key string) props))))
12584 (when (memq which '(all standard))
12585 ;; Get the standard properties, like :PROP: ...
12586 (setq range (org-get-property-block beg end))
12587 (when range
12588 (goto-char (car range))
12589 (while (re-search-forward
12590 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12591 (cdr range) t)
12592 (setq key (org-match-string-no-properties 1)
12593 value (org-trim (or (org-match-string-no-properties 2) "")))
12594 (unless (member key excluded)
12595 (push (cons key (or value "")) props)))))
12596 (if clocksum
12597 (push (cons "CLOCKSUM"
12598 (org-columns-number-to-string (/ (float clocksum) 60.)
12599 'add_times))
12600 props))
12601 (unless (assoc "CATEGORY" props)
12602 (setq value (or (org-get-category)
12603 (progn (org-refresh-category-properties)
12604 (org-get-category))))
12605 (push (cons "CATEGORY" value) props))
12606 (append sum-props (nreverse props)))))))
12608 (defun org-entry-get (pom property &optional inherit)
12609 "Get value of PROPERTY for entry at point-or-marker POM.
12610 If INHERIT is non-nil and the entry does not have the property,
12611 then also check higher levels of the hierarchy.
12612 If INHERIT is the symbol `selective', use inheritance only if the setting
12613 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12614 If the property is present but empty, the return value is the empty string.
12615 If the property is not present at all, nil is returned."
12616 (org-with-point-at pom
12617 (if (and inherit (if (eq inherit 'selective)
12618 (org-property-inherit-p property)
12620 (org-entry-get-with-inheritance property)
12621 (if (member property org-special-properties)
12622 ;; We need a special property. Use `org-entry-properties' to
12623 ;; retrieve it, but specify the wanted property
12624 (cdr (assoc property (org-entry-properties nil 'special property)))
12625 (let ((range (org-get-property-block)))
12626 (if (and range
12627 (goto-char (car range))
12628 (re-search-forward
12629 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12630 (cdr range) t))
12631 ;; Found the property, return it.
12632 (if (match-end 1)
12633 (org-match-string-no-properties 1)
12634 "")))))))
12636 (defun org-property-or-variable-value (var &optional inherit)
12637 "Check if there is a property fixing the value of VAR.
12638 If yes, return this value. If not, return the current value of the variable."
12639 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12640 (if (and prop (stringp prop) (string-match "\\S-" prop))
12641 (read prop)
12642 (symbol-value var))))
12644 (defun org-entry-delete (pom property)
12645 "Delete the property PROPERTY from entry at point-or-marker POM."
12646 (org-with-point-at pom
12647 (if (member property org-special-properties)
12648 nil ; cannot delete these properties.
12649 (let ((range (org-get-property-block)))
12650 (if (and range
12651 (goto-char (car range))
12652 (re-search-forward
12653 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12654 (cdr range) t))
12655 (progn
12656 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12658 nil)))))
12660 ;; Multi-values properties are properties that contain multiple values
12661 ;; These values are assumed to be single words, separated by whitespace.
12662 (defun org-entry-add-to-multivalued-property (pom property value)
12663 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12664 (let* ((old (org-entry-get pom property))
12665 (values (and old (org-split-string old "[ \t]"))))
12666 (setq value (org-entry-protect-space value))
12667 (unless (member value values)
12668 (setq values (cons value values))
12669 (org-entry-put pom property
12670 (mapconcat 'identity values " ")))))
12672 (defun org-entry-remove-from-multivalued-property (pom property value)
12673 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12674 (let* ((old (org-entry-get pom property))
12675 (values (and old (org-split-string old "[ \t]"))))
12676 (setq value (org-entry-protect-space value))
12677 (when (member value values)
12678 (setq values (delete value values))
12679 (org-entry-put pom property
12680 (mapconcat 'identity values " ")))))
12682 (defun org-entry-member-in-multivalued-property (pom property value)
12683 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12684 (let* ((old (org-entry-get pom property))
12685 (values (and old (org-split-string old "[ \t]"))))
12686 (setq value (org-entry-protect-space value))
12687 (member value values)))
12689 (defun org-entry-get-multivalued-property (pom property)
12690 "Return a list of values in a multivalued property."
12691 (let* ((value (org-entry-get pom property))
12692 (values (and value (org-split-string value "[ \t]"))))
12693 (mapcar 'org-entry-restore-space values)))
12695 (defun org-entry-put-multivalued-property (pom property &rest values)
12696 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12697 VALUES should be a list of strings. Spaces will be protected."
12698 (org-entry-put pom property
12699 (mapconcat 'org-entry-protect-space values " "))
12700 (let* ((value (org-entry-get pom property))
12701 (values (and value (org-split-string value "[ \t]"))))
12702 (mapcar 'org-entry-restore-space values)))
12704 (defun org-entry-protect-space (s)
12705 "Protect spaces and newline in string S."
12706 (while (string-match " " s)
12707 (setq s (replace-match "%20" t t s)))
12708 (while (string-match "\n" s)
12709 (setq s (replace-match "%0A" t t s)))
12712 (defun org-entry-restore-space (s)
12713 "Restore spaces and newline in string S."
12714 (while (string-match "%20" s)
12715 (setq s (replace-match " " t t s)))
12716 (while (string-match "%0A" s)
12717 (setq s (replace-match "\n" t t s)))
12720 (defvar org-entry-property-inherited-from (make-marker)
12721 "Marker pointing to the entry from where a property was inherited.
12722 Each call to `org-entry-get-with-inheritance' will set this marker to the
12723 location of the entry where the inheritance search matched. If there was
12724 no match, the marker will point nowhere.
12725 Note that also `org-entry-get' calls this function, if the INHERIT flag
12726 is set.")
12728 (defun org-entry-get-with-inheritance (property)
12729 "Get entry property, and search higher levels if not present."
12730 (move-marker org-entry-property-inherited-from nil)
12731 (let (tmp)
12732 (save-excursion
12733 (save-restriction
12734 (widen)
12735 (catch 'ex
12736 (while t
12737 (when (setq tmp (org-entry-get nil property))
12738 (org-back-to-heading t)
12739 (move-marker org-entry-property-inherited-from (point))
12740 (throw 'ex tmp))
12741 (or (org-up-heading-safe) (throw 'ex nil)))))
12742 (or tmp
12743 (cdr (assoc property org-file-properties))
12744 (cdr (assoc property org-global-properties))
12745 (cdr (assoc property org-global-properties-fixed))))))
12747 (defvar org-property-changed-functions nil
12748 "Hook called when the value of a property has changed.
12749 Each hook function should accept two arguments, the name of the property
12750 and the new value.")
12752 (defun org-entry-put (pom property value)
12753 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12754 (org-with-point-at pom
12755 (org-back-to-heading t)
12756 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12757 range)
12758 (cond
12759 ((equal property "TODO")
12760 (when (and (stringp value) (string-match "\\S-" value)
12761 (not (member value org-todo-keywords-1)))
12762 (error "\"%s\" is not a valid TODO state" value))
12763 (if (or (not value)
12764 (not (string-match "\\S-" value)))
12765 (setq value 'none))
12766 (org-todo value)
12767 (org-set-tags nil 'align))
12768 ((equal property "PRIORITY")
12769 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12770 (string-to-char value) ?\ ))
12771 (org-set-tags nil 'align))
12772 ((equal property "SCHEDULED")
12773 (if (re-search-forward org-scheduled-time-regexp end t)
12774 (cond
12775 ((eq value 'earlier) (org-timestamp-change -1 'day))
12776 ((eq value 'later) (org-timestamp-change 1 'day))
12777 (t (call-interactively 'org-schedule)))
12778 (call-interactively 'org-schedule)))
12779 ((equal property "DEADLINE")
12780 (if (re-search-forward org-deadline-time-regexp end t)
12781 (cond
12782 ((eq value 'earlier) (org-timestamp-change -1 'day))
12783 ((eq value 'later) (org-timestamp-change 1 'day))
12784 (t (call-interactively 'org-deadline)))
12785 (call-interactively 'org-deadline)))
12786 ((member property org-special-properties)
12787 (error "The %s property can not yet be set with `org-entry-put'"
12788 property))
12789 (t ; a non-special property
12790 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12791 (setq range (org-get-property-block beg end 'force))
12792 (goto-char (car range))
12793 (if (re-search-forward
12794 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12795 (progn
12796 (delete-region (match-beginning 1) (match-end 1))
12797 (goto-char (match-beginning 1)))
12798 (goto-char (cdr range))
12799 (insert "\n")
12800 (backward-char 1)
12801 (org-indent-line-function)
12802 (insert ":" property ":"))
12803 (and value (insert " " value))
12804 (org-indent-line-function)))))
12805 (run-hook-with-args 'org-property-changed-functions property value)))
12807 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12808 "Get all property keys in the current buffer.
12809 With INCLUDE-SPECIALS, also list the special properties that reflect things
12810 like tags and TODO state.
12811 With INCLUDE-DEFAULTS, also include properties that has special meaning
12812 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12813 With INCLUDE-COLUMNS, also include property names given in COLUMN
12814 formats in the current buffer."
12815 (let (rtn range cfmt s p)
12816 (save-excursion
12817 (save-restriction
12818 (widen)
12819 (goto-char (point-min))
12820 (while (re-search-forward org-property-start-re nil t)
12821 (setq range (org-get-property-block))
12822 (goto-char (car range))
12823 (while (re-search-forward
12824 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12825 (cdr range) t)
12826 (add-to-list 'rtn (org-match-string-no-properties 1)))
12827 (outline-next-heading))))
12829 (when include-specials
12830 (setq rtn (append org-special-properties rtn)))
12832 (when include-defaults
12833 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12834 (add-to-list 'rtn org-effort-property))
12836 (when include-columns
12837 (save-excursion
12838 (save-restriction
12839 (widen)
12840 (goto-char (point-min))
12841 (while (re-search-forward
12842 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12843 nil t)
12844 (setq cfmt (match-string 2) s 0)
12845 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12846 cfmt s)
12847 (setq s (match-end 0)
12848 p (match-string 1 cfmt))
12849 (unless (or (equal p "ITEM")
12850 (member p org-special-properties))
12851 (add-to-list 'rtn (match-string 1 cfmt))))))))
12853 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12855 (defun org-property-values (key)
12856 "Return a list of all values of property KEY."
12857 (save-excursion
12858 (save-restriction
12859 (widen)
12860 (goto-char (point-min))
12861 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12862 values)
12863 (while (re-search-forward re nil t)
12864 (add-to-list 'values (org-trim (match-string 1))))
12865 (delete "" values)))))
12867 (defun org-insert-property-drawer ()
12868 "Insert a property drawer into the current entry."
12869 (interactive)
12870 (org-back-to-heading t)
12871 (looking-at outline-regexp)
12872 (let ((indent (if org-adapt-indentation
12873 (- (match-end 0)(match-beginning 0))
12875 (beg (point))
12876 (re (concat "^[ \t]*" org-keyword-time-regexp))
12877 end hiddenp)
12878 (outline-next-heading)
12879 (setq end (point))
12880 (goto-char beg)
12881 (while (re-search-forward re end t))
12882 (setq hiddenp (org-invisible-p))
12883 (end-of-line 1)
12884 (and (equal (char-after) ?\n) (forward-char 1))
12885 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12886 (if (member (match-string 1) '("CLOCK:" ":END:"))
12887 ;; just skip this line
12888 (beginning-of-line 2)
12889 ;; Drawer start, find the end
12890 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12891 (beginning-of-line 1)))
12892 (org-skip-over-state-notes)
12893 (skip-chars-backward " \t\n\r")
12894 (if (eq (char-before) ?*) (forward-char 1))
12895 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12896 (beginning-of-line 0)
12897 (org-indent-to-column indent)
12898 (beginning-of-line 2)
12899 (org-indent-to-column indent)
12900 (beginning-of-line 0)
12901 (if hiddenp
12902 (save-excursion
12903 (org-back-to-heading t)
12904 (hide-entry))
12905 (org-flag-drawer t))))
12907 (defun org-set-property (property value)
12908 "In the current entry, set PROPERTY to VALUE.
12909 When called interactively, this will prompt for a property name, offering
12910 completion on existing and default properties. And then it will prompt
12911 for a value, offering completion either on allowed values (via an inherited
12912 xxx_ALL property) or on existing values in other instances of this property
12913 in the current file."
12914 (interactive
12915 (let* ((completion-ignore-case t)
12916 (keys (org-buffer-property-keys nil t t))
12917 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12918 (prop (if (member prop0 keys)
12919 prop0
12920 (or (cdr (assoc (downcase prop0)
12921 (mapcar (lambda (x) (cons (downcase x) x))
12922 keys)))
12923 prop0)))
12924 (cur (org-entry-get nil prop))
12925 (allowed (org-property-get-allowed-values nil prop 'table))
12926 (existing (mapcar 'list (org-property-values prop)))
12927 (val (if allowed
12928 (org-completing-read "Value: " allowed nil
12929 (not (get-text-property 0 'org-unrestricted
12930 (caar allowed))))
12931 (let (org-completion-use-ido org-completion-use-iswitchb)
12932 (org-completing-read
12933 (concat "Value " (if (and cur (string-match "\\S-" cur))
12934 (concat "[" cur "]") "")
12935 ": ")
12936 existing nil nil "" nil cur)))))
12937 (list prop (if (equal val "") cur val))))
12938 (unless (equal (org-entry-get nil property) value)
12939 (org-entry-put nil property value)))
12941 (defun org-delete-property (property)
12942 "In the current entry, delete PROPERTY."
12943 (interactive
12944 (let* ((completion-ignore-case t)
12945 (prop (org-icompleting-read
12946 "Property: " (org-entry-properties nil 'standard))))
12947 (list prop)))
12948 (message "Property %s %s" property
12949 (if (org-entry-delete nil property)
12950 "deleted"
12951 "was not present in the entry")))
12953 (defun org-delete-property-globally (property)
12954 "Remove PROPERTY globally, from all entries."
12955 (interactive
12956 (let* ((completion-ignore-case t)
12957 (prop (org-icompleting-read
12958 "Globally remove property: "
12959 (mapcar 'list (org-buffer-property-keys)))))
12960 (list prop)))
12961 (save-excursion
12962 (save-restriction
12963 (widen)
12964 (goto-char (point-min))
12965 (let ((cnt 0))
12966 (while (re-search-forward
12967 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12968 nil t)
12969 (setq cnt (1+ cnt))
12970 (replace-match ""))
12971 (message "Property \"%s\" removed from %d entries" property cnt)))))
12973 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12975 (defun org-compute-property-at-point ()
12976 "Compute the property at point.
12977 This looks for an enclosing column format, extracts the operator and
12978 then applies it to the property in the column format's scope."
12979 (interactive)
12980 (unless (org-at-property-p)
12981 (error "Not at a property"))
12982 (let ((prop (org-match-string-no-properties 2)))
12983 (org-columns-get-format-and-top-level)
12984 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12985 (error "No operator defined for property %s" prop))
12986 (org-columns-compute prop)))
12988 (defvar org-property-allowed-value-functions nil
12989 "Hook for functions supplying allowed values for a specific property.
12990 The functions must take a single argument, the name of the property, and
12991 return a flat list of allowed values. If \":ETC\" is one of
12992 the values, this means that these values are intended as defaults for
12993 completion, but that other values should be allowed too.
12994 The functions must return nil if they are not responsible for this
12995 property.")
12997 (defun org-property-get-allowed-values (pom property &optional table)
12998 "Get allowed values for the property PROPERTY.
12999 When TABLE is non-nil, return an alist that can directly be used for
13000 completion."
13001 (let (vals)
13002 (cond
13003 ((equal property "TODO")
13004 (setq vals (org-with-point-at pom
13005 (append org-todo-keywords-1 '("")))))
13006 ((equal property "PRIORITY")
13007 (let ((n org-lowest-priority))
13008 (while (>= n org-highest-priority)
13009 (push (char-to-string n) vals)
13010 (setq n (1- n)))))
13011 ((member property org-special-properties))
13012 ((setq vals (run-hook-with-args-until-success
13013 'org-property-allowed-value-functions property)))
13015 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13016 (when (and vals (string-match "\\S-" vals))
13017 (setq vals (car (read-from-string (concat "(" vals ")"))))
13018 (setq vals (mapcar (lambda (x)
13019 (cond ((stringp x) x)
13020 ((numberp x) (number-to-string x))
13021 ((symbolp x) (symbol-name x))
13022 (t "???")))
13023 vals)))))
13024 (when (member ":ETC" vals)
13025 (setq vals (remove ":ETC" vals))
13026 (org-add-props (car vals) '(org-unrestricted t)))
13027 (if table (mapcar 'list vals) vals)))
13029 (defun org-property-previous-allowed-value (&optional previous)
13030 "Switch to the next allowed value for this property."
13031 (interactive)
13032 (org-property-next-allowed-value t))
13034 (defun org-property-next-allowed-value (&optional previous)
13035 "Switch to the next allowed value for this property."
13036 (interactive)
13037 (unless (org-at-property-p)
13038 (error "Not at a property"))
13039 (let* ((key (match-string 2))
13040 (value (match-string 3))
13041 (allowed (or (org-property-get-allowed-values (point) key)
13042 (and (member value '("[ ]" "[-]" "[X]"))
13043 '("[ ]" "[X]"))))
13044 nval)
13045 (unless allowed
13046 (error "Allowed values for this property have not been defined"))
13047 (if previous (setq allowed (reverse allowed)))
13048 (if (member value allowed)
13049 (setq nval (car (cdr (member value allowed)))))
13050 (setq nval (or nval (car allowed)))
13051 (if (equal nval value)
13052 (error "Only one allowed value for this property"))
13053 (org-at-property-p)
13054 (replace-match (concat " :" key ": " nval) t t)
13055 (org-indent-line-function)
13056 (beginning-of-line 1)
13057 (skip-chars-forward " \t")
13058 (run-hook-with-args 'org-property-changed-functions key nval)))
13060 (defun org-find-entry-with-id (ident)
13061 "Locate the entry that contains the ID property with exact value IDENT.
13062 IDENT can be a string, a symbol or a number, this function will search for
13063 the string representation of it.
13064 Return the position where this entry starts, or nil if there is no such entry."
13065 (interactive "sID: ")
13066 (let ((id (cond
13067 ((stringp ident) ident)
13068 ((symbol-name ident) (symbol-name ident))
13069 ((numberp ident) (number-to-string ident))
13070 (t (error "IDENT %s must be a string, symbol or number" ident))))
13071 (case-fold-search nil))
13072 (save-excursion
13073 (save-restriction
13074 (widen)
13075 (goto-char (point-min))
13076 (when (re-search-forward
13077 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13078 nil t)
13079 (org-back-to-heading t)
13080 (point))))))
13082 ;;;; Timestamps
13084 (defvar org-last-changed-timestamp nil)
13085 (defvar org-last-inserted-timestamp nil
13086 "The last time stamp inserted with `org-insert-time-stamp'.")
13087 (defvar org-time-was-given) ; dynamically scoped parameter
13088 (defvar org-end-time-was-given) ; dynamically scoped parameter
13089 (defvar org-ts-what) ; dynamically scoped parameter
13091 (defun org-time-stamp (arg &optional inactive)
13092 "Prompt for a date/time and insert a time stamp.
13093 If the user specifies a time like HH:MM, or if this command is called
13094 with a prefix argument, the time stamp will contain date and time.
13095 Otherwise, only the date will be included. All parts of a date not
13096 specified by the user will be filled in from the current date/time.
13097 So if you press just return without typing anything, the time stamp
13098 will represent the current date/time. If there is already a timestamp
13099 at the cursor, it will be modified."
13100 (interactive "P")
13101 (let* ((ts nil)
13102 (default-time
13103 ;; Default time is either today, or, when entering a range,
13104 ;; the range start.
13105 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13106 (save-excursion
13107 (re-search-backward
13108 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13109 (- (point) 20) t)))
13110 (apply 'encode-time (org-parse-time-string (match-string 1)))
13111 (current-time)))
13112 (default-input (and ts (org-get-compact-tod ts)))
13113 org-time-was-given org-end-time-was-given time)
13114 (cond
13115 ((and (org-at-timestamp-p t)
13116 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13117 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13118 (insert "--")
13119 (setq time (let ((this-command this-command))
13120 (org-read-date arg 'totime nil nil
13121 default-time default-input)))
13122 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13123 ((org-at-timestamp-p t)
13124 (setq time (let ((this-command this-command))
13125 (org-read-date arg 'totime nil nil default-time default-input)))
13126 (when (org-at-timestamp-p t) ; just to get the match data
13127 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13128 (replace-match "")
13129 (setq org-last-changed-timestamp
13130 (org-insert-time-stamp
13131 time (or org-time-was-given arg)
13132 inactive nil nil (list org-end-time-was-given))))
13133 (message "Timestamp updated"))
13135 (setq time (let ((this-command this-command))
13136 (org-read-date arg 'totime nil nil default-time default-input)))
13137 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13138 nil nil (list org-end-time-was-given))))))
13140 ;; FIXME: can we use this for something else, like computing time differences?
13141 (defun org-get-compact-tod (s)
13142 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13143 (let* ((t1 (match-string 1 s))
13144 (h1 (string-to-number (match-string 2 s)))
13145 (m1 (string-to-number (match-string 3 s)))
13146 (t2 (and (match-end 4) (match-string 5 s)))
13147 (h2 (and t2 (string-to-number (match-string 6 s))))
13148 (m2 (and t2 (string-to-number (match-string 7 s))))
13149 dh dm)
13150 (if (not t2)
13152 (setq dh (- h2 h1) dm (- m2 m1))
13153 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13154 (concat t1 "+" (number-to-string dh)
13155 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13157 (defun org-time-stamp-inactive (&optional arg)
13158 "Insert an inactive time stamp.
13159 An inactive time stamp is enclosed in square brackets instead of angle
13160 brackets. It is inactive in the sense that it does not trigger agenda entries,
13161 does not link to the calendar and cannot be changed with the S-cursor keys.
13162 So these are more for recording a certain time/date."
13163 (interactive "P")
13164 (org-time-stamp arg 'inactive))
13166 (defvar org-date-ovl (org-make-overlay 1 1))
13167 (org-overlay-put org-date-ovl 'face 'org-warning)
13168 (org-detach-overlay org-date-ovl)
13170 (defvar org-ans1) ; dynamically scoped parameter
13171 (defvar org-ans2) ; dynamically scoped parameter
13173 (defvar org-plain-time-of-day-regexp) ; defined below
13175 (defvar org-overriding-default-time nil) ; dynamically scoped
13176 (defvar org-read-date-overlay nil)
13177 (defvar org-dcst nil) ; dynamically scoped
13178 (defvar org-read-date-history nil)
13179 (defvar org-read-date-final-answer nil)
13181 (defun org-read-date (&optional with-time to-time from-string prompt
13182 default-time default-input)
13183 "Read a date, possibly a time, and make things smooth for the user.
13184 The prompt will suggest to enter an ISO date, but you can also enter anything
13185 which will at least partially be understood by `parse-time-string'.
13186 Unrecognized parts of the date will default to the current day, month, year,
13187 hour and minute. If this command is called to replace a timestamp at point,
13188 of to enter the second timestamp of a range, the default time is taken from the
13189 existing stamp. For example,
13190 3-2-5 --> 2003-02-05
13191 feb 15 --> currentyear-02-15
13192 sep 12 9 --> 2009-09-12
13193 12:45 --> today 12:45
13194 22 sept 0:34 --> currentyear-09-22 0:34
13195 12 --> currentyear-currentmonth-12
13196 Fri --> nearest Friday (today or later)
13197 etc.
13199 Furthermore you can specify a relative date by giving, as the *first* thing
13200 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13201 change in days weeks, months, years.
13202 With a single plus or minus, the date is relative to today. With a double
13203 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13204 +4d --> four days from today
13205 +4 --> same as above
13206 +2w --> two weeks from today
13207 ++5 --> five days from default date
13209 The function understands only English month and weekday abbreviations,
13210 but this can be configured with the variables `parse-time-months' and
13211 `parse-time-weekdays'.
13213 While prompting, a calendar is popped up - you can also select the
13214 date with the mouse (button 1). The calendar shows a period of three
13215 months. To scroll it to other months, use the keys `>' and `<'.
13216 If you don't like the calendar, turn it off with
13217 \(setq org-read-date-popup-calendar nil)
13219 With optional argument TO-TIME, the date will immediately be converted
13220 to an internal time.
13221 With an optional argument WITH-TIME, the prompt will suggest to also
13222 insert a time. Note that when WITH-TIME is not set, you can still
13223 enter a time, and this function will inform the calling routine about
13224 this change. The calling routine may then choose to change the format
13225 used to insert the time stamp into the buffer to include the time.
13226 With optional argument FROM-STRING, read from this string instead from
13227 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13228 the time/date that is used for everything that is not specified by the
13229 user."
13230 (require 'parse-time)
13231 (let* ((org-time-stamp-rounding-minutes
13232 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13233 (org-dcst org-display-custom-times)
13234 (ct (org-current-time))
13235 (def (or org-overriding-default-time default-time ct))
13236 (defdecode (decode-time def))
13237 (dummy (progn
13238 (when (< (nth 2 defdecode) org-extend-today-until)
13239 (setcar (nthcdr 2 defdecode) -1)
13240 (setcar (nthcdr 1 defdecode) 59)
13241 (setq def (apply 'encode-time defdecode)
13242 defdecode (decode-time def)))))
13243 (calendar-frame-setup nil)
13244 (calendar-move-hook nil)
13245 (calendar-view-diary-initially-flag nil)
13246 (view-diary-entries-initially nil)
13247 (calendar-view-holidays-initially-flag nil)
13248 (view-calendar-holidays-initially nil)
13249 (timestr (format-time-string
13250 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
13251 (prompt (concat (if prompt (concat prompt " ") "")
13252 (format "Date+time [%s]: " timestr)))
13253 ans (org-ans0 "") org-ans1 org-ans2 final)
13255 (cond
13256 (from-string (setq ans from-string))
13257 (org-read-date-popup-calendar
13258 (save-excursion
13259 (save-window-excursion
13260 (calendar)
13261 (calendar-forward-day (- (time-to-days def)
13262 (calendar-absolute-from-gregorian
13263 (calendar-current-date))))
13264 (org-eval-in-calendar nil t)
13265 (let* ((old-map (current-local-map))
13266 (map (copy-keymap calendar-mode-map))
13267 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13268 (org-defkey map (kbd "RET") 'org-calendar-select)
13269 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
13270 'org-calendar-select-mouse)
13271 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
13272 'org-calendar-select-mouse)
13273 (org-defkey minibuffer-local-map [(meta shift left)]
13274 (lambda () (interactive)
13275 (org-eval-in-calendar '(calendar-backward-month 1))))
13276 (org-defkey minibuffer-local-map [(meta shift right)]
13277 (lambda () (interactive)
13278 (org-eval-in-calendar '(calendar-forward-month 1))))
13279 (org-defkey minibuffer-local-map [(meta shift up)]
13280 (lambda () (interactive)
13281 (org-eval-in-calendar '(calendar-backward-year 1))))
13282 (org-defkey minibuffer-local-map [(meta shift down)]
13283 (lambda () (interactive)
13284 (org-eval-in-calendar '(calendar-forward-year 1))))
13285 (org-defkey minibuffer-local-map [?\e (shift left)]
13286 (lambda () (interactive)
13287 (org-eval-in-calendar '(calendar-backward-month 1))))
13288 (org-defkey minibuffer-local-map [?\e (shift right)]
13289 (lambda () (interactive)
13290 (org-eval-in-calendar '(calendar-forward-month 1))))
13291 (org-defkey minibuffer-local-map [?\e (shift up)]
13292 (lambda () (interactive)
13293 (org-eval-in-calendar '(calendar-backward-year 1))))
13294 (org-defkey minibuffer-local-map [?\e (shift down)]
13295 (lambda () (interactive)
13296 (org-eval-in-calendar '(calendar-forward-year 1))))
13297 (org-defkey minibuffer-local-map [(shift up)]
13298 (lambda () (interactive)
13299 (org-eval-in-calendar '(calendar-backward-week 1))))
13300 (org-defkey minibuffer-local-map [(shift down)]
13301 (lambda () (interactive)
13302 (org-eval-in-calendar '(calendar-forward-week 1))))
13303 (org-defkey minibuffer-local-map [(shift left)]
13304 (lambda () (interactive)
13305 (org-eval-in-calendar '(calendar-backward-day 1))))
13306 (org-defkey minibuffer-local-map [(shift right)]
13307 (lambda () (interactive)
13308 (org-eval-in-calendar '(calendar-forward-day 1))))
13309 (org-defkey minibuffer-local-map ">"
13310 (lambda () (interactive)
13311 (org-eval-in-calendar '(scroll-calendar-left 1))))
13312 (org-defkey minibuffer-local-map "<"
13313 (lambda () (interactive)
13314 (org-eval-in-calendar '(scroll-calendar-right 1))))
13315 (run-hooks 'org-read-date-minibuffer-setup-hook)
13316 (unwind-protect
13317 (progn
13318 (use-local-map map)
13319 (add-hook 'post-command-hook 'org-read-date-display)
13320 (setq org-ans0 (read-string prompt default-input
13321 'org-read-date-history nil))
13322 ;; org-ans0: from prompt
13323 ;; org-ans1: from mouse click
13324 ;; org-ans2: from calendar motion
13325 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13326 (remove-hook 'post-command-hook 'org-read-date-display)
13327 (use-local-map old-map)
13328 (when org-read-date-overlay
13329 (org-delete-overlay org-read-date-overlay)
13330 (setq org-read-date-overlay nil)))))))
13332 (t ; Naked prompt only
13333 (unwind-protect
13334 (setq ans (read-string prompt default-input
13335 'org-read-date-history timestr))
13336 (when org-read-date-overlay
13337 (org-delete-overlay org-read-date-overlay)
13338 (setq org-read-date-overlay nil)))))
13340 (setq final (org-read-date-analyze ans def defdecode))
13341 (setq org-read-date-final-answer ans)
13343 (if to-time
13344 (apply 'encode-time final)
13345 (if (and (boundp 'org-time-was-given) org-time-was-given)
13346 (format "%04d-%02d-%02d %02d:%02d"
13347 (nth 5 final) (nth 4 final) (nth 3 final)
13348 (nth 2 final) (nth 1 final))
13349 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13351 (defvar def)
13352 (defvar defdecode)
13353 (defvar with-time)
13354 (defvar org-read-date-analyze-futurep nil)
13355 (defun org-read-date-display ()
13356 "Display the current date prompt interpretation in the minibuffer."
13357 (when org-read-date-display-live
13358 (when org-read-date-overlay
13359 (org-delete-overlay org-read-date-overlay))
13360 (let ((p (point)))
13361 (end-of-line 1)
13362 (while (not (equal (buffer-substring
13363 (max (point-min) (- (point) 4)) (point))
13364 " "))
13365 (insert " "))
13366 (goto-char p))
13367 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13368 " " (or org-ans1 org-ans2)))
13369 (org-end-time-was-given nil)
13370 (f (org-read-date-analyze ans def defdecode))
13371 (fmts (if org-dcst
13372 org-time-stamp-custom-formats
13373 org-time-stamp-formats))
13374 (fmt (if (or with-time
13375 (and (boundp 'org-time-was-given) org-time-was-given))
13376 (cdr fmts)
13377 (car fmts)))
13378 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13379 (when (and org-end-time-was-given
13380 (string-match org-plain-time-of-day-regexp txt))
13381 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13382 org-end-time-was-given
13383 (substring txt (match-end 0)))))
13384 (when org-read-date-analyze-futurep
13385 (setq txt (concat txt " (=>F)")))
13386 (setq org-read-date-overlay
13387 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13388 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13390 (defun org-read-date-analyze (ans def defdecode)
13391 "Analyse the combined answer of the date prompt."
13392 ;; FIXME: cleanup and comment
13393 (let ((nowdecode (decode-time (current-time)))
13394 delta deltan deltaw deltadef year month day
13395 hour minute second wday pm h2 m2 tl wday1
13396 iso-year iso-weekday iso-week iso-year iso-date futurep)
13397 (setq org-read-date-analyze-futurep nil)
13398 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13399 (setq ans "+0"))
13401 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13402 (setq ans (replace-match "" t t ans)
13403 deltan (car delta)
13404 deltaw (nth 1 delta)
13405 deltadef (nth 2 delta)))
13407 ;; Check if there is an iso week date in there
13408 ;; If yes, store the info and postpone interpreting it until the rest
13409 ;; of the parsing is done
13410 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13411 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
13412 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
13413 iso-week (string-to-number (match-string 2 ans)))
13414 (setq ans (replace-match "" t t ans)))
13416 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
13417 (when (string-match
13418 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13419 (setq year (if (match-end 2)
13420 (string-to-number (match-string 2 ans))
13421 (string-to-number (format-time-string "%Y")))
13422 month (string-to-number (match-string 3 ans))
13423 day (string-to-number (match-string 4 ans)))
13424 (if (< year 100) (setq year (+ 2000 year)))
13425 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13426 t nil ans)))
13427 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13428 ;; If there is a time with am/pm, and *no* time without it, we convert
13429 ;; so that matching will be successful.
13430 (loop for i from 1 to 2 do ; twice, for end time as well
13431 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13432 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13433 (setq hour (string-to-number (match-string 1 ans))
13434 minute (if (match-end 3)
13435 (string-to-number (match-string 3 ans))
13437 pm (equal ?p
13438 (string-to-char (downcase (match-string 4 ans)))))
13439 (if (and (= hour 12) (not pm))
13440 (setq hour 0)
13441 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13442 (setq ans (replace-match (format "%02d:%02d" hour minute)
13443 t t ans))))
13445 ;; Check if a time range is given as a duration
13446 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13447 (setq hour (string-to-number (match-string 1 ans))
13448 h2 (+ hour (string-to-number (match-string 3 ans)))
13449 minute (string-to-number (match-string 2 ans))
13450 m2 (+ minute (if (match-end 5) (string-to-number
13451 (match-string 5 ans))0)))
13452 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13453 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13454 t t ans)))
13456 ;; Check if there is a time range
13457 (when (boundp 'org-end-time-was-given)
13458 (setq org-time-was-given nil)
13459 (when (and (string-match org-plain-time-of-day-regexp ans)
13460 (match-end 8))
13461 (setq org-end-time-was-given (match-string 8 ans))
13462 (setq ans (concat (substring ans 0 (match-beginning 7))
13463 (substring ans (match-end 7))))))
13465 (setq tl (parse-time-string ans)
13466 day (or (nth 3 tl) (nth 3 defdecode))
13467 month (or (nth 4 tl)
13468 (if (and org-read-date-prefer-future
13469 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
13470 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
13471 (nth 4 defdecode)))
13472 year (or (nth 5 tl)
13473 (if (and org-read-date-prefer-future
13474 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
13475 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
13476 (nth 5 defdecode)))
13477 hour (or (nth 2 tl) (nth 2 defdecode))
13478 minute (or (nth 1 tl) (nth 1 defdecode))
13479 second (or (nth 0 tl) 0)
13480 wday (nth 6 tl))
13482 (when (and (eq org-read-date-prefer-future 'time)
13483 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13484 (equal day (nth 3 nowdecode))
13485 (equal month (nth 4 nowdecode))
13486 (equal year (nth 5 nowdecode))
13487 (nth 2 tl)
13488 (or (< (nth 2 tl) (nth 2 nowdecode))
13489 (and (= (nth 2 tl) (nth 2 nowdecode))
13490 (nth 1 tl)
13491 (< (nth 1 tl) (nth 1 nowdecode)))))
13492 (setq day (1+ day)
13493 futurep t))
13495 ;; Special date definitions below
13496 (cond
13497 (iso-week
13498 ;; There was an iso week
13499 (setq futurep nil)
13500 (setq year (or iso-year year)
13501 day (or iso-weekday wday 1)
13502 wday nil ; to make sure that the trigger below does not match
13503 iso-date (calendar-gregorian-from-absolute
13504 (calendar-absolute-from-iso
13505 (list iso-week day year))))
13506 ; FIXME: Should we also push ISO weeks into the future?
13507 ; (when (and org-read-date-prefer-future
13508 ; (not iso-year)
13509 ; (< (calendar-absolute-from-gregorian iso-date)
13510 ; (time-to-days (current-time))))
13511 ; (setq year (1+ year)
13512 ; iso-date (calendar-gregorian-from-absolute
13513 ; (calendar-absolute-from-iso
13514 ; (list iso-week day year)))))
13515 (setq month (car iso-date)
13516 year (nth 2 iso-date)
13517 day (nth 1 iso-date)))
13518 (deltan
13519 (setq futurep nil)
13520 (unless deltadef
13521 (let ((now (decode-time (current-time))))
13522 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13523 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13524 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13525 ((equal deltaw "m") (setq month (+ month deltan)))
13526 ((equal deltaw "y") (setq year (+ year deltan)))))
13527 ((and wday (not (nth 3 tl)))
13528 (setq futurep nil)
13529 ;; Weekday was given, but no day, so pick that day in the week
13530 ;; on or after the derived date.
13531 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13532 (unless (equal wday wday1)
13533 (setq day (+ day (% (- wday wday1 -7) 7))))))
13534 (if (and (boundp 'org-time-was-given)
13535 (nth 2 tl))
13536 (setq org-time-was-given t))
13537 (if (< year 100) (setq year (+ 2000 year)))
13538 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13539 (setq org-read-date-analyze-futurep futurep)
13540 (list second minute hour day month year)))
13542 (defvar parse-time-weekdays)
13544 (defun org-read-date-get-relative (s today default)
13545 "Check string S for special relative date string.
13546 TODAY and DEFAULT are internal times, for today and for a default.
13547 Return shift list (N what def-flag)
13548 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13549 N is the number of WHATs to shift.
13550 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13551 the DEFAULT date rather than TODAY."
13552 (when (and
13553 (string-match
13554 (concat
13555 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13556 "\\([0-9]+\\)?"
13557 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13558 "\\([ \t]\\|$\\)") s)
13559 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13560 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13561 (string-to-char (substring (match-string 1 s) -1))
13562 ?+))
13563 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13564 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13565 (what (if (match-end 3) (match-string 3 s) "d"))
13566 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13567 (date (if rel default today))
13568 (wday (nth 6 (decode-time date)))
13569 delta)
13570 (if wday1
13571 (progn
13572 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13573 (if (= dir ?-) (setq delta (- delta 7)))
13574 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13575 (list delta "d" rel))
13576 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13578 (defun org-order-calendar-date-args (arg1 arg2 arg3)
13579 "Turn a user-specified date into the internal representation.
13580 The internal representation needed by the calendar is (month day year).
13581 This is a wrapper to handle the brain-dead convention in calendar that
13582 user function argument order change dependent on argument order."
13583 (if (boundp 'calendar-date-style)
13584 (cond
13585 ((eq calendar-date-style 'american)
13586 (list arg1 arg2 arg3))
13587 ((eq calendar-date-style 'european)
13588 (list arg2 arg1 arg3))
13589 ((eq calendar-date-style 'iso)
13590 (list arg2 arg3 arg1)))
13591 (if (org-bound-and-true-p european-calendar-style)
13592 (list arg2 arg1 arg3)
13593 (list arg1 arg2 arg3))))
13595 (defun org-eval-in-calendar (form &optional keepdate)
13596 "Eval FORM in the calendar window and return to current window.
13597 Also, store the cursor date in variable org-ans2."
13598 (let ((sf (selected-frame))
13599 (sw (selected-window)))
13600 (select-window (get-buffer-window "*Calendar*" t))
13601 (eval form)
13602 (when (and (not keepdate) (calendar-cursor-to-date))
13603 (let* ((date (calendar-cursor-to-date))
13604 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13605 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13606 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13607 (select-window sw)
13608 (org-select-frame-set-input-focus sf)))
13610 (defun org-calendar-select ()
13611 "Return to `org-read-date' with the date currently selected.
13612 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13613 (interactive)
13614 (when (calendar-cursor-to-date)
13615 (let* ((date (calendar-cursor-to-date))
13616 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13617 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13618 (if (active-minibuffer-window) (exit-minibuffer))))
13620 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13621 "Insert a date stamp for the date given by the internal TIME.
13622 WITH-HM means use the stamp format that includes the time of the day.
13623 INACTIVE means use square brackets instead of angular ones, so that the
13624 stamp will not contribute to the agenda.
13625 PRE and POST are optional strings to be inserted before and after the
13626 stamp.
13627 The command returns the inserted time stamp."
13628 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13629 stamp)
13630 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13631 (insert-before-markers (or pre ""))
13632 (insert-before-markers (setq stamp (format-time-string fmt time)))
13633 (when (listp extra)
13634 (setq extra (car extra))
13635 (if (and (stringp extra)
13636 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13637 (setq extra (format "-%02d:%02d"
13638 (string-to-number (match-string 1 extra))
13639 (string-to-number (match-string 2 extra))))
13640 (setq extra nil)))
13641 (when extra
13642 (backward-char 1)
13643 (insert-before-markers extra)
13644 (forward-char 1))
13645 (insert-before-markers (or post ""))
13646 (setq org-last-inserted-timestamp stamp)))
13648 (defun org-toggle-time-stamp-overlays ()
13649 "Toggle the use of custom time stamp formats."
13650 (interactive)
13651 (setq org-display-custom-times (not org-display-custom-times))
13652 (unless org-display-custom-times
13653 (let ((p (point-min)) (bmp (buffer-modified-p)))
13654 (while (setq p (next-single-property-change p 'display))
13655 (if (and (get-text-property p 'display)
13656 (eq (get-text-property p 'face) 'org-date))
13657 (remove-text-properties
13658 p (setq p (next-single-property-change p 'display))
13659 '(display t))))
13660 (set-buffer-modified-p bmp)))
13661 (if (featurep 'xemacs)
13662 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13663 (org-restart-font-lock)
13664 (setq org-table-may-need-update t)
13665 (if org-display-custom-times
13666 (message "Time stamps are overlayed with custom format")
13667 (message "Time stamp overlays removed")))
13669 (defun org-display-custom-time (beg end)
13670 "Overlay modified time stamp format over timestamp between BEG and END."
13671 (let* ((ts (buffer-substring beg end))
13672 t1 w1 with-hm tf time str w2 (off 0))
13673 (save-match-data
13674 (setq t1 (org-parse-time-string ts t))
13675 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13676 (setq off (- (match-end 0) (match-beginning 0)))))
13677 (setq end (- end off))
13678 (setq w1 (- end beg)
13679 with-hm (and (nth 1 t1) (nth 2 t1))
13680 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13681 time (org-fix-decoded-time t1)
13682 str (org-add-props
13683 (format-time-string
13684 (substring tf 1 -1) (apply 'encode-time time))
13685 nil 'mouse-face 'highlight)
13686 w2 (length str))
13687 (if (not (= w2 w1))
13688 (add-text-properties (1+ beg) (+ 2 beg)
13689 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13690 (if (featurep 'xemacs)
13691 (progn
13692 (put-text-property beg end 'invisible t)
13693 (put-text-property beg end 'end-glyph (make-glyph str)))
13694 (put-text-property beg end 'display str))))
13696 (defun org-translate-time (string)
13697 "Translate all timestamps in STRING to custom format.
13698 But do this only if the variable `org-display-custom-times' is set."
13699 (when org-display-custom-times
13700 (save-match-data
13701 (let* ((start 0)
13702 (re org-ts-regexp-both)
13703 t1 with-hm inactive tf time str beg end)
13704 (while (setq start (string-match re string start))
13705 (setq beg (match-beginning 0)
13706 end (match-end 0)
13707 t1 (save-match-data
13708 (org-parse-time-string (substring string beg end) t))
13709 with-hm (and (nth 1 t1) (nth 2 t1))
13710 inactive (equal (substring string beg (1+ beg)) "[")
13711 tf (funcall (if with-hm 'cdr 'car)
13712 org-time-stamp-custom-formats)
13713 time (org-fix-decoded-time t1)
13714 str (format-time-string
13715 (concat
13716 (if inactive "[" "<") (substring tf 1 -1)
13717 (if inactive "]" ">"))
13718 (apply 'encode-time time))
13719 string (replace-match str t t string)
13720 start (+ start (length str)))))))
13721 string)
13723 (defun org-fix-decoded-time (time)
13724 "Set 0 instead of nil for the first 6 elements of time.
13725 Don't touch the rest."
13726 (let ((n 0))
13727 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13729 (defun org-days-to-time (timestamp-string)
13730 "Difference between TIMESTAMP-STRING and now in days."
13731 (- (time-to-days (org-time-string-to-time timestamp-string))
13732 (time-to-days (current-time))))
13734 (defun org-deadline-close (timestamp-string &optional ndays)
13735 "Is the time in TIMESTAMP-STRING close to the current date?"
13736 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13737 (and (< (org-days-to-time timestamp-string) ndays)
13738 (not (org-entry-is-done-p))))
13740 (defun org-get-wdays (ts)
13741 "Get the deadline lead time appropriate for timestring TS."
13742 (cond
13743 ((<= org-deadline-warning-days 0)
13744 ;; 0 or negative, enforce this value no matter what
13745 (- org-deadline-warning-days))
13746 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13747 ;; lead time is specified.
13748 (floor (* (string-to-number (match-string 1 ts))
13749 (cdr (assoc (match-string 2 ts)
13750 '(("d" . 1) ("w" . 7)
13751 ("m" . 30.4) ("y" . 365.25)))))))
13752 ;; go for the default.
13753 (t org-deadline-warning-days)))
13755 (defun org-calendar-select-mouse (ev)
13756 "Return to `org-read-date' with the date currently selected.
13757 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13758 (interactive "e")
13759 (mouse-set-point ev)
13760 (when (calendar-cursor-to-date)
13761 (let* ((date (calendar-cursor-to-date))
13762 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13763 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13764 (if (active-minibuffer-window) (exit-minibuffer))))
13766 (defun org-check-deadlines (ndays)
13767 "Check if there are any deadlines due or past due.
13768 A deadline is considered due if it happens within `org-deadline-warning-days'
13769 days from today's date. If the deadline appears in an entry marked DONE,
13770 it is not shown. The prefix arg NDAYS can be used to test that many
13771 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13772 (interactive "P")
13773 (let* ((org-warn-days
13774 (cond
13775 ((equal ndays '(4)) 100000)
13776 (ndays (prefix-numeric-value ndays))
13777 (t (abs org-deadline-warning-days))))
13778 (case-fold-search nil)
13779 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13780 (callback
13781 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13783 (message "%d deadlines past-due or due within %d days"
13784 (org-occur regexp nil callback)
13785 org-warn-days)))
13787 (defun org-check-before-date (date)
13788 "Check if there are deadlines or scheduled entries before DATE."
13789 (interactive (list (org-read-date)))
13790 (let ((case-fold-search nil)
13791 (regexp (concat "\\<\\(" org-deadline-string
13792 "\\|" org-scheduled-string
13793 "\\) *<\\([^>]+\\)>"))
13794 (callback
13795 (lambda () (time-less-p
13796 (org-time-string-to-time (match-string 2))
13797 (org-time-string-to-time date)))))
13798 (message "%d entries before %s"
13799 (org-occur regexp nil callback) date)))
13801 (defun org-check-after-date (date)
13802 "Check if there are deadlines or scheduled entries after DATE."
13803 (interactive (list (org-read-date)))
13804 (let ((case-fold-search nil)
13805 (regexp (concat "\\<\\(" org-deadline-string
13806 "\\|" org-scheduled-string
13807 "\\) *<\\([^>]+\\)>"))
13808 (callback
13809 (lambda () (not
13810 (time-less-p
13811 (org-time-string-to-time (match-string 2))
13812 (org-time-string-to-time date))))))
13813 (message "%d entries after %s"
13814 (org-occur regexp nil callback) date)))
13816 (defun org-evaluate-time-range (&optional to-buffer)
13817 "Evaluate a time range by computing the difference between start and end.
13818 Normally the result is just printed in the echo area, but with prefix arg
13819 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13820 If the time range is actually in a table, the result is inserted into the
13821 next column.
13822 For time difference computation, a year is assumed to be exactly 365
13823 days in order to avoid rounding problems."
13824 (interactive "P")
13826 (org-clock-update-time-maybe)
13827 (save-excursion
13828 (unless (org-at-date-range-p t)
13829 (goto-char (point-at-bol))
13830 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13831 (if (not (org-at-date-range-p t))
13832 (error "Not at a time-stamp range, and none found in current line")))
13833 (let* ((ts1 (match-string 1))
13834 (ts2 (match-string 2))
13835 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13836 (match-end (match-end 0))
13837 (time1 (org-time-string-to-time ts1))
13838 (time2 (org-time-string-to-time ts2))
13839 (t1 (org-float-time time1))
13840 (t2 (org-float-time time2))
13841 (diff (abs (- t2 t1)))
13842 (negative (< (- t2 t1) 0))
13843 ;; (ys (floor (* 365 24 60 60)))
13844 (ds (* 24 60 60))
13845 (hs (* 60 60))
13846 (fy "%dy %dd %02d:%02d")
13847 (fy1 "%dy %dd")
13848 (fd "%dd %02d:%02d")
13849 (fd1 "%dd")
13850 (fh "%02d:%02d")
13851 y d h m align)
13852 (if havetime
13853 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13855 d (floor (/ diff ds)) diff (mod diff ds)
13856 h (floor (/ diff hs)) diff (mod diff hs)
13857 m (floor (/ diff 60)))
13858 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13860 d (floor (+ (/ diff ds) 0.5))
13861 h 0 m 0))
13862 (if (not to-buffer)
13863 (message "%s" (org-make-tdiff-string y d h m))
13864 (if (org-at-table-p)
13865 (progn
13866 (goto-char match-end)
13867 (setq align t)
13868 (and (looking-at " *|") (goto-char (match-end 0))))
13869 (goto-char match-end))
13870 (if (looking-at
13871 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13872 (replace-match ""))
13873 (if negative (insert " -"))
13874 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13875 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13876 (insert " " (format fh h m))))
13877 (if align (org-table-align))
13878 (message "Time difference inserted")))))
13880 (defun org-make-tdiff-string (y d h m)
13881 (let ((fmt "")
13882 (l nil))
13883 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13884 l (push y l)))
13885 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13886 l (push d l)))
13887 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13888 l (push h l)))
13889 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13890 l (push m l)))
13891 (apply 'format fmt (nreverse l))))
13893 (defun org-time-string-to-time (s)
13894 (apply 'encode-time (org-parse-time-string s)))
13895 (defun org-time-string-to-seconds (s)
13896 (org-float-time (org-time-string-to-time s)))
13898 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13899 "Convert a time stamp to an absolute day number.
13900 If there is a specifyer for a cyclic time stamp, get the closest date to
13901 DAYNR.
13902 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13903 the variable date is bound by the calendar when this is called."
13904 (cond
13905 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13906 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13907 daynr
13908 (+ daynr 1000)))
13909 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13910 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13911 (time-to-days (current-time))) (match-string 0 s)
13912 prefer show-all))
13913 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13915 (defun org-days-to-iso-week (days)
13916 "Return the iso week number."
13917 (require 'cal-iso)
13918 (car (calendar-iso-from-absolute days)))
13920 (defun org-small-year-to-year (year)
13921 "Convert 2-digit years into 4-digit years.
13922 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13923 The year 2000 cannot be abbreviated. Any year larger than 99
13924 is returned unchanged."
13925 (if (< year 38)
13926 (setq year (+ 2000 year))
13927 (if (< year 100)
13928 (setq year (+ 1900 year))))
13929 year)
13931 (defun org-time-from-absolute (d)
13932 "Return the time corresponding to date D.
13933 D may be an absolute day number, or a calendar-type list (month day year)."
13934 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13935 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13937 (defun org-calendar-holiday ()
13938 "List of holidays, for Diary display in Org-mode."
13939 (require 'holidays)
13940 (let ((hl (funcall
13941 (if (fboundp 'calendar-check-holidays)
13942 'calendar-check-holidays 'check-calendar-holidays) date)))
13943 (if hl (mapconcat 'identity hl "; "))))
13945 (defun org-diary-sexp-entry (sexp entry date)
13946 "Process a SEXP diary ENTRY for DATE."
13947 (require 'diary-lib)
13948 (let ((result (if calendar-debug-sexp
13949 (let ((stack-trace-on-error t))
13950 (eval (car (read-from-string sexp))))
13951 (condition-case nil
13952 (eval (car (read-from-string sexp)))
13953 (error
13954 (beep)
13955 (message "Bad sexp at line %d in %s: %s"
13956 (org-current-line)
13957 (buffer-file-name) sexp)
13958 (sleep-for 2))))))
13959 (cond ((stringp result) result)
13960 ((and (consp result)
13961 (stringp (cdr result))) (cdr result))
13962 (result entry)
13963 (t nil))))
13965 (defun org-diary-to-ical-string (frombuf)
13966 "Get iCalendar entries from diary entries in buffer FROMBUF.
13967 This uses the icalendar.el library."
13968 (let* ((tmpdir (if (featurep 'xemacs)
13969 (temp-directory)
13970 temporary-file-directory))
13971 (tmpfile (make-temp-name
13972 (expand-file-name "orgics" tmpdir)))
13973 buf rtn b e)
13974 (with-current-buffer frombuf
13975 (icalendar-export-region (point-min) (point-max) tmpfile)
13976 (setq buf (find-buffer-visiting tmpfile))
13977 (set-buffer buf)
13978 (goto-char (point-min))
13979 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13980 (setq b (match-beginning 0)))
13981 (goto-char (point-max))
13982 (if (re-search-backward "^END:VEVENT" nil t)
13983 (setq e (match-end 0)))
13984 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13985 (kill-buffer buf)
13986 (delete-file tmpfile)
13987 rtn))
13989 (defun org-closest-date (start current change prefer show-all)
13990 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13991 When PREFER is `past' return a date that is either CURRENT or past.
13992 When PREFER is `future', return a date that is either CURRENT or future.
13993 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13994 ;; Make the proper lists from the dates
13995 (catch 'exit
13996 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13997 dn dw sday cday n1 n2 n0
13998 d m y y1 y2 date1 date2 nmonths nm ny m2)
14000 (setq start (org-date-to-gregorian start)
14001 current (org-date-to-gregorian
14002 (if show-all
14003 current
14004 (time-to-days (current-time))))
14005 sday (calendar-absolute-from-gregorian start)
14006 cday (calendar-absolute-from-gregorian current))
14008 (if (<= cday sday) (throw 'exit sday))
14010 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
14011 (setq dn (string-to-number (match-string 1 change))
14012 dw (cdr (assoc (match-string 2 change) a1)))
14013 (error "Invalid change specifyer: %s" change))
14014 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
14015 (cond
14016 ((eq dw 'day)
14017 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
14018 n2 (+ n1 dn)))
14019 ((eq dw 'year)
14020 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
14021 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
14022 (setq date1 (list m d y1)
14023 n1 (calendar-absolute-from-gregorian date1)
14024 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
14025 n2 (calendar-absolute-from-gregorian date2)))
14026 ((eq dw 'month)
14027 ;; approx number of month between the two dates
14028 (setq nmonths (floor (/ (- cday sday) 30.436875)))
14029 ;; How often does dn fit in there?
14030 (setq d (nth 1 start) m (car start) y (nth 2 start)
14031 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
14032 m (+ m nm)
14033 ny (floor (/ m 12))
14034 y (+ y ny)
14035 m (- m (* ny 12)))
14036 (while (> m 12) (setq m (- m 12) y (1+ y)))
14037 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14038 (setq m2 (+ m dn) y2 y)
14039 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14040 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14041 (while (<= n2 cday)
14042 (setq n1 n2 m m2 y y2)
14043 (setq m2 (+ m dn) y2 y)
14044 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14045 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14046 ;; Make sure n1 is the earlier date
14047 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14048 (if show-all
14049 (cond
14050 ((eq prefer 'past) (if (= cday n2) n2 n1))
14051 ((eq prefer 'future) (if (= cday n1) n1 n2))
14052 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14053 (cond
14054 ((eq prefer 'past) (if (= cday n2) n2 n1))
14055 ((eq prefer 'future) (if (= cday n1) n1 n2))
14056 (t (if (= cday n1) n1 n2)))))))
14058 (defun org-date-to-gregorian (date)
14059 "Turn any specification of DATE into a gregorian date for the calendar."
14060 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14061 ((and (listp date) (= (length date) 3)) date)
14062 ((stringp date)
14063 (setq date (org-parse-time-string date))
14064 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14065 ((listp date)
14066 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14068 (defun org-parse-time-string (s &optional nodefault)
14069 "Parse the standard Org-mode time string.
14070 This should be a lot faster than the normal `parse-time-string'.
14071 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14072 hour and minute fields will be nil if not given."
14073 (if (string-match org-ts-regexp0 s)
14074 (list 0
14075 (if (or (match-beginning 8) (not nodefault))
14076 (string-to-number (or (match-string 8 s) "0")))
14077 (if (or (match-beginning 7) (not nodefault))
14078 (string-to-number (or (match-string 7 s) "0")))
14079 (string-to-number (match-string 4 s))
14080 (string-to-number (match-string 3 s))
14081 (string-to-number (match-string 2 s))
14082 nil nil nil)
14083 (error "Not a standard Org-mode time string: %s" s)))
14085 (defun org-timestamp-up (&optional arg)
14086 "Increase the date item at the cursor by one.
14087 If the cursor is on the year, change the year. If it is on the month or
14088 the day, change that.
14089 With prefix ARG, change by that many units."
14090 (interactive "p")
14091 (org-timestamp-change (prefix-numeric-value arg)))
14093 (defun org-timestamp-down (&optional arg)
14094 "Decrease the date item at the cursor by one.
14095 If the cursor is on the year, change the year. If it is on the month or
14096 the day, change that.
14097 With prefix ARG, change by that many units."
14098 (interactive "p")
14099 (org-timestamp-change (- (prefix-numeric-value arg))))
14101 (defun org-timestamp-up-day (&optional arg)
14102 "Increase the date in the time stamp by one day.
14103 With prefix ARG, change that many days."
14104 (interactive "p")
14105 (if (and (not (org-at-timestamp-p t))
14106 (org-on-heading-p))
14107 (org-todo 'up)
14108 (org-timestamp-change (prefix-numeric-value arg) 'day)))
14110 (defun org-timestamp-down-day (&optional arg)
14111 "Decrease the date in the time stamp by one day.
14112 With prefix ARG, change that many days."
14113 (interactive "p")
14114 (if (and (not (org-at-timestamp-p t))
14115 (org-on-heading-p))
14116 (org-todo 'down)
14117 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
14119 (defun org-at-timestamp-p (&optional inactive-ok)
14120 "Determine if the cursor is in or at a timestamp."
14121 (interactive)
14122 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
14123 (pos (point))
14124 (ans (or (looking-at tsr)
14125 (save-excursion
14126 (skip-chars-backward "^[<\n\r\t")
14127 (if (> (point) (point-min)) (backward-char 1))
14128 (and (looking-at tsr)
14129 (> (- (match-end 0) pos) -1))))))
14130 (and ans
14131 (boundp 'org-ts-what)
14132 (setq org-ts-what
14133 (cond
14134 ((= pos (match-beginning 0)) 'bracket)
14135 ((= pos (1- (match-end 0))) 'bracket)
14136 ((org-pos-in-match-range pos 2) 'year)
14137 ((org-pos-in-match-range pos 3) 'month)
14138 ((org-pos-in-match-range pos 7) 'hour)
14139 ((org-pos-in-match-range pos 8) 'minute)
14140 ((or (org-pos-in-match-range pos 4)
14141 (org-pos-in-match-range pos 5)) 'day)
14142 ((and (> pos (or (match-end 8) (match-end 5)))
14143 (< pos (match-end 0)))
14144 (- pos (or (match-end 8) (match-end 5))))
14145 (t 'day))))
14146 ans))
14148 (defun org-toggle-timestamp-type ()
14149 "Toggle the type (<active> or [inactive]) of a time stamp."
14150 (interactive)
14151 (when (org-at-timestamp-p t)
14152 (let ((beg (match-beginning 0)) (end (match-end 0))
14153 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14154 (save-excursion
14155 (goto-char beg)
14156 (while (re-search-forward "[][<>]" end t)
14157 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14158 t t)))
14159 (message "Timestamp is now %sactive"
14160 (if (equal (char-after beg) ?<) "" "in")))))
14162 (defun org-timestamp-change (n &optional what)
14163 "Change the date in the time stamp at point.
14164 The date will be changed by N times WHAT. WHAT can be `day', `month',
14165 `year', `minute', `second'. If WHAT is not given, the cursor position
14166 in the timestamp determines what will be changed."
14167 (let ((pos (point))
14168 with-hm inactive
14169 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14170 org-ts-what
14171 extra rem
14172 ts time time0)
14173 (if (not (org-at-timestamp-p t))
14174 (error "Not at a timestamp"))
14175 (if (and (not what) (eq org-ts-what 'bracket))
14176 (org-toggle-timestamp-type)
14177 (if (and (not what) (not (eq org-ts-what 'day))
14178 org-display-custom-times
14179 (get-text-property (point) 'display)
14180 (not (get-text-property (1- (point)) 'display)))
14181 (setq org-ts-what 'day))
14182 (setq org-ts-what (or what org-ts-what)
14183 inactive (= (char-after (match-beginning 0)) ?\[)
14184 ts (match-string 0))
14185 (replace-match "")
14186 (if (string-match
14187 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14189 (setq extra (match-string 1 ts)))
14190 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14191 (setq with-hm t))
14192 (setq time0 (org-parse-time-string ts))
14193 (when (and (eq org-ts-what 'minute)
14194 (eq current-prefix-arg nil))
14195 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14196 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14197 (setcar (cdr time0) (+ (nth 1 time0)
14198 (if (> n 0) (- rem) (- dm rem))))))
14199 (setq time
14200 (encode-time (or (car time0) 0)
14201 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14202 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14203 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14204 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14205 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14206 (nthcdr 6 time0)))
14207 (when (and (member org-ts-what '(hour minute))
14208 extra
14209 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14210 (setq extra (org-modify-ts-extra
14211 extra
14212 (if (eq org-ts-what 'hour) 2 5)
14213 n dm)))
14214 (when (integerp org-ts-what)
14215 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14216 (if (eq what 'calendar)
14217 (let ((cal-date (org-get-date-from-calendar)))
14218 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14219 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14220 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14221 (setcar time0 (or (car time0) 0))
14222 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
14223 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
14224 (setq time (apply 'encode-time time0))))
14225 (setq org-last-changed-timestamp
14226 (org-insert-time-stamp time with-hm inactive nil nil extra))
14227 (org-clock-update-time-maybe)
14228 (goto-char pos)
14229 ;; Try to recenter the calendar window, if any
14230 (if (and org-calendar-follow-timestamp-change
14231 (get-buffer-window "*Calendar*" t)
14232 (memq org-ts-what '(day month year)))
14233 (org-recenter-calendar (time-to-days time))))))
14235 (defun org-modify-ts-extra (s pos n dm)
14236 "Change the different parts of the lead-time and repeat fields in timestamp."
14237 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
14238 ng h m new rem)
14239 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
14240 (cond
14241 ((or (org-pos-in-match-range pos 2)
14242 (org-pos-in-match-range pos 3))
14243 (setq m (string-to-number (match-string 3 s))
14244 h (string-to-number (match-string 2 s)))
14245 (if (org-pos-in-match-range pos 2)
14246 (setq h (+ h n))
14247 (setq n (* dm (org-no-warnings (signum n))))
14248 (when (not (= 0 (setq rem (% m dm))))
14249 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
14250 (setq m (+ m n)))
14251 (if (< m 0) (setq m (+ m 60) h (1- h)))
14252 (if (> m 59) (setq m (- m 60) h (1+ h)))
14253 (setq h (min 24 (max 0 h)))
14254 (setq ng 1 new (format "-%02d:%02d" h m)))
14255 ((org-pos-in-match-range pos 6)
14256 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
14257 ((org-pos-in-match-range pos 5)
14258 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
14260 ((org-pos-in-match-range pos 9)
14261 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
14262 ((org-pos-in-match-range pos 8)
14263 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
14265 (when ng
14266 (setq s (concat
14267 (substring s 0 (match-beginning ng))
14269 (substring s (match-end ng))))))
14272 (defun org-recenter-calendar (date)
14273 "If the calendar is visible, recenter it to DATE."
14274 (let* ((win (selected-window))
14275 (cwin (get-buffer-window "*Calendar*" t))
14276 (calendar-move-hook nil))
14277 (when cwin
14278 (select-window cwin)
14279 (calendar-goto-date (if (listp date) date
14280 (calendar-gregorian-from-absolute date)))
14281 (select-window win))))
14283 (defun org-goto-calendar (&optional arg)
14284 "Go to the Emacs calendar at the current date.
14285 If there is a time stamp in the current line, go to that date.
14286 A prefix ARG can be used to force the current date."
14287 (interactive "P")
14288 (let ((tsr org-ts-regexp) diff
14289 (calendar-move-hook nil)
14290 (calendar-view-holidays-initially-flag nil)
14291 (view-calendar-holidays-initially nil)
14292 (calendar-view-diary-initially-flag nil)
14293 (view-diary-entries-initially nil))
14294 (if (or (org-at-timestamp-p)
14295 (save-excursion
14296 (beginning-of-line 1)
14297 (looking-at (concat ".*" tsr))))
14298 (let ((d1 (time-to-days (current-time)))
14299 (d2 (time-to-days
14300 (org-time-string-to-time (match-string 1)))))
14301 (setq diff (- d2 d1))))
14302 (calendar)
14303 (calendar-goto-today)
14304 (if (and diff (not arg)) (calendar-forward-day diff))))
14306 (defun org-get-date-from-calendar ()
14307 "Return a list (month day year) of date at point in calendar."
14308 (with-current-buffer "*Calendar*"
14309 (save-match-data
14310 (calendar-cursor-to-date))))
14312 (defun org-date-from-calendar ()
14313 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14314 If there is already a time stamp at the cursor position, update it."
14315 (interactive)
14316 (if (org-at-timestamp-p t)
14317 (org-timestamp-change 0 'calendar)
14318 (let ((cal-date (org-get-date-from-calendar)))
14319 (org-insert-time-stamp
14320 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14322 (defun org-minutes-to-hh:mm-string (m)
14323 "Compute H:MM from a number of minutes."
14324 (let ((h (/ m 60)))
14325 (setq m (- m (* 60 h)))
14326 (format org-time-clocksum-format h m)))
14328 (defun org-hh:mm-string-to-minutes (s)
14329 "Convert a string H:MM to a number of minutes.
14330 If the string is just a number, interpret it as minutes.
14331 In fact, the first hh:mm or number in the string will be taken,
14332 there can be extra stuff in the string.
14333 If no number is found, the return value is 0."
14334 (cond
14335 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14336 (+ (* (string-to-number (match-string 1 s)) 60)
14337 (string-to-number (match-string 2 s))))
14338 ((string-match "\\([0-9]+\\)" s)
14339 (string-to-number (match-string 1 s)))
14340 (t 0)))
14342 ;;;; Files
14344 (defun org-save-all-org-buffers ()
14345 "Save all Org-mode buffers without user confirmation."
14346 (interactive)
14347 (message "Saving all Org-mode buffers...")
14348 (save-some-buffers t 'org-mode-p)
14349 (when (featurep 'org-id) (org-id-locations-save))
14350 (message "Saving all Org-mode buffers... done"))
14352 (defun org-revert-all-org-buffers ()
14353 "Revert all Org-mode buffers.
14354 Prompt for confirmation when there are unsaved changes.
14355 Be sure you know what you are doing before letting this function
14356 overwrite your changes.
14358 This function is useful in a setup where one tracks org files
14359 with a version control system, to revert on one machine after pulling
14360 changes from another. I believe the procedure must be like this:
14362 1. M-x org-save-all-org-buffers
14363 2. Pull changes from the other machine, resolve conflicts
14364 3. M-x org-revert-all-org-buffers"
14365 (interactive)
14366 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14367 (error "Abort"))
14368 (save-excursion
14369 (save-window-excursion
14370 (mapc
14371 (lambda (b)
14372 (when (and (with-current-buffer b (org-mode-p))
14373 (with-current-buffer b buffer-file-name))
14374 (switch-to-buffer b)
14375 (revert-buffer t 'no-confirm)))
14376 (buffer-list))
14377 (when (and (featurep 'org-id) org-id-track-globally)
14378 (org-id-locations-load)))))
14380 ;;;; Agenda files
14382 ;;;###autoload
14383 (defun org-iswitchb (&optional arg)
14384 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14385 With a prefix argument, restrict available to files.
14386 With two prefix arguments, restrict available buffers to agenda files."
14387 (interactive "P")
14388 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14389 ((equal arg '(16)) (org-buffer-list 'agenda))
14390 (t (org-buffer-list)))))
14391 (switch-to-buffer
14392 (org-icompleting-read "Org buffer: "
14393 (mapcar 'list (mapcar 'buffer-name blist))
14394 nil t))))
14396 ;;;###autoload
14397 (defalias 'org-ido-switchb 'org-iswitchb)
14399 (defun org-buffer-list (&optional predicate exclude-tmp)
14400 "Return a list of Org buffers.
14401 PREDICATE can be `export', `files' or `agenda'.
14403 export restrict the list to Export buffers.
14404 files restrict the list to buffers visiting Org files.
14405 agenda restrict the list to buffers visiting agenda files.
14407 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14408 (let* ((bfn nil)
14409 (agenda-files (and (eq predicate 'agenda)
14410 (mapcar 'file-truename (org-agenda-files t))))
14411 (filter
14412 (cond
14413 ((eq predicate 'files)
14414 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14415 ((eq predicate 'export)
14416 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14417 ((eq predicate 'agenda)
14418 (lambda (b)
14419 (with-current-buffer b
14420 (and (eq major-mode 'org-mode)
14421 (setq bfn (buffer-file-name b))
14422 (member (file-truename bfn) agenda-files)))))
14423 (t (lambda (b) (with-current-buffer b
14424 (or (eq major-mode 'org-mode)
14425 (string-match "\*Org .*Export"
14426 (buffer-name b)))))))))
14427 (delq nil
14428 (mapcar
14429 (lambda(b)
14430 (if (and (funcall filter b)
14431 (or (not exclude-tmp)
14432 (not (string-match "tmp" (buffer-name b)))))
14434 nil))
14435 (buffer-list)))))
14437 (defun org-agenda-files (&optional unrestricted archives)
14438 "Get the list of agenda files.
14439 Optional UNRESTRICTED means return the full list even if a restriction
14440 is currently in place.
14441 When ARCHIVES is t, include all archive files hat are really being
14442 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14443 `org-agenda-archives-mode' is t."
14444 (let ((files
14445 (cond
14446 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14447 ((stringp org-agenda-files) (org-read-agenda-file-list))
14448 ((listp org-agenda-files) org-agenda-files)
14449 (t (error "Invalid value of `org-agenda-files'")))))
14450 (setq files (apply 'append
14451 (mapcar (lambda (f)
14452 (if (file-directory-p f)
14453 (directory-files
14454 f t org-agenda-file-regexp)
14455 (list f)))
14456 files)))
14457 (when org-agenda-skip-unavailable-files
14458 (setq files (delq nil
14459 (mapcar (function
14460 (lambda (file)
14461 (and (file-readable-p file) file)))
14462 files))))
14463 (when (or (eq archives t)
14464 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14465 (setq files (org-add-archive-files files)))
14466 files))
14468 (defun org-edit-agenda-file-list ()
14469 "Edit the list of agenda files.
14470 Depending on setup, this either uses customize to edit the variable
14471 `org-agenda-files', or it visits the file that is holding the list. In the
14472 latter case, the buffer is set up in a way that saving it automatically kills
14473 the buffer and restores the previous window configuration."
14474 (interactive)
14475 (if (stringp org-agenda-files)
14476 (let ((cw (current-window-configuration)))
14477 (find-file org-agenda-files)
14478 (org-set-local 'org-window-configuration cw)
14479 (org-add-hook 'after-save-hook
14480 (lambda ()
14481 (set-window-configuration
14482 (prog1 org-window-configuration
14483 (kill-buffer (current-buffer))))
14484 (org-install-agenda-files-menu)
14485 (message "New agenda file list installed"))
14486 nil 'local)
14487 (message "%s" (substitute-command-keys
14488 "Edit list and finish with \\[save-buffer]")))
14489 (customize-variable 'org-agenda-files)))
14491 (defun org-store-new-agenda-file-list (list)
14492 "Set new value for the agenda file list and save it correctly."
14493 (if (stringp org-agenda-files)
14494 (let ((f org-agenda-files) b)
14495 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14496 (with-temp-file f
14497 (insert (mapconcat 'identity list "\n") "\n")))
14498 (let ((org-mode-hook nil) (org-inhibit-startup t)
14499 (org-insert-mode-line-in-empty-file nil))
14500 (setq org-agenda-files list)
14501 (customize-save-variable 'org-agenda-files org-agenda-files))))
14503 (defun org-read-agenda-file-list ()
14504 "Read the list of agenda files from a file."
14505 (when (file-directory-p org-agenda-files)
14506 (error "`org-agenda-files' cannot be a single directory"))
14507 (when (stringp org-agenda-files)
14508 (with-temp-buffer
14509 (insert-file-contents org-agenda-files)
14510 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14513 ;;;###autoload
14514 (defun org-cycle-agenda-files ()
14515 "Cycle through the files in `org-agenda-files'.
14516 If the current buffer visits an agenda file, find the next one in the list.
14517 If the current buffer does not, find the first agenda file."
14518 (interactive)
14519 (let* ((fs (org-agenda-files t))
14520 (files (append fs (list (car fs))))
14521 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14522 file)
14523 (unless files (error "No agenda files"))
14524 (catch 'exit
14525 (while (setq file (pop files))
14526 (if (equal (file-truename file) tcf)
14527 (when (car files)
14528 (find-file (car files))
14529 (throw 'exit t))))
14530 (find-file (car fs)))
14531 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14533 (defun org-agenda-file-to-front (&optional to-end)
14534 "Move/add the current file to the top of the agenda file list.
14535 If the file is not present in the list, it is added to the front. If it is
14536 present, it is moved there. With optional argument TO-END, add/move to the
14537 end of the list."
14538 (interactive "P")
14539 (let ((org-agenda-skip-unavailable-files nil)
14540 (file-alist (mapcar (lambda (x)
14541 (cons (file-truename x) x))
14542 (org-agenda-files t)))
14543 (ctf (file-truename buffer-file-name))
14544 x had)
14545 (setq x (assoc ctf file-alist) had x)
14547 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14548 (if to-end
14549 (setq file-alist (append (delq x file-alist) (list x)))
14550 (setq file-alist (cons x (delq x file-alist))))
14551 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14552 (org-install-agenda-files-menu)
14553 (message "File %s to %s of agenda file list"
14554 (if had "moved" "added") (if to-end "end" "front"))))
14556 (defun org-remove-file (&optional file)
14557 "Remove current file from the list of files in variable `org-agenda-files'.
14558 These are the files which are being checked for agenda entries.
14559 Optional argument FILE means use this file instead of the current."
14560 (interactive)
14561 (let* ((org-agenda-skip-unavailable-files nil)
14562 (file (or file buffer-file-name))
14563 (true-file (file-truename file))
14564 (afile (abbreviate-file-name file))
14565 (files (delq nil (mapcar
14566 (lambda (x)
14567 (if (equal true-file
14568 (file-truename x))
14569 nil x))
14570 (org-agenda-files t)))))
14571 (if (not (= (length files) (length (org-agenda-files t))))
14572 (progn
14573 (org-store-new-agenda-file-list files)
14574 (org-install-agenda-files-menu)
14575 (message "Removed file: %s" afile))
14576 (message "File was not in list: %s (not removed)" afile))))
14578 (defun org-file-menu-entry (file)
14579 (vector file (list 'find-file file) t))
14581 (defun org-check-agenda-file (file)
14582 "Make sure FILE exists. If not, ask user what to do."
14583 (when (not (file-exists-p file))
14584 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14585 (abbreviate-file-name file))
14586 (let ((r (downcase (read-char-exclusive))))
14587 (cond
14588 ((equal r ?r)
14589 (org-remove-file file)
14590 (throw 'nextfile t))
14591 (t (error "Abort"))))))
14593 (defun org-get-agenda-file-buffer (file)
14594 "Get a buffer visiting FILE. If the buffer needs to be created, add
14595 it to the list of buffers which might be released later."
14596 (let ((buf (org-find-base-buffer-visiting file)))
14597 (if buf
14598 buf ; just return it
14599 ;; Make a new buffer and remember it
14600 (setq buf (find-file-noselect file))
14601 (if buf (push buf org-agenda-new-buffers))
14602 buf)))
14604 (defun org-release-buffers (blist)
14605 "Release all buffers in list, asking the user for confirmation when needed.
14606 When a buffer is unmodified, it is just killed. When modified, it is saved
14607 \(if the user agrees) and then killed."
14608 (let (buf file)
14609 (while (setq buf (pop blist))
14610 (setq file (buffer-file-name buf))
14611 (when (and (buffer-modified-p buf)
14612 file
14613 (y-or-n-p (format "Save file %s? " file)))
14614 (with-current-buffer buf (save-buffer)))
14615 (kill-buffer buf))))
14617 (defun org-prepare-agenda-buffers (files)
14618 "Create buffers for all agenda files, protect archived trees and comments."
14619 (interactive)
14620 (let ((pa '(:org-archived t))
14621 (pc '(:org-comment t))
14622 (pall '(:org-archived t :org-comment t))
14623 (inhibit-read-only t)
14624 (rea (concat ":" org-archive-tag ":"))
14625 bmp file re)
14626 (save-excursion
14627 (save-restriction
14628 (while (setq file (pop files))
14629 (catch 'nextfile
14630 (if (bufferp file)
14631 (set-buffer file)
14632 (org-check-agenda-file file)
14633 (set-buffer (org-get-agenda-file-buffer file)))
14634 (widen)
14635 (setq bmp (buffer-modified-p))
14636 (org-refresh-category-properties)
14637 (setq org-todo-keywords-for-agenda
14638 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14639 (setq org-done-keywords-for-agenda
14640 (append org-done-keywords-for-agenda org-done-keywords))
14641 (setq org-todo-keyword-alist-for-agenda
14642 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14643 (setq org-drawers-for-agenda
14644 (append org-drawers-for-agenda org-drawers))
14645 (setq org-tag-alist-for-agenda
14646 (append org-tag-alist-for-agenda org-tag-alist))
14648 (save-excursion
14649 (remove-text-properties (point-min) (point-max) pall)
14650 (when org-agenda-skip-archived-trees
14651 (goto-char (point-min))
14652 (while (re-search-forward rea nil t)
14653 (if (org-on-heading-p t)
14654 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14655 (goto-char (point-min))
14656 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14657 (while (re-search-forward re nil t)
14658 (add-text-properties
14659 (match-beginning 0) (org-end-of-subtree t) pc)))
14660 (set-buffer-modified-p bmp)))))
14661 (setq org-todo-keyword-alist-for-agenda
14662 (org-uniquify org-todo-keyword-alist-for-agenda)
14663 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14665 ;;;; Embedded LaTeX
14667 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14668 "Keymap for the minor `org-cdlatex-mode'.")
14670 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14671 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14672 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14673 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14674 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14676 (defvar org-cdlatex-texmathp-advice-is-done nil
14677 "Flag remembering if we have applied the advice to texmathp already.")
14679 (define-minor-mode org-cdlatex-mode
14680 "Toggle the minor `org-cdlatex-mode'.
14681 This mode supports entering LaTeX environment and math in LaTeX fragments
14682 in Org-mode.
14683 \\{org-cdlatex-mode-map}"
14684 nil " OCDL" nil
14685 (when org-cdlatex-mode (require 'cdlatex))
14686 (unless org-cdlatex-texmathp-advice-is-done
14687 (setq org-cdlatex-texmathp-advice-is-done t)
14688 (defadvice texmathp (around org-math-always-on activate)
14689 "Always return t in org-mode buffers.
14690 This is because we want to insert math symbols without dollars even outside
14691 the LaTeX math segments. If Orgmode thinks that point is actually inside
14692 an embedded LaTeX fragment, let texmathp do its job.
14693 \\[org-cdlatex-mode-map]"
14694 (interactive)
14695 (let (p)
14696 (cond
14697 ((not (org-mode-p)) ad-do-it)
14698 ((eq this-command 'cdlatex-math-symbol)
14699 (setq ad-return-value t
14700 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14702 (let ((p (org-inside-LaTeX-fragment-p)))
14703 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14704 (setq ad-return-value t
14705 texmathp-why '("Org-mode embedded math" . 0))
14706 (if p ad-do-it)))))))))
14708 (defun turn-on-org-cdlatex ()
14709 "Unconditionally turn on `org-cdlatex-mode'."
14710 (org-cdlatex-mode 1))
14712 (defun org-inside-LaTeX-fragment-p ()
14713 "Test if point is inside a LaTeX fragment.
14714 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14715 sequence appearing also before point.
14716 Even though the matchers for math are configurable, this function assumes
14717 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14718 delimiters are skipped when they have been removed by customization.
14719 The return value is nil, or a cons cell with the delimiter and
14720 and the position of this delimiter.
14722 This function does a reasonably good job, but can locally be fooled by
14723 for example currency specifications. For example it will assume being in
14724 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14725 fragments that are properly closed, but during editing, we have to live
14726 with the uncertainty caused by missing closing delimiters. This function
14727 looks only before point, not after."
14728 (catch 'exit
14729 (let ((pos (point))
14730 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14731 (lim (progn
14732 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14733 (point)))
14734 dd-on str (start 0) m re)
14735 (goto-char pos)
14736 (when dodollar
14737 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14738 re (nth 1 (assoc "$" org-latex-regexps)))
14739 (while (string-match re str start)
14740 (cond
14741 ((= (match-end 0) (length str))
14742 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14743 ((= (match-end 0) (- (length str) 5))
14744 (throw 'exit nil))
14745 (t (setq start (match-end 0))))))
14746 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14747 (goto-char pos)
14748 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14749 (and (match-beginning 2) (throw 'exit nil))
14750 ;; count $$
14751 (while (re-search-backward "\\$\\$" lim t)
14752 (setq dd-on (not dd-on)))
14753 (goto-char pos)
14754 (if dd-on (cons "$$" m))))))
14756 (defun org-inside-latex-macro-p ()
14757 "Is point inside a LaTeX macro or its arguments?"
14758 (save-match-data
14759 (org-in-regexp
14760 "\\\\[a-zA-Z]+\\*?\\(\\[[^][\n{}]*\\]\\)?\\({[^{}\n]*}\\)?")))
14762 (defun org-try-cdlatex-tab ()
14763 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14764 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14765 - inside a LaTeX fragment, or
14766 - after the first word in a line, where an abbreviation expansion could
14767 insert a LaTeX environment."
14768 (when org-cdlatex-mode
14769 (cond
14770 ((save-excursion
14771 (skip-chars-backward "a-zA-Z0-9*")
14772 (skip-chars-backward " \t")
14773 (bolp))
14774 (cdlatex-tab) t)
14775 ((org-inside-LaTeX-fragment-p)
14776 (cdlatex-tab) t)
14777 (t nil))))
14779 (defun org-cdlatex-underscore-caret (&optional arg)
14780 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14781 Revert to the normal definition outside of these fragments."
14782 (interactive "P")
14783 (if (org-inside-LaTeX-fragment-p)
14784 (call-interactively 'cdlatex-sub-superscript)
14785 (let (org-cdlatex-mode)
14786 (call-interactively (key-binding (vector last-input-event))))))
14788 (defun org-cdlatex-math-modify (&optional arg)
14789 "Execute `cdlatex-math-modify' in LaTeX fragments.
14790 Revert to the normal definition outside of these fragments."
14791 (interactive "P")
14792 (if (org-inside-LaTeX-fragment-p)
14793 (call-interactively 'cdlatex-math-modify)
14794 (let (org-cdlatex-mode)
14795 (call-interactively (key-binding (vector last-input-event))))))
14797 (defvar org-latex-fragment-image-overlays nil
14798 "List of overlays carrying the images of latex fragments.")
14799 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14801 (defun org-remove-latex-fragment-image-overlays ()
14802 "Remove all overlays with LaTeX fragment images in current buffer."
14803 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14804 (setq org-latex-fragment-image-overlays nil))
14806 (defun org-preview-latex-fragment (&optional subtree)
14807 "Preview the LaTeX fragment at point, or all locally or globally.
14808 If the cursor is in a LaTeX fragment, create the image and overlay
14809 it over the source code. If there is no fragment at point, display
14810 all fragments in the current text, from one headline to the next. With
14811 prefix SUBTREE, display all fragments in the current subtree. With a
14812 double prefix `C-u C-u', or when the cursor is before the first headline,
14813 display all fragments in the buffer.
14814 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14815 (interactive "P")
14816 (org-remove-latex-fragment-image-overlays)
14817 (save-excursion
14818 (save-restriction
14819 (let (beg end at msg)
14820 (cond
14821 ((or (equal subtree '(16))
14822 (not (save-excursion
14823 (re-search-backward (concat "^" outline-regexp) nil t))))
14824 (setq beg (point-min) end (point-max)
14825 msg "Creating images for buffer...%s"))
14826 ((equal subtree '(4))
14827 (org-back-to-heading)
14828 (setq beg (point) end (org-end-of-subtree t)
14829 msg "Creating images for subtree...%s"))
14831 (if (setq at (org-inside-LaTeX-fragment-p))
14832 (goto-char (max (point-min) (- (cdr at) 2)))
14833 (org-back-to-heading))
14834 (setq beg (point) end (progn (outline-next-heading) (point))
14835 msg (if at "Creating image...%s"
14836 "Creating images for entry...%s"))))
14837 (message msg "")
14838 (narrow-to-region beg end)
14839 (goto-char beg)
14840 (org-format-latex
14841 (concat "ltxpng/" (file-name-sans-extension
14842 (file-name-nondirectory
14843 buffer-file-name)))
14844 default-directory 'overlays msg at 'forbuffer)
14845 (message msg "done. Use `C-c C-c' to remove images.")))))
14847 (defvar org-latex-regexps
14848 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14849 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14850 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14851 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14852 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14853 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14854 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14855 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14856 "Regular expressions for matching embedded LaTeX.")
14858 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14859 "Replace LaTeX fragments with links to an image, and produce images.
14860 Some of the options can be changed using the variable
14861 `org-format-latex-options'."
14862 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14863 (let* ((prefixnodir (file-name-nondirectory prefix))
14864 (absprefix (expand-file-name prefix dir))
14865 (todir (file-name-directory absprefix))
14866 (opt org-format-latex-options)
14867 (matchers (plist-get opt :matchers))
14868 (re-list org-latex-regexps)
14869 (org-format-latex-header-extra
14870 (plist-get (org-infile-export-plist) :latex-header-extra))
14871 (cnt 0) txt hash link beg end re e checkdir
14872 executables-checked
14873 m n block linkfile movefile ov)
14874 ;; Check the different regular expressions
14875 (while (setq e (pop re-list))
14876 (setq m (car e) re (nth 1 e) n (nth 2 e)
14877 block (if (nth 3 e) "\n\n" ""))
14878 (when (member m matchers)
14879 (goto-char (point-min))
14880 (while (re-search-forward re nil t)
14881 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14882 (not (get-text-property (match-beginning n)
14883 'org-protected))
14884 (or (not overlays)
14885 (not (eq (get-char-property (match-beginning n)
14886 'org-overlay-type)
14887 'org-latex-overlay))))
14888 (setq txt (match-string n)
14889 beg (match-beginning n) end (match-end n)
14890 cnt (1+ cnt))
14891 (let (print-length print-level) ; make sure full list is printed
14892 (setq hash (sha1 (prin1-to-string
14893 (list org-format-latex-header
14894 org-format-latex-header-extra
14895 org-export-latex-packages-alist
14896 org-format-latex-options
14897 forbuffer txt)))
14898 linkfile (format "%s_%s.png" prefix hash)
14899 movefile (format "%s_%s.png" absprefix hash)))
14900 (setq link (concat block "[[file:" linkfile "]]" block))
14901 (if msg (message msg cnt))
14902 (goto-char beg)
14903 (unless checkdir ; make sure the directory exists
14904 (setq checkdir t)
14905 (or (file-directory-p todir) (make-directory todir)))
14907 (unless executables-checked
14908 (org-check-external-command
14909 "latex" "needed to convert LaTeX fragments to images")
14910 (org-check-external-command
14911 "dvipng" "needed to convert LaTeX fragments to images")
14912 (setq executables-checked t))
14914 (unless (file-exists-p movefile)
14915 (org-create-formula-image
14916 txt movefile opt forbuffer))
14917 (if overlays
14918 (progn
14919 (mapc (lambda (o)
14920 (if (eq (org-overlay-get o 'org-overlay-type)
14921 'org-latex-overlay)
14922 (org-delete-overlay o)))
14923 (org-overlays-in beg end))
14924 (setq ov (org-make-overlay beg end))
14925 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14926 (if (featurep 'xemacs)
14927 (progn
14928 (org-overlay-put ov 'invisible t)
14929 (org-overlay-put
14930 ov 'end-glyph
14931 (make-glyph (vector 'png :file movefile))))
14932 (org-overlay-put
14933 ov 'display
14934 (list 'image :type 'png :file movefile :ascent 'center)))
14935 (push ov org-latex-fragment-image-overlays)
14936 (goto-char end))
14937 (delete-region beg end)
14938 (insert link))))))))
14940 ;; This function borrows from Ganesh Swami's latex2png.el
14941 (defun org-create-formula-image (string tofile options buffer)
14942 "This calls dvipng."
14943 (require 'org-latex)
14944 (let* ((tmpdir (if (featurep 'xemacs)
14945 (temp-directory)
14946 temporary-file-directory))
14947 (texfilebase (make-temp-name
14948 (expand-file-name "orgtex" tmpdir)))
14949 (texfile (concat texfilebase ".tex"))
14950 (dvifile (concat texfilebase ".dvi"))
14951 (pngfile (concat texfilebase ".png"))
14952 (fnh (if (featurep 'xemacs)
14953 (font-height (get-face-font 'default))
14954 (face-attribute 'default :height nil)))
14955 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14956 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14957 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14958 "Black"))
14959 (bg (or (plist-get options (if buffer :background :html-background))
14960 "Transparent")))
14961 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14962 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14963 (with-temp-file texfile
14964 (insert org-format-latex-header
14965 (if org-export-latex-packages-alist
14966 (concat "\n"
14967 (mapconcat (lambda(p)
14968 (if (equal "" (car p))
14969 (format "\\usepackage{%s}" (cadr p))
14970 (format "\\usepackage[%s]{%s}"
14971 (car p) (cadr p))))
14972 org-export-latex-packages-alist "\n"))
14974 (if org-format-latex-header-extra
14975 (concat "\n" org-format-latex-header-extra)
14977 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14978 (let ((dir default-directory))
14979 (condition-case nil
14980 (progn
14981 (cd tmpdir)
14982 (call-process "latex" nil nil nil texfile))
14983 (error nil))
14984 (cd dir))
14985 (if (not (file-exists-p dvifile))
14986 (progn (message "Failed to create dvi file from %s" texfile) nil)
14987 (condition-case nil
14988 (call-process "dvipng" nil nil nil
14989 "-fg" fg "-bg" bg
14990 "-D" dpi
14991 ;;"-x" scale "-y" scale
14992 "-T" "tight"
14993 "-o" pngfile
14994 dvifile)
14995 (error nil))
14996 (if (not (file-exists-p pngfile))
14997 (progn (message "Failed to create png file from %s" texfile) nil)
14998 ;; Use the requested file name and clean up
14999 (copy-file pngfile tofile 'replace)
15000 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15001 (delete-file (concat texfilebase e)))
15002 pngfile))))
15004 (defun org-dvipng-color (attr)
15005 "Return an rgb color specification for dvipng."
15006 (apply 'format "rgb %s %s %s"
15007 (mapcar 'org-normalize-color
15008 (color-values (face-attribute 'default attr nil)))))
15010 (defun org-normalize-color (value)
15011 "Return string to be used as color value for an RGB component."
15012 (format "%g" (/ value 65535.0)))
15014 ;;;; Key bindings
15016 ;; Make `C-c C-x' a prefix key
15017 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
15019 ;; TAB key with modifiers
15020 (org-defkey org-mode-map "\C-i" 'org-cycle)
15021 (org-defkey org-mode-map [(tab)] 'org-cycle)
15022 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
15023 (org-defkey org-mode-map [(meta tab)] 'org-complete)
15024 (org-defkey org-mode-map "\M-\t" 'org-complete)
15025 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
15026 ;; The following line is necessary under Suse GNU/Linux
15027 (unless (featurep 'xemacs)
15028 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
15029 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
15030 (define-key org-mode-map [backtab] 'org-shifttab)
15032 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
15033 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15034 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
15036 ;; Cursor keys with modifiers
15037 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
15038 (org-defkey org-mode-map [(meta right)] 'org-metaright)
15039 (org-defkey org-mode-map [(meta up)] 'org-metaup)
15040 (org-defkey org-mode-map [(meta down)] 'org-metadown)
15042 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15043 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
15044 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
15045 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
15047 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
15048 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
15049 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
15050 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
15052 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
15053 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
15055 ;;; Extra keys for tty access.
15056 ;; We only set them when really needed because otherwise the
15057 ;; menus don't show the simple keys
15059 (when (or org-use-extra-keys
15060 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
15061 (not window-system))
15062 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
15063 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
15064 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
15065 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
15066 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
15067 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
15068 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
15069 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
15070 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
15071 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
15072 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
15073 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
15074 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
15075 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
15076 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
15077 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
15078 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
15079 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
15080 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
15081 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
15082 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
15083 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
15084 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
15085 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
15086 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
15087 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
15088 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
15089 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
15091 ;; All the other keys
15093 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15094 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
15095 (if (boundp 'narrow-map)
15096 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
15097 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
15098 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
15099 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
15100 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
15101 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
15102 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
15103 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
15104 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
15105 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
15106 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
15107 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
15108 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
15109 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
15110 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
15111 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
15112 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15113 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
15114 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
15115 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
15116 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
15117 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
15118 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
15119 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
15120 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
15121 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
15122 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
15123 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
15124 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
15125 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
15126 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
15127 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
15128 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15129 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15130 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15131 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15132 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
15133 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
15134 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15135 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
15136 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
15137 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
15138 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
15139 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15140 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
15141 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
15142 (org-defkey org-mode-map "\C-c^" 'org-sort)
15143 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15144 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
15145 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
15146 (org-defkey org-mode-map "\C-m" 'org-return)
15147 (org-defkey org-mode-map "\C-j" 'org-return-indent)
15148 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
15149 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
15150 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
15151 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
15152 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
15153 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
15154 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15155 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15156 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
15157 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
15158 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
15159 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
15160 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
15161 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15162 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
15163 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
15164 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
15165 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
15166 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
15167 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
15169 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
15170 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15171 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15172 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15174 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
15175 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15176 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15177 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
15178 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15179 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15180 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15181 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15182 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15183 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15184 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
15185 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
15186 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
15187 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
15188 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
15190 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
15191 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
15192 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
15193 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
15195 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
15197 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
15199 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
15200 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
15202 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
15205 (when (featurep 'xemacs)
15206 (org-defkey org-mode-map 'button3 'popup-mode-menu))
15209 (defconst org-speed-commands-default
15211 ("Outline Navigation")
15212 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
15213 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
15214 ("f" . (org-speed-move-safe 'org-forward-same-level))
15215 ("b" . (org-speed-move-safe 'org-backward-same-level))
15216 ("u" . (org-speed-move-safe 'outline-up-heading))
15217 ("j" . org-goto)
15218 ("g" . (org-refile t))
15219 ("Outline Visibility")
15220 ("c" . org-cycle)
15221 ("C" . org-shifttab)
15222 (" " . org-display-outline-path)
15223 ("Outline Structure Editing")
15224 ("U" . org-shiftmetaup)
15225 ("D" . org-shiftmetadown)
15226 ("r" . org-metaright)
15227 ("l" . org-metaleft)
15228 ("R" . org-shiftmetaright)
15229 ("L" . org-shiftmetaleft)
15230 ("i" . (progn (forward-char 1) (call-interactively
15231 'org-insert-heading-respect-content)))
15232 ("^" . org-sort)
15233 ("w" . org-refile)
15234 ("a" . org-archive-subtree-default-with-confirmation)
15235 ("." . outline-mark-subtree)
15236 ("Clock Commands")
15237 ("I" . org-clock-in)
15238 ("O" . org-clock-out)
15239 ("Meta Data Editing")
15240 ("t" . org-todo)
15241 ("0" . (org-priority ?\ ))
15242 ("1" . (org-priority ?A))
15243 ("2" . (org-priority ?B))
15244 ("3" . (org-priority ?C))
15245 (";" . org-set-tags-command)
15246 ("e" . org-set-effort)
15247 ("Agenda Views etc")
15248 ("v" . org-agenda)
15249 ("/" . org-sparse-tree)
15250 ("Misc")
15251 ("o" . org-open-at-point)
15252 ("?" . org-speed-command-help)
15254 "The default speed commands.")
15256 (defun org-print-speed-command (e)
15257 (if (> (length (car e)) 1)
15258 (progn
15259 (princ "\n")
15260 (princ (car e))
15261 (princ "\n")
15262 (princ (make-string (length (car e)) ?-))
15263 (princ "\n"))
15264 (princ (car e))
15265 (princ " ")
15266 (if (symbolp (cdr e))
15267 (princ (symbol-name (cdr e)))
15268 (prin1 (cdr e)))
15269 (princ "\n")))
15271 (defun org-speed-command-help ()
15272 "Show the available speed commands."
15273 (interactive)
15274 (if (not org-use-speed-commands)
15275 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
15276 (with-output-to-temp-buffer "*Help*"
15277 (princ "User-defined Speed commands\n===========================\n")
15278 (mapc 'org-print-speed-command org-speed-commands-user)
15279 (princ "\n")
15280 (princ "Built-in Speed commands\n=======================\n")
15281 (mapc 'org-print-speed-command org-speed-commands-default))
15282 (with-current-buffer "*Help*"
15283 (setq truncate-lines t))))
15285 (defun org-speed-move-safe (cmd)
15286 "Execute CMD, but make sure that the cursor always ends up in a headline.
15287 If not, return to the original position and throw an error."
15288 (interactive)
15289 (let ((pos (point)))
15290 (call-interactively cmd)
15291 (unless (and (bolp) (org-on-heading-p))
15292 (goto-char pos)
15293 (error "Boundary reached while executing %s" cmd))))
15295 (defvar org-self-insert-command-undo-counter 0)
15297 (defvar org-table-auto-blank-field) ; defined in org-table.el
15298 (defvar org-speed-command nil)
15299 (defun org-self-insert-command (N)
15300 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15301 If the cursor is in a table looking at whitespace, the whitespace is
15302 overwritten, and the table is not marked as requiring realignment."
15303 (interactive "p")
15304 (cond
15305 ((and org-use-speed-commands
15306 (or (and (bolp) (looking-at outline-regexp))
15307 (and (functionp org-use-speed-commands)
15308 (funcall org-use-speed-commands)))
15309 (setq
15310 org-speed-command
15311 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15312 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15313 (cond
15314 ((commandp org-speed-command)
15315 (setq this-command org-speed-command)
15316 (call-interactively org-speed-command))
15317 ((functionp org-speed-command)
15318 (funcall org-speed-command))
15319 ((and org-speed-command (listp org-speed-command))
15320 (eval org-speed-command))
15321 (t (let (org-use-speed-commands)
15322 (call-interactively 'org-self-insert-command)))))
15323 ((and
15324 (org-table-p)
15325 (progn
15326 ;; check if we blank the field, and if that triggers align
15327 (and (featurep 'org-table) org-table-auto-blank-field
15328 (member last-command
15329 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15330 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15331 ;; got extra space, this field does not determine column width
15332 (let (org-table-may-need-update) (org-table-blank-field))
15333 ;; no extra space, this field may determine column width
15334 (org-table-blank-field)))
15336 (eq N 1)
15337 (looking-at "[^|\n]* |"))
15338 (let (org-table-may-need-update)
15339 (goto-char (1- (match-end 0)))
15340 (delete-backward-char 1)
15341 (goto-char (match-beginning 0))
15342 (self-insert-command N)))
15344 (setq org-table-may-need-update t)
15345 (self-insert-command N)
15346 (org-fix-tags-on-the-fly)
15347 (if org-self-insert-cluster-for-undo
15348 (if (not (eq last-command 'org-self-insert-command))
15349 (setq org-self-insert-command-undo-counter 1)
15350 (if (>= org-self-insert-command-undo-counter 20)
15351 (setq org-self-insert-command-undo-counter 1)
15352 (and (> org-self-insert-command-undo-counter 0)
15353 buffer-undo-list
15354 (not (cadr buffer-undo-list)) ; remove nil entry
15355 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15356 (setq org-self-insert-command-undo-counter
15357 (1+ org-self-insert-command-undo-counter))))))))
15359 (defun org-fix-tags-on-the-fly ()
15360 (when (and (equal (char-after (point-at-bol)) ?*)
15361 (org-on-heading-p))
15362 (org-align-tags-here org-tags-column)))
15364 (defun org-delete-backward-char (N)
15365 "Like `delete-backward-char', insert whitespace at field end in tables.
15366 When deleting backwards, in tables this function will insert whitespace in
15367 front of the next \"|\" separator, to keep the table aligned. The table will
15368 still be marked for re-alignment if the field did fill the entire column,
15369 because, in this case the deletion might narrow the column."
15370 (interactive "p")
15371 (if (and (org-table-p)
15372 (eq N 1)
15373 (string-match "|" (buffer-substring (point-at-bol) (point)))
15374 (looking-at ".*?|"))
15375 (let ((pos (point))
15376 (noalign (looking-at "[^|\n\r]* |"))
15377 (c org-table-may-need-update))
15378 (backward-delete-char N)
15379 (skip-chars-forward "^|")
15380 (insert " ")
15381 (goto-char (1- pos))
15382 ;; noalign: if there were two spaces at the end, this field
15383 ;; does not determine the width of the column.
15384 (if noalign (setq org-table-may-need-update c)))
15385 (backward-delete-char N)
15386 (org-fix-tags-on-the-fly)))
15388 (defun org-delete-char (N)
15389 "Like `delete-char', but insert whitespace at field end in tables.
15390 When deleting characters, in tables this function will insert whitespace in
15391 front of the next \"|\" separator, to keep the table aligned. The table will
15392 still be marked for re-alignment if the field did fill the entire column,
15393 because, in this case the deletion might narrow the column."
15394 (interactive "p")
15395 (if (and (org-table-p)
15396 (not (bolp))
15397 (not (= (char-after) ?|))
15398 (eq N 1))
15399 (if (looking-at ".*?|")
15400 (let ((pos (point))
15401 (noalign (looking-at "[^|\n\r]* |"))
15402 (c org-table-may-need-update))
15403 (replace-match (concat
15404 (substring (match-string 0) 1 -1)
15405 " |"))
15406 (goto-char pos)
15407 ;; noalign: if there were two spaces at the end, this field
15408 ;; does not determine the width of the column.
15409 (if noalign (setq org-table-may-need-update c)))
15410 (delete-char N))
15411 (delete-char N)
15412 (org-fix-tags-on-the-fly)))
15414 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15415 (put 'org-self-insert-command 'delete-selection t)
15416 (put 'orgtbl-self-insert-command 'delete-selection t)
15417 (put 'org-delete-char 'delete-selection 'supersede)
15418 (put 'org-delete-backward-char 'delete-selection 'supersede)
15419 (put 'org-yank 'delete-selection 'yank)
15421 ;; Make `flyspell-mode' delay after some commands
15422 (put 'org-self-insert-command 'flyspell-delayed t)
15423 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15424 (put 'org-delete-char 'flyspell-delayed t)
15425 (put 'org-delete-backward-char 'flyspell-delayed t)
15427 ;; Make pabbrev-mode expand after org-mode commands
15428 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15429 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15431 ;; How to do this: Measure non-white length of current string
15432 ;; If equal to column width, we should realign.
15434 (defun org-remap (map &rest commands)
15435 "In MAP, remap the functions given in COMMANDS.
15436 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15437 (let (new old)
15438 (while commands
15439 (setq old (pop commands) new (pop commands))
15440 (if (fboundp 'command-remapping)
15441 (org-defkey map (vector 'remap old) new)
15442 (substitute-key-definition old new map global-map)))))
15444 (when (eq org-enable-table-editor 'optimized)
15445 ;; If the user wants maximum table support, we need to hijack
15446 ;; some standard editing functions
15447 (org-remap org-mode-map
15448 'self-insert-command 'org-self-insert-command
15449 'delete-char 'org-delete-char
15450 'delete-backward-char 'org-delete-backward-char)
15451 (org-defkey org-mode-map "|" 'org-force-self-insert))
15453 (defvar org-ctrl-c-ctrl-c-hook nil
15454 "Hook for functions attaching themselves to `C-c C-c'.
15455 This can be used to add additional functionality to the C-c C-c key which
15456 executes context-dependent commands.
15457 Each function will be called with no arguments. The function must check
15458 if the context is appropriate for it to act. If yes, it should do its
15459 thing and then return a non-nil value. If the context is wrong,
15460 just do nothing and return nil.")
15462 (defvar org-tab-first-hook nil
15463 "Hook for functions to attach themselves to TAB.
15464 See `org-ctrl-c-ctrl-c-hook' for more information.
15465 This hook runs as the first action when TAB is pressed, even before
15466 `org-cycle' messes around with the `outline-regexp' to cater for
15467 inline tasks and plain list item folding.
15468 If any function in this hook returns t, not other actions like table
15469 field motion visibility cycling will be done.")
15471 (defvar org-tab-after-check-for-table-hook nil
15472 "Hook for functions to attach themselves to TAB.
15473 See `org-ctrl-c-ctrl-c-hook' for more information.
15474 This hook runs after it has been established that the cursor is not in a
15475 table, but before checking if the cursor is in a headline or if global cycling
15476 should be done.
15477 If any function in this hook returns t, not other actions like visibility
15478 cycling will be done.")
15480 (defvar org-tab-after-check-for-cycling-hook nil
15481 "Hook for functions to attach themselves to TAB.
15482 See `org-ctrl-c-ctrl-c-hook' for more information.
15483 This hook runs after it has been established that not table field motion and
15484 not visibility should be done because of current context. This is probably
15485 the place where a package like yasnippets can hook in.")
15487 (defvar org-tab-before-tab-emulation-hook nil
15488 "Hook for functions to attach themselves to TAB.
15489 See `org-ctrl-c-ctrl-c-hook' for more information.
15490 This hook runs after every other options for TAB have been exhausted, but
15491 before indentation and \t insertion takes place.")
15493 (defvar org-metaleft-hook nil
15494 "Hook for functions attaching themselves to `M-left'.
15495 See `org-ctrl-c-ctrl-c-hook' for more information.")
15496 (defvar org-metaright-hook nil
15497 "Hook for functions attaching themselves to `M-right'.
15498 See `org-ctrl-c-ctrl-c-hook' for more information.")
15499 (defvar org-metaup-hook nil
15500 "Hook for functions attaching themselves to `M-up'.
15501 See `org-ctrl-c-ctrl-c-hook' for more information.")
15502 (defvar org-metadown-hook nil
15503 "Hook for functions attaching themselves to `M-down'.
15504 See `org-ctrl-c-ctrl-c-hook' for more information.")
15505 (defvar org-shiftmetaleft-hook nil
15506 "Hook for functions attaching themselves to `M-S-left'.
15507 See `org-ctrl-c-ctrl-c-hook' for more information.")
15508 (defvar org-shiftmetaright-hook nil
15509 "Hook for functions attaching themselves to `M-S-right'.
15510 See `org-ctrl-c-ctrl-c-hook' for more information.")
15511 (defvar org-shiftmetaup-hook nil
15512 "Hook for functions attaching themselves to `M-S-up'.
15513 See `org-ctrl-c-ctrl-c-hook' for more information.")
15514 (defvar org-shiftmetadown-hook nil
15515 "Hook for functions attaching themselves to `M-S-down'.
15516 See `org-ctrl-c-ctrl-c-hook' for more information.")
15517 (defvar org-metareturn-hook nil
15518 "Hook for functions attaching themselves to `M-RET'.
15519 See `org-ctrl-c-ctrl-c-hook' for more information.")
15521 (defun org-modifier-cursor-error ()
15522 "Throw an error, a modified cursor command was applied in wrong context."
15523 (error "This command is active in special context like tables, headlines or items"))
15525 (defun org-shiftselect-error ()
15526 "Throw an error because Shift-Cursor command was applied in wrong context."
15527 (if (and (boundp 'shift-select-mode) shift-select-mode)
15528 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15529 (error "This command works only in special context like headlines or timestamps")))
15531 (defun org-call-for-shift-select (cmd)
15532 (let ((this-command-keys-shift-translated t))
15533 (call-interactively cmd)))
15535 (defun org-shifttab (&optional arg)
15536 "Global visibility cycling or move to previous table field.
15537 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15538 on context.
15539 See the individual commands for more information."
15540 (interactive "P")
15541 (cond
15542 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15543 ((integerp arg)
15544 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15545 (message "Content view to level: %d" arg)
15546 (org-content (prefix-numeric-value arg2))
15547 (setq org-cycle-global-status 'overview)))
15548 (t (call-interactively 'org-global-cycle))))
15550 (defun org-shiftmetaleft ()
15551 "Promote subtree or delete table column.
15552 Calls `org-promote-subtree', `org-outdent-item',
15553 or `org-table-delete-column', depending on context.
15554 See the individual commands for more information."
15555 (interactive)
15556 (cond
15557 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15558 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15559 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15560 ((org-at-item-p) (call-interactively 'org-outdent-item))
15561 (t (org-modifier-cursor-error))))
15563 (defun org-shiftmetaright ()
15564 "Demote subtree or insert table column.
15565 Calls `org-demote-subtree', `org-indent-item',
15566 or `org-table-insert-column', depending on context.
15567 See the individual commands for more information."
15568 (interactive)
15569 (cond
15570 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15571 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15572 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15573 ((org-at-item-p) (call-interactively 'org-indent-item))
15574 (t (org-modifier-cursor-error))))
15576 (defun org-shiftmetaup (&optional arg)
15577 "Move subtree up or kill table row.
15578 Calls `org-move-subtree-up' or `org-table-kill-row' or
15579 `org-move-item-up' depending on context. See the individual commands
15580 for more information."
15581 (interactive "P")
15582 (cond
15583 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15584 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15585 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15586 ((org-at-item-p) (call-interactively 'org-move-item-up))
15587 (t (org-modifier-cursor-error))))
15589 (defun org-shiftmetadown (&optional arg)
15590 "Move subtree down or insert table row.
15591 Calls `org-move-subtree-down' or `org-table-insert-row' or
15592 `org-move-item-down', depending on context. See the individual
15593 commands for more information."
15594 (interactive "P")
15595 (cond
15596 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15597 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15598 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15599 ((org-at-item-p) (call-interactively 'org-move-item-down))
15600 (t (org-modifier-cursor-error))))
15602 (defun org-metaleft (&optional arg)
15603 "Promote heading or move table column to left.
15604 Calls `org-do-promote' or `org-table-move-column', depending on context.
15605 With no specific context, calls the Emacs default `backward-word'.
15606 See the individual commands for more information."
15607 (interactive "P")
15608 (cond
15609 ((run-hook-with-args-until-success 'org-metaleft-hook))
15610 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15611 ((or (org-on-heading-p)
15612 (and (org-region-active-p)
15613 (save-excursion
15614 (goto-char (region-beginning))
15615 (org-on-heading-p))))
15616 (call-interactively 'org-do-promote))
15617 ((or (org-at-item-p)
15618 (and (org-region-active-p)
15619 (save-excursion
15620 (goto-char (region-beginning))
15621 (org-at-item-p))))
15622 (call-interactively 'org-outdent-item))
15623 (t (call-interactively 'backward-word))))
15625 (defun org-metaright (&optional arg)
15626 "Demote subtree or move table column to right.
15627 Calls `org-do-demote' or `org-table-move-column', depending on context.
15628 With no specific context, calls the Emacs default `forward-word'.
15629 See the individual commands for more information."
15630 (interactive "P")
15631 (cond
15632 ((run-hook-with-args-until-success 'org-metaright-hook))
15633 ((org-at-table-p) (call-interactively 'org-table-move-column))
15634 ((or (org-on-heading-p)
15635 (and (org-region-active-p)
15636 (save-excursion
15637 (goto-char (region-beginning))
15638 (org-on-heading-p))))
15639 (call-interactively 'org-do-demote))
15640 ((or (org-at-item-p)
15641 (and (org-region-active-p)
15642 (save-excursion
15643 (goto-char (region-beginning))
15644 (org-at-item-p))))
15645 (call-interactively 'org-indent-item))
15646 (t (call-interactively 'forward-word))))
15648 (defun org-metaup (&optional arg)
15649 "Move subtree up or move table row up.
15650 Calls `org-move-subtree-up' or `org-table-move-row' or
15651 `org-move-item-up', depending on context. See the individual commands
15652 for more information."
15653 (interactive "P")
15654 (cond
15655 ((run-hook-with-args-until-success 'org-metaup-hook))
15656 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15657 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15658 ((org-at-item-p) (call-interactively 'org-move-item-up))
15659 (t (transpose-lines 1) (beginning-of-line -1))))
15661 (defun org-metadown (&optional arg)
15662 "Move subtree down or move table row down.
15663 Calls `org-move-subtree-down' or `org-table-move-row' or
15664 `org-move-item-down', depending on context. See the individual
15665 commands for more information."
15666 (interactive "P")
15667 (cond
15668 ((run-hook-with-args-until-success 'org-metadown-hook))
15669 ((org-at-table-p) (call-interactively 'org-table-move-row))
15670 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15671 ((org-at-item-p) (call-interactively 'org-move-item-down))
15672 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15674 (defun org-shiftup (&optional arg)
15675 "Increase item in timestamp or increase priority of current headline.
15676 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15677 depending on context. See the individual commands for more information."
15678 (interactive "P")
15679 (cond
15680 ((and org-support-shift-select (org-region-active-p))
15681 (org-call-for-shift-select 'previous-line))
15682 ((org-at-timestamp-p t)
15683 (call-interactively (if org-edit-timestamp-down-means-later
15684 'org-timestamp-down 'org-timestamp-up)))
15685 ((and (not (eq org-support-shift-select 'always))
15686 org-enable-priority-commands
15687 (org-on-heading-p))
15688 (call-interactively 'org-priority-up))
15689 ((and (not org-support-shift-select) (org-at-item-p))
15690 (call-interactively 'org-previous-item))
15691 ((org-clocktable-try-shift 'up arg))
15692 (org-support-shift-select
15693 (org-call-for-shift-select 'previous-line))
15694 (t (org-shiftselect-error))))
15696 (defun org-shiftdown (&optional arg)
15697 "Decrease item in timestamp or decrease priority of current headline.
15698 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15699 depending on context. See the individual commands for more information."
15700 (interactive "P")
15701 (cond
15702 ((and org-support-shift-select (org-region-active-p))
15703 (org-call-for-shift-select 'next-line))
15704 ((org-at-timestamp-p t)
15705 (call-interactively (if org-edit-timestamp-down-means-later
15706 'org-timestamp-up 'org-timestamp-down)))
15707 ((and (not (eq org-support-shift-select 'always))
15708 org-enable-priority-commands
15709 (org-on-heading-p))
15710 (call-interactively 'org-priority-down))
15711 ((and (not org-support-shift-select) (org-at-item-p))
15712 (call-interactively 'org-next-item))
15713 ((org-clocktable-try-shift 'down arg))
15714 (org-support-shift-select
15715 (org-call-for-shift-select 'next-line))
15716 (t (org-shiftselect-error))))
15718 (defun org-shiftright (&optional arg)
15719 "Cycle the thing at point or in the current line, depending on context.
15720 Depending on context, this does one of the following:
15722 - switch a timestamp at point one day into the future
15723 - on a headline, switch to the next TODO keyword.
15724 - on an item, switch entire list to the next bullet type
15725 - on a property line, switch to the next allowed value
15726 - on a clocktable definition line, move time block into the future"
15727 (interactive "P")
15728 (cond
15729 ((and org-support-shift-select (org-region-active-p))
15730 (org-call-for-shift-select 'forward-char))
15731 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15732 ((and (not (eq org-support-shift-select 'always))
15733 (org-on-heading-p))
15734 (let ((org-inhibit-logging
15735 (not org-treat-S-cursor-todo-selection-as-state-change))
15736 (org-inhibit-blocking
15737 (not org-treat-S-cursor-todo-selection-as-state-change)))
15738 (org-call-with-arg 'org-todo 'right)))
15739 ((or (and org-support-shift-select
15740 (not (eq org-support-shift-select 'always))
15741 (org-at-item-bullet-p))
15742 (and (not org-support-shift-select) (org-at-item-p)))
15743 (org-call-with-arg 'org-cycle-list-bullet nil))
15744 ((and (not (eq org-support-shift-select 'always))
15745 (org-at-property-p))
15746 (call-interactively 'org-property-next-allowed-value))
15747 ((org-clocktable-try-shift 'right arg))
15748 (org-support-shift-select
15749 (org-call-for-shift-select 'forward-char))
15750 (t (org-shiftselect-error))))
15752 (defun org-shiftleft (&optional arg)
15753 "Cycle the thing at point or in the current line, depending on context.
15754 Depending on context, this does one of the following:
15756 - switch a timestamp at point one day into the past
15757 - on a headline, switch to the previous TODO keyword.
15758 - on an item, switch entire list to the previous bullet type
15759 - on a property line, switch to the previous allowed value
15760 - on a clocktable definition line, move time block into the past"
15761 (interactive "P")
15762 (cond
15763 ((and org-support-shift-select (org-region-active-p))
15764 (org-call-for-shift-select 'backward-char))
15765 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15766 ((and (not (eq org-support-shift-select 'always))
15767 (org-on-heading-p))
15768 (let ((org-inhibit-logging
15769 (not org-treat-S-cursor-todo-selection-as-state-change))
15770 (org-inhibit-blocking
15771 (not org-treat-S-cursor-todo-selection-as-state-change)))
15772 (org-call-with-arg 'org-todo 'left)))
15773 ((or (and org-support-shift-select
15774 (not (eq org-support-shift-select 'always))
15775 (org-at-item-bullet-p))
15776 (and (not org-support-shift-select) (org-at-item-p)))
15777 (org-call-with-arg 'org-cycle-list-bullet 'previous))
15778 ((and (not (eq org-support-shift-select 'always))
15779 (org-at-property-p))
15780 (call-interactively 'org-property-previous-allowed-value))
15781 ((org-clocktable-try-shift 'left arg))
15782 (org-support-shift-select
15783 (org-call-for-shift-select 'backward-char))
15784 (t (org-shiftselect-error))))
15786 (defun org-shiftcontrolright ()
15787 "Switch to next TODO set."
15788 (interactive)
15789 (cond
15790 ((and org-support-shift-select (org-region-active-p))
15791 (org-call-for-shift-select 'forward-word))
15792 ((and (not (eq org-support-shift-select 'always))
15793 (org-on-heading-p))
15794 (org-call-with-arg 'org-todo 'nextset))
15795 (org-support-shift-select
15796 (org-call-for-shift-select 'forward-word))
15797 (t (org-shiftselect-error))))
15799 (defun org-shiftcontrolleft ()
15800 "Switch to previous TODO set."
15801 (interactive)
15802 (cond
15803 ((and org-support-shift-select (org-region-active-p))
15804 (org-call-for-shift-select 'backward-word))
15805 ((and (not (eq org-support-shift-select 'always))
15806 (org-on-heading-p))
15807 (org-call-with-arg 'org-todo 'previousset))
15808 (org-support-shift-select
15809 (org-call-for-shift-select 'backward-word))
15810 (t (org-shiftselect-error))))
15812 (defun org-ctrl-c-ret ()
15813 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15814 (interactive)
15815 (cond
15816 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15817 (t (call-interactively 'org-insert-heading))))
15819 (defun org-copy-special ()
15820 "Copy region in table or copy current subtree.
15821 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15822 See the individual commands for more information."
15823 (interactive)
15824 (call-interactively
15825 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15827 (defun org-cut-special ()
15828 "Cut region in table or cut current subtree.
15829 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15830 See the individual commands for more information."
15831 (interactive)
15832 (call-interactively
15833 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15835 (defun org-paste-special (arg)
15836 "Paste rectangular region into table, or past subtree relative to level.
15837 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15838 See the individual commands for more information."
15839 (interactive "P")
15840 (if (org-at-table-p)
15841 (org-table-paste-rectangle)
15842 (org-paste-subtree arg)))
15844 (defun org-edit-special ()
15845 "Call a special editor for the stuff at point.
15846 When at a table, call the formula editor with `org-table-edit-formulas'.
15847 When at the first line of an src example, call `org-edit-src-code'.
15848 When in an #+include line, visit the include file. Otherwise call
15849 `ffap' to visit the file at point."
15850 (interactive)
15851 (cond
15852 ((org-at-table-p)
15853 (call-interactively 'org-table-edit-formulas))
15854 ((save-excursion
15855 (beginning-of-line 1)
15856 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
15857 (find-file (org-trim (match-string 1))))
15858 ((org-edit-src-code))
15859 ((org-edit-fixed-width-region))
15860 (t (call-interactively 'ffap))))
15863 (defun org-ctrl-c-ctrl-c (&optional arg)
15864 "Set tags in headline, or update according to changed information at point.
15866 This command does many different things, depending on context:
15868 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15869 this is what we do.
15871 - If the cursor is on a statistics cookie, update it.
15873 - If the cursor is in a headline, prompt for tags and insert them
15874 into the current line, aligned to `org-tags-column'. When called
15875 with prefix arg, realign all tags in the current buffer.
15877 - If the cursor is in one of the special #+KEYWORD lines, this
15878 triggers scanning the buffer for these lines and updating the
15879 information.
15881 - If the cursor is inside a table, realign the table. This command
15882 works even if the automatic table editor has been turned off.
15884 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15885 the entire table.
15887 - If the cursor is at a footnote reference or definition, jump to
15888 the corresponding definition or references, respectively.
15890 - If the cursor is a the beginning of a dynamic block, update it.
15892 - If the cursor is inside a table created by the table.el package,
15893 activate that table.
15895 - If the current buffer is a remember buffer, close note and file
15896 it. A prefix argument of 1 files to the default location
15897 without further interaction. A prefix argument of 2 files to
15898 the currently clocking task.
15900 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15901 links in this buffer.
15903 - If the cursor is on a numbered item in a plain list, renumber the
15904 ordered list.
15906 - If the cursor is on a checkbox, toggle it."
15907 (interactive "P")
15908 (let ((org-enable-table-editor t))
15909 (cond
15910 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15911 org-occur-highlights
15912 org-latex-fragment-image-overlays)
15913 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15914 (org-remove-occur-highlights)
15915 (org-remove-latex-fragment-image-overlays)
15916 (message "Temporary highlights/overlays removed from current buffer"))
15917 ((and (local-variable-p 'org-finish-function (current-buffer))
15918 (fboundp org-finish-function))
15919 (funcall org-finish-function))
15920 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15921 ((org-at-property-p)
15922 (call-interactively 'org-property-action))
15923 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15924 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15925 (or (org-on-heading-p) (org-at-item-p)))
15926 (call-interactively 'org-update-statistics-cookies))
15927 ((org-on-heading-p) (call-interactively 'org-set-tags))
15928 ((org-at-table.el-p)
15929 (require 'table)
15930 (beginning-of-line 1)
15931 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15932 (call-interactively 'table-recognize-table))
15933 ((org-at-table-p)
15934 (org-table-maybe-eval-formula)
15935 (if arg
15936 (call-interactively 'org-table-recalculate)
15937 (org-table-maybe-recalculate-line))
15938 (call-interactively 'org-table-align))
15939 ((or (org-footnote-at-reference-p)
15940 (org-footnote-at-definition-p))
15941 (call-interactively 'org-footnote-action))
15942 ((org-at-item-checkbox-p)
15943 (call-interactively 'org-toggle-checkbox))
15944 ((org-at-item-p)
15945 (if arg
15946 (call-interactively 'org-toggle-checkbox)
15947 (call-interactively 'org-maybe-renumber-ordered-list)))
15948 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15949 ;; Dynamic block
15950 (beginning-of-line 1)
15951 (save-excursion (org-update-dblock)))
15952 ((save-excursion
15953 (beginning-of-line 1)
15954 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15955 (cond
15956 ((equal (match-string 1) "TBLFM")
15957 ;; Recalculate the table before this line
15958 (save-excursion
15959 (beginning-of-line 1)
15960 (skip-chars-backward " \r\n\t")
15961 (if (org-at-table-p)
15962 (org-call-with-arg 'org-table-recalculate (or arg t)))))
15964 (let ((org-inhibit-startup-visibility-stuff t)
15965 (org-startup-align-all-tables nil))
15966 (org-save-outline-visibility 'use-markers (org-mode-restart)))
15967 (message "Local setup has been refreshed"))))
15968 ((org-clock-update-time-maybe))
15969 (t (error "C-c C-c can do nothing useful at this location")))))
15971 (defun org-mode-restart ()
15972 "Restart Org-mode, to scan again for special lines.
15973 Also updates the keyword regular expressions."
15974 (interactive)
15975 (org-mode)
15976 (message "Org-mode restarted"))
15978 (defun org-kill-note-or-show-branches ()
15979 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15980 (interactive)
15981 (if (not org-finish-function)
15982 (call-interactively 'show-branches)
15983 (let ((org-note-abort t))
15984 (funcall org-finish-function))))
15986 (defun org-return (&optional indent)
15987 "Goto next table row or insert a newline.
15988 Calls `org-table-next-row' or `newline', depending on context.
15989 See the individual commands for more information."
15990 (interactive)
15991 (cond
15992 ((bobp) (if indent (newline-and-indent) (newline)))
15993 ((org-at-table-p)
15994 (org-table-justify-field-maybe)
15995 (call-interactively 'org-table-next-row))
15996 ((and org-return-follows-link
15997 (eq (get-text-property (point) 'face) 'org-link))
15998 (call-interactively 'org-open-at-point))
15999 ((and (org-at-heading-p)
16000 (looking-at
16001 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
16002 (org-show-entry)
16003 (end-of-line 1)
16004 (newline))
16005 (t (if indent (newline-and-indent) (newline)))))
16007 (defun org-return-indent ()
16008 "Goto next table row or insert a newline and indent.
16009 Calls `org-table-next-row' or `newline-and-indent', depending on
16010 context. See the individual commands for more information."
16011 (interactive)
16012 (org-return t))
16014 (defun org-ctrl-c-star ()
16015 "Compute table, or change heading status of lines.
16016 Calls `org-table-recalculate' or `org-toggle-heading',
16017 depending on context."
16018 (interactive)
16019 (cond
16020 ((org-at-table-p)
16021 (call-interactively 'org-table-recalculate))
16023 ;; Convert all lines in region to list items
16024 (call-interactively 'org-toggle-heading))))
16026 (defun org-ctrl-c-minus ()
16027 "Insert separator line in table or modify bullet status of line.
16028 Also turns a plain line or a region of lines into list items.
16029 Calls `org-table-insert-hline', `org-toggle-item', or
16030 `org-cycle-list-bullet', depending on context."
16031 (interactive)
16032 (cond
16033 ((org-at-table-p)
16034 (call-interactively 'org-table-insert-hline))
16035 ((org-region-active-p)
16036 (call-interactively 'org-toggle-item))
16037 ((org-in-item-p)
16038 (call-interactively 'org-cycle-list-bullet))
16040 (call-interactively 'org-toggle-item))))
16042 (defun org-toggle-item ()
16043 "Convert headings or normal lines to items, items to normal lines.
16044 If there is no active region, only the current line is considered.
16046 If the first line in the region is a headline, convert all headlines to items.
16048 If the first line in the region is an item, convert all items to normal lines.
16050 If the first line is normal text, add an item bullet to each line."
16051 (interactive)
16052 (let (l2 l beg end)
16053 (if (org-region-active-p)
16054 (setq beg (region-beginning) end (region-end))
16055 (setq beg (point-at-bol)
16056 end (min (1+ (point-at-eol)) (point-max))))
16057 (save-excursion
16058 (goto-char end)
16059 (setq l2 (org-current-line))
16060 (goto-char beg)
16061 (beginning-of-line 1)
16062 (setq l (1- (org-current-line)))
16063 (if (org-at-item-p)
16064 ;; We already have items, de-itemize
16065 (while (< (setq l (1+ l)) l2)
16066 (when (org-at-item-p)
16067 (goto-char (match-beginning 2))
16068 (delete-region (match-beginning 2) (match-end 2))
16069 (and (looking-at "[ \t]+") (replace-match "")))
16070 (beginning-of-line 2))
16071 (if (org-on-heading-p)
16072 ;; Headings, convert to items
16073 (while (< (setq l (1+ l)) l2)
16074 (if (looking-at org-outline-regexp)
16075 (replace-match "- " t t))
16076 (beginning-of-line 2))
16077 ;; normal lines, turn them into items
16078 (while (< (setq l (1+ l)) l2)
16079 (unless (org-at-item-p)
16080 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16081 (replace-match "\\1- \\2")))
16082 (beginning-of-line 2)))))))
16084 (defun org-toggle-heading (&optional nstars)
16085 "Convert headings to normal text, or items or text to headings.
16086 If there is no active region, only the current line is considered.
16088 If the first line is a heading, remove the stars from all headlines
16089 in the region.
16091 If the first line is a plain list item, turn all plain list items
16092 into headings.
16094 If the first line is a normal line, turn each and every line in the
16095 region into a heading.
16097 When converting a line into a heading, the number of stars is chosen
16098 such that the lines become children of the current entry. However,
16099 when a prefix argument is given, its value determines the number of
16100 stars to add."
16101 (interactive "P")
16102 (let (l2 l itemp beg end)
16103 (if (org-region-active-p)
16104 (setq beg (region-beginning) end (region-end))
16105 (setq beg (point-at-bol)
16106 end (min (1+ (point-at-eol)) (point-max))))
16107 (save-excursion
16108 (goto-char end)
16109 (setq l2 (org-current-line))
16110 (goto-char beg)
16111 (beginning-of-line 1)
16112 (setq l (1- (org-current-line)))
16113 (if (org-on-heading-p)
16114 ;; We already have headlines, de-star them
16115 (while (< (setq l (1+ l)) l2)
16116 (when (org-on-heading-p t)
16117 (and (looking-at outline-regexp) (replace-match "")))
16118 (beginning-of-line 2))
16119 (setq itemp (org-at-item-p))
16120 (let* ((stars
16121 (if nstars
16122 (make-string (prefix-numeric-value current-prefix-arg)
16124 (save-excursion
16125 (if (re-search-backward org-complex-heading-regexp nil t)
16126 (match-string 1) ""))))
16127 (add-stars (cond (nstars "")
16128 ((equal stars "") "*")
16129 (org-odd-levels-only "**")
16130 (t "*")))
16131 (rpl (concat stars add-stars " ")))
16132 (while (< (setq l (1+ l)) l2)
16133 (if itemp
16134 (and (org-at-item-p) (replace-match rpl t t))
16135 (unless (org-on-heading-p)
16136 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16137 (replace-match (concat rpl (match-string 2))))))
16138 (beginning-of-line 2)))))))
16140 (defun org-meta-return (&optional arg)
16141 "Insert a new heading or wrap a region in a table.
16142 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16143 See the individual commands for more information."
16144 (interactive "P")
16145 (cond
16146 ((run-hook-with-args-until-success 'org-metareturn-hook))
16147 ((org-at-table-p)
16148 (call-interactively 'org-table-wrap-region))
16149 (t (call-interactively 'org-insert-heading))))
16151 ;;; Menu entries
16153 ;; Define the Org-mode menus
16154 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16155 '("Tbl"
16156 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
16157 ["Next Field" org-cycle (org-at-table-p)]
16158 ["Previous Field" org-shifttab (org-at-table-p)]
16159 ["Next Row" org-return (org-at-table-p)]
16160 "--"
16161 ["Blank Field" org-table-blank-field (org-at-table-p)]
16162 ["Edit Field" org-table-edit-field (org-at-table-p)]
16163 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16164 "--"
16165 ("Column"
16166 ["Move Column Left" org-metaleft (org-at-table-p)]
16167 ["Move Column Right" org-metaright (org-at-table-p)]
16168 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16169 ["Insert Column" org-shiftmetaright (org-at-table-p)])
16170 ("Row"
16171 ["Move Row Up" org-metaup (org-at-table-p)]
16172 ["Move Row Down" org-metadown (org-at-table-p)]
16173 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16174 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16175 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16176 "--"
16177 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
16178 ("Rectangle"
16179 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16180 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16181 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16182 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16183 "--"
16184 ("Calculate"
16185 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16186 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16187 ["Edit Formulas" org-edit-special (org-at-table-p)]
16188 "--"
16189 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16190 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16191 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
16192 "--"
16193 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16194 "--"
16195 ["Sum Column/Rectangle" org-table-sum
16196 (or (org-at-table-p) (org-region-active-p))]
16197 ["Which Column?" org-table-current-column (org-at-table-p)])
16198 ["Debug Formulas"
16199 org-table-toggle-formula-debugger
16200 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
16201 ["Show Col/Row Numbers"
16202 org-table-toggle-coordinate-overlays
16203 :style toggle
16204 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
16205 "--"
16206 ["Create" org-table-create (and (not (org-at-table-p))
16207 org-enable-table-editor)]
16208 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16209 ["Import from File" org-table-import (not (org-at-table-p))]
16210 ["Export to File" org-table-export (org-at-table-p)]
16211 "--"
16212 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16214 (easy-menu-define org-org-menu org-mode-map "Org menu"
16215 '("Org"
16216 ("Show/Hide"
16217 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
16218 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
16219 ["Sparse Tree..." org-sparse-tree t]
16220 ["Reveal Context" org-reveal t]
16221 ["Show All" show-all t]
16222 "--"
16223 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
16224 "--"
16225 ["New Heading" org-insert-heading t]
16226 ("Navigate Headings"
16227 ["Up" outline-up-heading t]
16228 ["Next" outline-next-visible-heading t]
16229 ["Previous" outline-previous-visible-heading t]
16230 ["Next Same Level" outline-forward-same-level t]
16231 ["Previous Same Level" outline-backward-same-level t]
16232 "--"
16233 ["Jump" org-goto t])
16234 ("Edit Structure"
16235 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16236 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16237 "--"
16238 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16239 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16240 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16241 "--"
16242 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
16243 "--"
16244 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16245 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16246 ["Demote Heading" org-metaright (not (org-at-table-p))]
16247 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16248 "--"
16249 ["Sort Region/Children" org-sort (not (org-at-table-p))]
16250 "--"
16251 ["Convert to odd levels" org-convert-to-odd-levels t]
16252 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16253 ("Editing"
16254 ["Emphasis..." org-emphasize t]
16255 ["Edit Source Example" org-edit-special t]
16256 "--"
16257 ["Footnote new/jump" org-footnote-action t]
16258 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
16259 ("Archive"
16260 ["Archive (default method)" org-archive-subtree-default t]
16261 "--"
16262 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
16263 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16264 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
16266 "--"
16267 ("Hyperlinks"
16268 ["Store Link (Global)" org-store-link t]
16269 ["Find existing link to here" org-occur-link-in-agenda-files t]
16270 ["Insert Link" org-insert-link t]
16271 ["Follow Link" org-open-at-point t]
16272 "--"
16273 ["Next link" org-next-link t]
16274 ["Previous link" org-previous-link t]
16275 "--"
16276 ["Descriptive Links"
16277 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16278 :style radio
16279 :selected (member '(org-link) buffer-invisibility-spec)]
16280 ["Literal Links"
16281 (progn
16282 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16283 :style radio
16284 :selected (not (member '(org-link) buffer-invisibility-spec))])
16285 "--"
16286 ("TODO Lists"
16287 ["TODO/DONE/-" org-todo t]
16288 ("Select keyword"
16289 ["Next keyword" org-shiftright (org-on-heading-p)]
16290 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16291 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
16292 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
16293 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
16294 ["Show TODO Tree" org-show-todo-tree t]
16295 ["Global TODO list" org-todo-list t]
16296 "--"
16297 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
16298 :selected org-enforce-todo-dependencies :style toggle :active t]
16299 "Settings for tree at point"
16300 ["Do Children sequentially" org-toggle-ordered-property :style radio
16301 :selected (ignore-errors (org-entry-get nil "ORDERED"))
16302 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16303 ["Do Children parallel" org-toggle-ordered-property :style radio
16304 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
16305 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16306 "--"
16307 ["Set Priority" org-priority t]
16308 ["Priority Up" org-shiftup t]
16309 ["Priority Down" org-shiftdown t]
16310 "--"
16311 ["Get news from all feeds" org-feed-update-all t]
16312 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16313 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16314 ("TAGS and Properties"
16315 ["Set Tags" org-set-tags-command t]
16316 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16317 "--"
16318 ["Set property" org-set-property t]
16319 ["Column view of properties" org-columns t]
16320 ["Insert Column View DBlock" org-insert-columns-dblock t])
16321 ("Dates and Scheduling"
16322 ["Timestamp" org-time-stamp t]
16323 ["Timestamp (inactive)" org-time-stamp-inactive t]
16324 ("Change Date"
16325 ["1 Day Later" org-shiftright t]
16326 ["1 Day Earlier" org-shiftleft t]
16327 ["1 ... Later" org-shiftup t]
16328 ["1 ... Earlier" org-shiftdown t])
16329 ["Compute Time Range" org-evaluate-time-range t]
16330 ["Schedule Item" org-schedule t]
16331 ["Deadline" org-deadline t]
16332 "--"
16333 ["Custom time format" org-toggle-time-stamp-overlays
16334 :style radio :selected org-display-custom-times]
16335 "--"
16336 ["Goto Calendar" org-goto-calendar t]
16337 ["Date from Calendar" org-date-from-calendar t]
16338 "--"
16339 ["Start/Restart Timer" org-timer-start t]
16340 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16341 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16342 ["Insert Timer String" org-timer t]
16343 ["Insert Timer Item" org-timer-item t])
16344 ("Logging work"
16345 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16346 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16347 ["Clock out" org-clock-out t]
16348 ["Clock cancel" org-clock-cancel t]
16349 "--"
16350 ["Mark as default task" org-clock-mark-default-task t]
16351 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16352 ["Goto running clock" org-clock-goto t]
16353 "--"
16354 ["Display times" org-clock-display t]
16355 ["Create clock table" org-clock-report t]
16356 "--"
16357 ["Record DONE time"
16358 (progn (setq org-log-done (not org-log-done))
16359 (message "Switching to %s will %s record a timestamp"
16360 (car org-done-keywords)
16361 (if org-log-done "automatically" "not")))
16362 :style toggle :selected org-log-done])
16363 "--"
16364 ["Agenda Command..." org-agenda t]
16365 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16366 ("File List for Agenda")
16367 ("Special views current file"
16368 ["TODO Tree" org-show-todo-tree t]
16369 ["Check Deadlines" org-check-deadlines t]
16370 ["Timeline" org-timeline t]
16371 ["Tags/Property tree" org-match-sparse-tree t])
16372 "--"
16373 ["Export/Publish..." org-export t]
16374 ("LaTeX"
16375 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16376 :selected org-cdlatex-mode]
16377 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16378 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16379 ["Modify math symbol" org-cdlatex-math-modify
16380 (org-inside-LaTeX-fragment-p)]
16381 ["Insert citation" org-reftex-citation t]
16382 "--"
16383 ["Export LaTeX fragments as images"
16384 (if (featurep 'org-exp)
16385 (setq org-export-with-LaTeX-fragments
16386 (not org-export-with-LaTeX-fragments))
16387 (require 'org-exp))
16388 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16389 org-export-with-LaTeX-fragments)]
16390 "--"
16391 ["Template for BEAMER" org-beamer-settings-template t])
16392 "--"
16393 ("MobileOrg"
16394 ["Push Files and Views" org-mobile-push t]
16395 ["Get Captured and Flagged" org-mobile-pull t]
16396 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16397 "--"
16398 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16399 "--"
16400 ("Documentation"
16401 ["Show Version" org-version t]
16402 ["Info Documentation" org-info t])
16403 ("Customize"
16404 ["Browse Org Group" org-customize t]
16405 "--"
16406 ["Expand This Menu" org-create-customize-menu
16407 (fboundp 'customize-menu-create)])
16408 ["Send bug report" org-submit-bug-report t]
16409 "--"
16410 ("Refresh/Reload"
16411 ["Refresh setup current buffer" org-mode-restart t]
16412 ["Reload Org (after update)" org-reload t]
16413 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16416 (defun org-info (&optional node)
16417 "Read documentation for Org-mode in the info system.
16418 With optional NODE, go directly to that node."
16419 (interactive)
16420 (info (format "(org)%s" (or node ""))))
16422 ;;;###autoload
16423 (defun org-submit-bug-report ()
16424 "Submit a bug report on Org-mode via mail.
16426 Don't hesitate to report any problems or inaccurate documentation.
16428 If you don't have setup sending mail from (X)Emacs, please copy the
16429 output buffer into your mail program, as it gives us important
16430 information about your Org-mode version and configuration."
16431 (interactive)
16432 (require 'reporter)
16433 (org-load-modules-maybe)
16434 (org-require-autoloaded-modules)
16435 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16436 (reporter-submit-bug-report
16437 "emacs-orgmode@gnu.org"
16438 (org-version)
16439 (let (list)
16440 (save-window-excursion
16441 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16442 (delete-other-windows)
16443 (erase-buffer)
16444 (insert "You are about to submit a bug report to the Org-mode mailing list.
16446 We would like to add your full Org-mode and Outline configuration to the
16447 bug report. This greatly simplifies the work of the maintainer and
16448 other experts on the mailing list.
16450 HOWEVER, some variables you have customized may contain private
16451 information. The names of customers, colleagues, or friends, might
16452 appear in the form of file names, tags, todo states, or search strings.
16453 If you answer yes to the prompt, you might want to check and remove
16454 such private information before sending the email.")
16455 (add-text-properties (point-min) (point-max) '(face org-warning))
16456 (when (yes-or-no-p "Include your Org-mode configuration ")
16457 (mapatoms
16458 (lambda (v)
16459 (and (boundp v)
16460 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16461 (or (and (symbol-value v)
16462 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16463 (and
16464 (get v 'custom-type) (get v 'standard-value)
16465 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16466 (push v list)))))
16467 (kill-buffer (get-buffer "*Warn about privacy*"))
16468 list))
16469 nil nil
16470 "Remember to cover the basics, that is, what you expected to happen and
16471 what in fact did happen. You don't know how to make a good report? See
16473 http://orgmode.org/manual/Feedback.html#Feedback
16475 Your bug report will be posted to the Org-mode mailing list.
16476 ------------------------------------------------------------------------")
16477 (save-excursion
16478 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16479 (replace-match "\\1Bug: \\3 [\\2]")))))
16482 (defun org-install-agenda-files-menu ()
16483 (let ((bl (buffer-list)))
16484 (save-excursion
16485 (while bl
16486 (set-buffer (pop bl))
16487 (if (org-mode-p) (setq bl nil)))
16488 (when (org-mode-p)
16489 (easy-menu-change
16490 '("Org") "File List for Agenda"
16491 (append
16492 (list
16493 ["Edit File List" (org-edit-agenda-file-list) t]
16494 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16495 ["Remove Current File from List" org-remove-file t]
16496 ["Cycle through agenda files" org-cycle-agenda-files t]
16497 ["Occur in all agenda files" org-occur-in-agenda-files t]
16498 "--")
16499 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16501 ;;;; Documentation
16503 ;;;###autoload
16504 (defun org-require-autoloaded-modules ()
16505 (interactive)
16506 (mapc 'require
16507 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16508 org-docbook org-exp org-html org-icalendar
16509 org-id org-latex
16510 org-publish org-remember org-table
16511 org-timer org-xoxo)))
16513 ;;;###autoload
16514 (defun org-reload (&optional uncompiled)
16515 "Reload all org lisp files.
16516 With prefix arg UNCOMPILED, load the uncompiled versions."
16517 (interactive "P")
16518 (require 'find-func)
16519 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16520 (dir-org (file-name-directory (org-find-library-name "org")))
16521 (dir-org-contrib (ignore-errors
16522 (file-name-directory
16523 (org-find-library-name "org-contribdir"))))
16524 (files
16525 (append (directory-files dir-org t file-re)
16526 (and dir-org-contrib
16527 (directory-files dir-org-contrib t file-re))))
16528 (remove-re (concat (if (featurep 'xemacs)
16529 "org-colview" "org-colview-xemacs")
16530 "\\'")))
16531 (setq files (mapcar 'file-name-sans-extension files))
16532 (setq files (mapcar
16533 (lambda (x) (if (string-match remove-re x) nil x))
16534 files))
16535 (setq files (delq nil files))
16536 (mapc
16537 (lambda (f)
16538 (when (featurep (intern (file-name-nondirectory f)))
16539 (if (and (not uncompiled)
16540 (file-exists-p (concat f ".elc")))
16541 (load (concat f ".elc") nil nil t)
16542 (load (concat f ".el") nil nil t))))
16543 files))
16544 (org-version))
16546 ;;;###autoload
16547 (defun org-customize ()
16548 "Call the customize function with org as argument."
16549 (interactive)
16550 (org-load-modules-maybe)
16551 (org-require-autoloaded-modules)
16552 (customize-browse 'org))
16554 (defun org-create-customize-menu ()
16555 "Create a full customization menu for Org-mode, insert it into the menu."
16556 (interactive)
16557 (org-load-modules-maybe)
16558 (org-require-autoloaded-modules)
16559 (if (fboundp 'customize-menu-create)
16560 (progn
16561 (easy-menu-change
16562 '("Org") "Customize"
16563 `(["Browse Org group" org-customize t]
16564 "--"
16565 ,(customize-menu-create 'org)
16566 ["Set" Custom-set t]
16567 ["Save" Custom-save t]
16568 ["Reset to Current" Custom-reset-current t]
16569 ["Reset to Saved" Custom-reset-saved t]
16570 ["Reset to Standard Settings" Custom-reset-standard t]))
16571 (message "\"Org\"-menu now contains full customization menu"))
16572 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16574 ;;;; Miscellaneous stuff
16576 ;;; Generally useful functions
16578 (defun org-get-at-bol (property)
16579 "Get text property PROPERTY at beginning of line."
16580 (get-text-property (point-at-bol) property))
16582 (defun org-find-text-property-in-string (prop s)
16583 "Return the first non-nil value of property PROP in string S."
16584 (or (get-text-property 0 prop s)
16585 (get-text-property (or (next-single-property-change 0 prop s) 0)
16586 prop s)))
16588 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16589 "Display the given MESSAGE as a warning."
16590 (if (fboundp 'display-warning)
16591 (display-warning 'org message
16592 (if (featurep 'xemacs)
16593 'warning
16594 :warning))
16595 (let ((buf (get-buffer-create "*Org warnings*")))
16596 (with-current-buffer buf
16597 (goto-char (point-max))
16598 (insert "Warning (Org): " message)
16599 (unless (bolp)
16600 (newline)))
16601 (display-buffer buf)
16602 (sit-for 0))))
16604 (defun org-in-commented-line ()
16605 "Is point in a line starting with `#'?"
16606 (equal (char-after (point-at-bol)) ?#))
16608 (defun org-in-verbatim-emphasis ()
16609 (save-match-data
16610 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16612 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16613 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16614 (if (and marker (marker-buffer marker)
16615 (buffer-live-p (marker-buffer marker)))
16616 (progn
16617 (switch-to-buffer (marker-buffer marker))
16618 (if (or (> marker (point-max)) (< marker (point-min)))
16619 (widen))
16620 (goto-char marker)
16621 (org-show-context 'org-goto))
16622 (if bookmark
16623 (bookmark-jump bookmark)
16624 (error "Cannot find location"))))
16626 (defun org-quote-csv-field (s)
16627 "Quote field for inclusion in CSV material."
16628 (if (string-match "[\",]" s)
16629 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16632 (defun org-plist-delete (plist property)
16633 "Delete PROPERTY from PLIST.
16634 This is in contrast to merely setting it to 0."
16635 (let (p)
16636 (while plist
16637 (if (not (eq property (car plist)))
16638 (setq p (plist-put p (car plist) (nth 1 plist))))
16639 (setq plist (cddr plist)))
16642 (defun org-force-self-insert (N)
16643 "Needed to enforce self-insert under remapping."
16644 (interactive "p")
16645 (self-insert-command N))
16647 (defun org-string-width (s)
16648 "Compute width of string, ignoring invisible characters.
16649 This ignores character with invisibility property `org-link', and also
16650 characters with property `org-cwidth', because these will become invisible
16651 upon the next fontification round."
16652 (let (b l)
16653 (when (or (eq t buffer-invisibility-spec)
16654 (assq 'org-link buffer-invisibility-spec))
16655 (while (setq b (text-property-any 0 (length s)
16656 'invisible 'org-link s))
16657 (setq s (concat (substring s 0 b)
16658 (substring s (or (next-single-property-change
16659 b 'invisible s) (length s)))))))
16660 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16661 (setq s (concat (substring s 0 b)
16662 (substring s (or (next-single-property-change
16663 b 'org-cwidth s) (length s))))))
16664 (setq l (string-width s) b -1)
16665 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16666 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16669 (defun org-get-indentation (&optional line)
16670 "Get the indentation of the current line, interpreting tabs.
16671 When LINE is given, assume it represents a line and compute its indentation."
16672 (if line
16673 (if (string-match "^ *" (org-remove-tabs line))
16674 (match-end 0))
16675 (save-excursion
16676 (beginning-of-line 1)
16677 (skip-chars-forward " \t")
16678 (current-column))))
16680 (defun org-remove-tabs (s &optional width)
16681 "Replace tabulators in S with spaces.
16682 Assumes that s is a single line, starting in column 0."
16683 (setq width (or width tab-width))
16684 (while (string-match "\t" s)
16685 (setq s (replace-match
16686 (make-string
16687 (- (* width (/ (+ (match-beginning 0) width) width))
16688 (match-beginning 0)) ?\ )
16689 t t s)))
16692 (defun org-fix-indentation (line ind)
16693 "Fix indentation in LINE.
16694 IND is a cons cell with target and minimum indentation.
16695 If the current indentation in LINE is smaller than the minimum,
16696 leave it alone. If it is larger than ind, set it to the target."
16697 (let* ((l (org-remove-tabs line))
16698 (i (org-get-indentation l))
16699 (i1 (car ind)) (i2 (cdr ind)))
16700 (if (>= i i2) (setq l (substring line i2)))
16701 (if (> i1 0)
16702 (concat (make-string i1 ?\ ) l)
16703 l)))
16705 (defun org-remove-indentation (code &optional n)
16706 "Remove the maximum common indentation from the lines in CODE.
16707 N may optionally be the number of spaces to remove."
16708 (with-temp-buffer
16709 (insert code)
16710 (org-do-remove-indentation n)
16711 (buffer-string)))
16713 (defun org-do-remove-indentation (&optional n)
16714 "Remove the maximum common indentation from the buffer."
16715 (untabify (point-min) (point-max))
16716 (let ((min 10000) re)
16717 (if n
16718 (setq min n)
16719 (goto-char (point-min))
16720 (while (re-search-forward "^ *[^ \n]" nil t)
16721 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16722 (unless (or (= min 0) (= min 10000))
16723 (setq re (format "^ \\{%d\\}" min))
16724 (goto-char (point-min))
16725 (while (re-search-forward re nil t)
16726 (replace-match "")
16727 (end-of-line 1))
16728 min)))
16730 (defun org-fill-template (template alist)
16731 "Find each %key of ALIST in TEMPLATE and replace it."
16732 (let ((case-fold-search nil)
16733 entry key value)
16734 (setq alist (sort (copy-sequence alist)
16735 (lambda (a b) (< (length (car a)) (length (car b))))))
16736 (while (setq entry (pop alist))
16737 (setq template
16738 (replace-regexp-in-string
16739 (concat "%" (regexp-quote (car entry)))
16740 (cdr entry) template t t)))
16741 template))
16743 (defun org-base-buffer (buffer)
16744 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16745 (if (not buffer)
16746 buffer
16747 (or (buffer-base-buffer buffer)
16748 buffer)))
16750 (defun org-trim (s)
16751 "Remove whitespace at beginning and end of string."
16752 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
16753 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
16756 (defun org-wrap (string &optional width lines)
16757 "Wrap string to either a number of lines, or a width in characters.
16758 If WIDTH is non-nil, the string is wrapped to that width, however many lines
16759 that costs. If there is a word longer than WIDTH, the text is actually
16760 wrapped to the length of that word.
16761 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
16762 many lines, whatever width that takes.
16763 The return value is a list of lines, without newlines at the end."
16764 (let* ((words (org-split-string string "[ \t\n]+"))
16765 (maxword (apply 'max (mapcar 'org-string-width words)))
16766 w ll)
16767 (cond (width
16768 (org-do-wrap words (max maxword width)))
16769 (lines
16770 (setq w maxword)
16771 (setq ll (org-do-wrap words maxword))
16772 (if (<= (length ll) lines)
16774 (setq ll words)
16775 (while (> (length ll) lines)
16776 (setq w (1+ w))
16777 (setq ll (org-do-wrap words w)))
16778 ll))
16779 (t (error "Cannot wrap this")))))
16781 (defun org-do-wrap (words width)
16782 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
16783 (let (lines line)
16784 (while words
16785 (setq line (pop words))
16786 (while (and words (< (+ (length line) (length (car words))) width))
16787 (setq line (concat line " " (pop words))))
16788 (setq lines (push line lines)))
16789 (nreverse lines)))
16791 (defun org-split-string (string &optional separators)
16792 "Splits STRING into substrings at SEPARATORS.
16793 No empty strings are returned if there are matches at the beginning
16794 and end of string."
16795 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
16796 (start 0)
16797 notfirst
16798 (list nil))
16799 (while (and (string-match rexp string
16800 (if (and notfirst
16801 (= start (match-beginning 0))
16802 (< start (length string)))
16803 (1+ start) start))
16804 (< (match-beginning 0) (length string)))
16805 (setq notfirst t)
16806 (or (eq (match-beginning 0) 0)
16807 (and (eq (match-beginning 0) (match-end 0))
16808 (eq (match-beginning 0) start))
16809 (setq list
16810 (cons (substring string start (match-beginning 0))
16811 list)))
16812 (setq start (match-end 0)))
16813 (or (eq start (length string))
16814 (setq list
16815 (cons (substring string start)
16816 list)))
16817 (nreverse list)))
16819 (defun org-quote-vert (s)
16820 "Replace \"|\" with \"\\vert\"."
16821 (while (string-match "|" s)
16822 (setq s (replace-match "\\vert" t t s)))
16825 (defun org-uuidgen-p (s)
16826 "Is S an ID created by UUIDGEN?"
16827 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16829 (defun org-context ()
16830 "Return a list of contexts of the current cursor position.
16831 If several contexts apply, all are returned.
16832 Each context entry is a list with a symbol naming the context, and
16833 two positions indicating start and end of the context. Possible
16834 contexts are:
16836 :headline anywhere in a headline
16837 :headline-stars on the leading stars in a headline
16838 :todo-keyword on a TODO keyword (including DONE) in a headline
16839 :tags on the TAGS in a headline
16840 :priority on the priority cookie in a headline
16841 :item on the first line of a plain list item
16842 :item-bullet on the bullet/number of a plain list item
16843 :checkbox on the checkbox in a plain list item
16844 :table in an org-mode table
16845 :table-special on a special filed in a table
16846 :table-table in a table.el table
16847 :link on a hyperlink
16848 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16849 :target on a <<target>>
16850 :radio-target on a <<<radio-target>>>
16851 :latex-fragment on a LaTeX fragment
16852 :latex-preview on a LaTeX fragment with overlayed preview image
16854 This function expects the position to be visible because it uses font-lock
16855 faces as a help to recognize the following contexts: :table-special, :link,
16856 and :keyword."
16857 (let* ((f (get-text-property (point) 'face))
16858 (faces (if (listp f) f (list f)))
16859 (p (point)) clist o)
16860 ;; First the large context
16861 (cond
16862 ((org-on-heading-p t)
16863 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16864 (when (progn
16865 (beginning-of-line 1)
16866 (looking-at org-todo-line-tags-regexp))
16867 (push (org-point-in-group p 1 :headline-stars) clist)
16868 (push (org-point-in-group p 2 :todo-keyword) clist)
16869 (push (org-point-in-group p 4 :tags) clist))
16870 (goto-char p)
16871 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
16872 (if (looking-at "\\[#[A-Z0-9]\\]")
16873 (push (org-point-in-group p 0 :priority) clist)))
16875 ((org-at-item-p)
16876 (push (org-point-in-group p 2 :item-bullet) clist)
16877 (push (list :item (point-at-bol)
16878 (save-excursion (org-end-of-item) (point)))
16879 clist)
16880 (and (org-at-item-checkbox-p)
16881 (push (org-point-in-group p 0 :checkbox) clist)))
16883 ((org-at-table-p)
16884 (push (list :table (org-table-begin) (org-table-end)) clist)
16885 (if (memq 'org-formula faces)
16886 (push (list :table-special
16887 (previous-single-property-change p 'face)
16888 (next-single-property-change p 'face)) clist)))
16889 ((org-at-table-p 'any)
16890 (push (list :table-table) clist)))
16891 (goto-char p)
16893 ;; Now the small context
16894 (cond
16895 ((org-at-timestamp-p)
16896 (push (org-point-in-group p 0 :timestamp) clist))
16897 ((memq 'org-link faces)
16898 (push (list :link
16899 (previous-single-property-change p 'face)
16900 (next-single-property-change p 'face)) clist))
16901 ((memq 'org-special-keyword faces)
16902 (push (list :keyword
16903 (previous-single-property-change p 'face)
16904 (next-single-property-change p 'face)) clist))
16905 ((org-on-target-p)
16906 (push (org-point-in-group p 0 :target) clist)
16907 (goto-char (1- (match-beginning 0)))
16908 (if (looking-at org-radio-target-regexp)
16909 (push (org-point-in-group p 0 :radio-target) clist))
16910 (goto-char p))
16911 ((setq o (car (delq nil
16912 (mapcar
16913 (lambda (x)
16914 (if (memq x org-latex-fragment-image-overlays) x))
16915 (org-overlays-at (point))))))
16916 (push (list :latex-fragment
16917 (org-overlay-start o) (org-overlay-end o)) clist)
16918 (push (list :latex-preview
16919 (org-overlay-start o) (org-overlay-end o)) clist))
16920 ((org-inside-LaTeX-fragment-p)
16921 ;; FIXME: positions wrong.
16922 (push (list :latex-fragment (point) (point)) clist)))
16924 (setq clist (nreverse (delq nil clist)))
16925 clist))
16927 ;; FIXME: Compare with at-regexp-p Do we need both?
16928 (defun org-in-regexp (re &optional nlines visually)
16929 "Check if point is inside a match of regexp.
16930 Normally only the current line is checked, but you can include NLINES extra
16931 lines both before and after point into the search.
16932 If VISUALLY is set, require that the cursor is not after the match but
16933 really on, so that the block visually is on the match."
16934 (catch 'exit
16935 (let ((pos (point))
16936 (eol (point-at-eol (+ 1 (or nlines 0))))
16937 (inc (if visually 1 0)))
16938 (save-excursion
16939 (beginning-of-line (- 1 (or nlines 0)))
16940 (while (re-search-forward re eol t)
16941 (if (and (<= (match-beginning 0) pos)
16942 (>= (+ inc (match-end 0)) pos))
16943 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16945 (defun org-at-regexp-p (regexp)
16946 "Is point inside a match of REGEXP in the current line?"
16947 (catch 'exit
16948 (save-excursion
16949 (let ((pos (point)) (end (point-at-eol)))
16950 (beginning-of-line 1)
16951 (while (re-search-forward regexp end t)
16952 (if (and (<= (match-beginning 0) pos)
16953 (>= (match-end 0) pos))
16954 (throw 'exit t)))
16955 nil))))
16957 (defun org-occur-in-agenda-files (regexp &optional nlines)
16958 "Call `multi-occur' with buffers for all agenda files."
16959 (interactive "sOrg-files matching: \np")
16960 (let* ((files (org-agenda-files))
16961 (tnames (mapcar 'file-truename files))
16962 (extra org-agenda-text-search-extra-files)
16964 (when (eq (car extra) 'agenda-archives)
16965 (setq extra (cdr extra))
16966 (setq files (org-add-archive-files files)))
16967 (while (setq f (pop extra))
16968 (unless (member (file-truename f) tnames)
16969 (add-to-list 'files f 'append)
16970 (add-to-list 'tnames (file-truename f) 'append)))
16971 (multi-occur
16972 (mapcar (lambda (x)
16973 (with-current-buffer
16974 (or (get-file-buffer x) (find-file-noselect x))
16975 (widen)
16976 (current-buffer)))
16977 files)
16978 regexp)))
16980 (if (boundp 'occur-mode-find-occurrence-hook)
16981 ;; Emacs 23
16982 (add-hook 'occur-mode-find-occurrence-hook
16983 (lambda ()
16984 (when (org-mode-p)
16985 (org-reveal))))
16986 ;; Emacs 22
16987 (defadvice occur-mode-goto-occurrence
16988 (after org-occur-reveal activate)
16989 (and (org-mode-p) (org-reveal)))
16990 (defadvice occur-mode-goto-occurrence-other-window
16991 (after org-occur-reveal activate)
16992 (and (org-mode-p) (org-reveal)))
16993 (defadvice occur-mode-display-occurrence
16994 (after org-occur-reveal activate)
16995 (when (org-mode-p)
16996 (let ((pos (occur-mode-find-occurrence)))
16997 (with-current-buffer (marker-buffer pos)
16998 (save-excursion
16999 (goto-char pos)
17000 (org-reveal)))))))
17002 (defun org-occur-link-in-agenda-files ()
17003 "Create a link and search for it in the agendas.
17004 The link is not stored in `org-stored-links', it is just created
17005 for the search purpose."
17006 (interactive)
17007 (let ((link (condition-case nil
17008 (org-store-link nil)
17009 (error "Unable to create a link to here"))))
17010 (org-occur-in-agenda-files (regexp-quote link))))
17012 (defun org-uniquify (list)
17013 "Remove duplicate elements from LIST."
17014 (let (res)
17015 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
17016 res))
17018 (defun org-delete-all (elts list)
17019 "Remove all elements in ELTS from LIST."
17020 (while elts
17021 (setq list (delete (pop elts) list)))
17022 list)
17024 (defun org-back-over-empty-lines ()
17025 "Move backwards over whitespace, to the beginning of the first empty line.
17026 Returns the number of empty lines passed."
17027 (let ((pos (point)))
17028 (skip-chars-backward " \t\n\r")
17029 (beginning-of-line 2)
17030 (goto-char (min (point) pos))
17031 (count-lines (point) pos)))
17033 (defun org-skip-whitespace ()
17034 (skip-chars-forward " \t\n\r"))
17036 (defun org-point-in-group (point group &optional context)
17037 "Check if POINT is in match-group GROUP.
17038 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
17039 match. If the match group does ot exist or point is not inside it,
17040 return nil."
17041 (and (match-beginning group)
17042 (>= point (match-beginning group))
17043 (<= point (match-end group))
17044 (if context
17045 (list context (match-beginning group) (match-end group))
17046 t)))
17048 (defun org-switch-to-buffer-other-window (&rest args)
17049 "Switch to buffer in a second window on the current frame.
17050 In particular, do not allow pop-up frames."
17051 (let (pop-up-frames special-display-buffer-names special-display-regexps
17052 special-display-function)
17053 (apply 'switch-to-buffer-other-window args)))
17055 (defun org-combine-plists (&rest plists)
17056 "Create a single property list from all plists in PLISTS.
17057 The process starts by copying the first list, and then setting properties
17058 from the other lists. Settings in the last list are the most significant
17059 ones and overrule settings in the other lists."
17060 (let ((rtn (copy-sequence (pop plists)))
17061 p v ls)
17062 (while plists
17063 (setq ls (pop plists))
17064 (while ls
17065 (setq p (pop ls) v (pop ls))
17066 (setq rtn (plist-put rtn p v))))
17067 rtn))
17069 (defun org-move-line-down (arg)
17070 "Move the current line down. With prefix argument, move it past ARG lines."
17071 (interactive "p")
17072 (let ((col (current-column))
17073 beg end pos)
17074 (beginning-of-line 1) (setq beg (point))
17075 (beginning-of-line 2) (setq end (point))
17076 (beginning-of-line (+ 1 arg))
17077 (setq pos (move-marker (make-marker) (point)))
17078 (insert (delete-and-extract-region beg end))
17079 (goto-char pos)
17080 (org-move-to-column col)))
17082 (defun org-move-line-up (arg)
17083 "Move the current line up. With prefix argument, move it past ARG lines."
17084 (interactive "p")
17085 (let ((col (current-column))
17086 beg end pos)
17087 (beginning-of-line 1) (setq beg (point))
17088 (beginning-of-line 2) (setq end (point))
17089 (beginning-of-line (- arg))
17090 (setq pos (move-marker (make-marker) (point)))
17091 (insert (delete-and-extract-region beg end))
17092 (goto-char pos)
17093 (org-move-to-column col)))
17095 (defun org-replace-escapes (string table)
17096 "Replace %-escapes in STRING with values in TABLE.
17097 TABLE is an association list with keys like \"%a\" and string values.
17098 The sequences in STRING may contain normal field width and padding information,
17099 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
17100 so values can contain further %-escapes if they are define later in TABLE."
17101 (let ((case-fold-search nil)
17102 e re rpl)
17103 (while (setq e (pop table))
17104 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
17105 (while (string-match re string)
17106 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
17107 (cdr e)))
17108 (setq string (replace-match rpl t t string))))
17109 string))
17112 (defun org-sublist (list start end)
17113 "Return a section of LIST, from START to END.
17114 Counting starts at 1."
17115 (let (rtn (c start))
17116 (setq list (nthcdr (1- start) list))
17117 (while (and list (<= c end))
17118 (push (pop list) rtn)
17119 (setq c (1+ c)))
17120 (nreverse rtn)))
17122 (defun org-find-base-buffer-visiting (file)
17123 "Like `find-buffer-visiting' but always return the base buffer and
17124 not an indirect buffer."
17125 (let ((buf (or (get-file-buffer file)
17126 (find-buffer-visiting file))))
17127 (if buf
17128 (or (buffer-base-buffer buf) buf)
17129 nil)))
17131 (defun org-image-file-name-regexp (&optional extensions)
17132 "Return regexp matching the file names of images.
17133 If EXTENSIONS is given, only match these."
17134 (if (and (not extensions) (fboundp 'image-file-name-regexp))
17135 (image-file-name-regexp)
17136 (let ((image-file-name-extensions
17137 (or extensions
17138 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
17139 "xbm" "xpm" "pbm" "pgm" "ppm"))))
17140 (concat "\\."
17141 (regexp-opt (nconc (mapcar 'upcase
17142 image-file-name-extensions)
17143 image-file-name-extensions)
17145 "\\'"))))
17147 (defun org-file-image-p (file &optional extensions)
17148 "Return non-nil if FILE is an image."
17149 (save-match-data
17150 (string-match (org-image-file-name-regexp extensions) file)))
17152 (defun org-get-cursor-date ()
17153 "Return the date at cursor in as a time.
17154 This works in the calendar and in the agenda, anywhere else it just
17155 returns the current time."
17156 (let (date day defd)
17157 (cond
17158 ((eq major-mode 'calendar-mode)
17159 (setq date (calendar-cursor-to-date)
17160 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17161 ((eq major-mode 'org-agenda-mode)
17162 (setq day (get-text-property (point) 'day))
17163 (if day
17164 (setq date (calendar-gregorian-from-absolute day)
17165 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
17166 (nth 2 date))))))
17167 (or defd (current-time))))
17169 (defvar org-agenda-action-marker (make-marker)
17170 "Marker pointing to the entry for the next agenda action.")
17172 (defun org-mark-entry-for-agenda-action ()
17173 "Mark the current entry as target of an agenda action.
17174 Agenda actions are actions executed from the agenda with the key `k',
17175 which make use of the date at the cursor."
17176 (interactive)
17177 (move-marker org-agenda-action-marker
17178 (save-excursion (org-back-to-heading t) (point))
17179 (current-buffer))
17180 (message
17181 "Entry marked for action; press `k' at desired date in agenda or calendar"))
17183 ;;; Paragraph filling stuff.
17184 ;; We want this to be just right, so use the full arsenal.
17186 (defun org-indent-line-function ()
17187 "Indent line like previous, but further if previous was headline or item."
17188 (interactive)
17189 (let* ((pos (point))
17190 (itemp (org-at-item-p))
17191 (case-fold-search t)
17192 (org-drawer-regexp (or org-drawer-regexp "\000"))
17193 column bpos bcol tpos tcol bullet btype bullet-type)
17194 ;; Find the previous relevant line
17195 (beginning-of-line 1)
17196 (cond
17197 ((looking-at "#") (setq column 0))
17198 ((looking-at "\\*+ ") (setq column 0))
17199 ((and (looking-at "[ \t]*:END:")
17200 (save-excursion (re-search-backward org-drawer-regexp nil t)))
17201 (save-excursion
17202 (goto-char (1- (match-beginning 1)))
17203 (setq column (current-column))))
17204 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
17205 (save-excursion
17206 (re-search-backward
17207 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
17208 (setq column (org-get-indentation (match-string 0))))
17210 (beginning-of-line 0)
17211 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
17212 (not (looking-at "[ \t]*:END:"))
17213 (not (looking-at org-drawer-regexp)))
17214 (beginning-of-line 0))
17215 (cond
17216 ((looking-at "\\*+[ \t]+")
17217 (if (not org-adapt-indentation)
17218 (setq column 0)
17219 (goto-char (match-end 0))
17220 (setq column (current-column))))
17221 ((looking-at org-drawer-regexp)
17222 (goto-char (1- (match-beginning 1)))
17223 (setq column (current-column)))
17224 ((looking-at "\\([ \t]*\\):END:")
17225 (goto-char (match-end 1))
17226 (setq column (current-column)))
17227 ((org-in-item-p)
17228 (org-beginning-of-item)
17229 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
17230 (setq bpos (match-beginning 1) tpos (match-end 0)
17231 bcol (progn (goto-char bpos) (current-column))
17232 tcol (progn (goto-char tpos) (current-column))
17233 bullet (match-string 1)
17234 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
17235 (if (> tcol (+ bcol org-description-max-indent))
17236 (setq tcol (+ bcol 5)))
17237 (if (not itemp)
17238 (setq column tcol)
17239 (goto-char pos)
17240 (beginning-of-line 1)
17241 (if (looking-at "\\S-")
17242 (progn
17243 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
17244 (setq bullet (match-string 1)
17245 btype (if (string-match "[0-9]" bullet) "n" bullet))
17246 (setq column (if (equal btype bullet-type) bcol tcol)))
17247 (setq column (org-get-indentation)))))
17248 (t (setq column (org-get-indentation))))))
17249 (goto-char pos)
17250 (if (<= (current-column) (current-indentation))
17251 (org-indent-line-to column)
17252 (save-excursion (org-indent-line-to column)))
17253 (setq column (current-column))
17254 (beginning-of-line 1)
17255 (if (looking-at
17256 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
17257 (replace-match (concat (match-string 1)
17258 (format org-property-format
17259 (match-string 2) (match-string 3)))
17260 t t))
17261 (org-move-to-column column)))
17263 (defun org-set-autofill-regexps ()
17264 (interactive)
17265 ;; In the paragraph separator we include headlines, because filling
17266 ;; text in a line directly attached to a headline would otherwise
17267 ;; fill the headline as well.
17268 (org-set-local 'comment-start-skip "^#+[ \t]*")
17269 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
17270 ;; The paragraph starter includes hand-formatted lists.
17271 (org-set-local
17272 'paragraph-start
17273 (concat
17274 "\f" "\\|"
17275 "[ ]*$" "\\|"
17276 "\\*+ " "\\|"
17277 "[ \t]*#" "\\|"
17278 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
17279 "[ \t]*[:|]" "\\|"
17280 "\\$\\$" "\\|"
17281 "\\\\\\(begin\\|end\\|[][]\\)"))
17282 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17283 ;; But only if the user has not turned off tables or fixed-width regions
17284 (org-set-local
17285 'auto-fill-inhibit-regexp
17286 (concat "\\*+ \\|#\\+"
17287 "\\|[ \t]*" org-keyword-time-regexp
17288 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17289 (concat
17290 "\\|[ \t]*["
17291 (if org-enable-table-editor "|" "")
17292 (if org-enable-fixed-width-editor ":" "")
17293 "]"))))
17294 ;; We use our own fill-paragraph function, to make sure that tables
17295 ;; and fixed-width regions are not wrapped. That function will pass
17296 ;; through to `fill-paragraph' when appropriate.
17297 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17298 ; Adaptive filling: To get full control, first make sure that
17299 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17300 (org-set-local 'adaptive-fill-regexp "\000")
17301 (org-set-local 'adaptive-fill-function
17302 'org-adaptive-fill-function)
17303 (org-set-local
17304 'align-mode-rules-list
17305 '((org-in-buffer-settings
17306 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
17307 (modes . '(org-mode))))))
17309 (defun org-fill-paragraph (&optional justify)
17310 "Re-align a table, pass through to fill-paragraph if no table."
17311 (let ((table-p (org-at-table-p))
17312 (table.el-p (org-at-table.el-p)))
17313 (cond ((and (equal (char-after (point-at-bol)) ?*)
17314 (save-excursion (goto-char (point-at-bol))
17315 (looking-at outline-regexp)))
17316 t) ; skip headlines
17317 (table.el-p t) ; skip table.el tables
17318 (table-p (org-table-align) t) ; align org-mode tables
17319 (t nil)))) ; call paragraph-fill
17321 ;; For reference, this is the default value of adaptive-fill-regexp
17322 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17324 (defun org-adaptive-fill-function ()
17325 "Return a fill prefix for org-mode files.
17326 In particular, this makes sure hanging paragraphs for hand-formatted lists
17327 work correctly."
17328 (cond ((looking-at "#[ \t]+")
17329 (match-string 0))
17330 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17331 (save-excursion
17332 (if (> (match-end 1) (+ (match-beginning 1)
17333 org-description-max-indent))
17334 (goto-char (+ (match-beginning 1) 5))
17335 (goto-char (match-end 0)))
17336 (make-string (current-column) ?\ )))
17337 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
17338 (save-excursion
17339 (goto-char (match-end 0))
17340 (make-string (current-column) ?\ )))
17341 (t nil)))
17343 ;;; Other stuff.
17345 (defun org-toggle-fixed-width-section (arg)
17346 "Toggle the fixed-width export.
17347 If there is no active region, the QUOTE keyword at the current headline is
17348 inserted or removed. When present, it causes the text between this headline
17349 and the next to be exported as fixed-width text, and unmodified.
17350 If there is an active region, this command adds or removes a colon as the
17351 first character of this line. If the first character of a line is a colon,
17352 this line is also exported in fixed-width font."
17353 (interactive "P")
17354 (let* ((cc 0)
17355 (regionp (org-region-active-p))
17356 (beg (if regionp (region-beginning) (point)))
17357 (end (if regionp (region-end)))
17358 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17359 (case-fold-search nil)
17360 (re "[ \t]*\\(: \\)")
17361 off)
17362 (if regionp
17363 (save-excursion
17364 (goto-char beg)
17365 (setq cc (current-column))
17366 (beginning-of-line 1)
17367 (setq off (looking-at re))
17368 (while (> nlines 0)
17369 (setq nlines (1- nlines))
17370 (beginning-of-line 1)
17371 (cond
17372 (arg
17373 (org-move-to-column cc t)
17374 (insert ": \n")
17375 (forward-line -1))
17376 ((and off (looking-at re))
17377 (replace-match "" t t nil 1))
17378 ((not off) (org-move-to-column cc t) (insert ": ")))
17379 (forward-line 1)))
17380 (save-excursion
17381 (org-back-to-heading)
17382 (if (looking-at (concat outline-regexp
17383 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17384 (replace-match "" t t nil 1)
17385 (if (looking-at outline-regexp)
17386 (progn
17387 (goto-char (match-end 0))
17388 (insert org-quote-string " "))))))))
17390 (defun org-reftex-citation ()
17391 "Use reftex-citation to insert a citation into the buffer.
17392 This looks for a line like
17394 #+BIBLIOGRAPHY: foo plain option:-d
17396 and derives from it that foo.bib is the bibliography file relevant
17397 for this document. It then installs the necessary environment for RefTeX
17398 to work in this buffer and calls `reftex-citation' to insert a citation
17399 into the buffer.
17401 Export of such citations to both LaTeX and HTML is handled by the contributed
17402 package org-exp-bibtex by Taru Karttunen."
17403 (interactive)
17404 (let ((reftex-docstruct-symbol 'rds)
17405 (reftex-cite-format "\\cite{%l}")
17406 rds bib)
17407 (save-excursion
17408 (save-restriction
17409 (widen)
17410 (let ((case-fold-search t)
17411 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17412 (if (not (save-excursion
17413 (or (re-search-forward re nil t)
17414 (re-search-backward re nil t))))
17415 (error "No bibliography defined in file")
17416 (setq bib (concat (match-string 1) ".bib")
17417 rds (list (list 'bib bib)))))))
17418 (call-interactively 'reftex-citation)))
17420 ;;;; Functions extending outline functionality
17422 (defun org-beginning-of-line (&optional arg)
17423 "Go to the beginning of the current line. If that is invisible, continue
17424 to a visible line beginning. This makes the function of C-a more intuitive.
17425 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17426 first attempt, and only move to after the tags when the cursor is already
17427 beyond the end of the headline."
17428 (interactive "P")
17429 (let ((pos (point))
17430 (special (if (consp org-special-ctrl-a/e)
17431 (car org-special-ctrl-a/e)
17432 org-special-ctrl-a/e))
17433 refpos)
17434 (if (org-bound-and-true-p line-move-visual)
17435 (beginning-of-visual-line 1)
17436 (beginning-of-line 1))
17437 (if (and arg (fboundp 'move-beginning-of-line))
17438 (call-interactively 'move-beginning-of-line)
17439 (if (bobp)
17441 (backward-char 1)
17442 (if (org-invisible-p)
17443 (while (and (not (bobp)) (org-invisible-p))
17444 (backward-char 1)
17445 (beginning-of-line 1))
17446 (forward-char 1))))
17447 (when special
17448 (cond
17449 ((and (looking-at org-complex-heading-regexp)
17450 (= (char-after (match-end 1)) ?\ ))
17451 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17452 (point-at-eol)))
17453 (goto-char
17454 (if (eq special t)
17455 (cond ((> pos refpos) refpos)
17456 ((= pos (point)) refpos)
17457 (t (point)))
17458 (cond ((> pos (point)) (point))
17459 ((not (eq last-command this-command)) (point))
17460 (t refpos)))))
17461 ((org-at-item-p)
17462 (goto-char
17463 (if (eq special t)
17464 (cond ((> pos (match-end 4)) (match-end 4))
17465 ((= pos (point)) (match-end 4))
17466 (t (point)))
17467 (cond ((> pos (point)) (point))
17468 ((not (eq last-command this-command)) (point))
17469 (t (match-end 4))))))))
17470 (org-no-warnings
17471 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17473 (defun org-end-of-line (&optional arg)
17474 "Go to the end of the line.
17475 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17476 first attempt, and only move to after the tags when the cursor is already
17477 beyond the end of the headline."
17478 (interactive "P")
17479 (let ((special (if (consp org-special-ctrl-a/e)
17480 (cdr org-special-ctrl-a/e)
17481 org-special-ctrl-a/e)))
17482 (if (or (not special)
17483 (not (org-on-heading-p))
17484 arg)
17485 (call-interactively
17486 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17487 ((fboundp 'move-end-of-line) 'move-end-of-line)
17488 (t 'end-of-line)))
17489 (let ((pos (point)))
17490 (beginning-of-line 1)
17491 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17492 (if (eq special t)
17493 (if (or (< pos (match-beginning 1))
17494 (= pos (match-end 0)))
17495 (goto-char (match-beginning 1))
17496 (goto-char (match-end 0)))
17497 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17498 (goto-char (match-end 0))
17499 (goto-char (match-beginning 1))))
17500 (call-interactively (if (fboundp 'move-end-of-line)
17501 'move-end-of-line
17502 'end-of-line)))))
17503 (org-no-warnings
17504 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17506 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17507 (define-key org-mode-map "\C-e" 'org-end-of-line)
17508 (define-key org-mode-map [home] 'org-beginning-of-line)
17509 (define-key org-mode-map [end] 'org-end-of-line)
17511 (defun org-backward-sentence (&optional arg)
17512 "Go to beginning of sentence, or beginning of table field.
17513 This will call `backward-sentence' or `org-table-beginning-of-field',
17514 depending on context."
17515 (interactive "P")
17516 (cond
17517 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17518 (t (call-interactively 'backward-sentence))))
17520 (defun org-forward-sentence (&optional arg)
17521 "Go to end of sentence, or end of table field.
17522 This will call `forward-sentence' or `org-table-end-of-field',
17523 depending on context."
17524 (interactive "P")
17525 (cond
17526 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17527 (t (call-interactively 'forward-sentence))))
17529 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17530 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17532 (defun org-kill-line (&optional arg)
17533 "Kill line, to tags or end of line."
17534 (interactive "P")
17535 (cond
17536 ((or (not org-special-ctrl-k)
17537 (bolp)
17538 (not (org-on-heading-p)))
17539 (call-interactively 'kill-line))
17540 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17541 (kill-region (point) (match-beginning 1))
17542 (org-set-tags nil t))
17543 (t (kill-region (point) (point-at-eol)))))
17545 (define-key org-mode-map "\C-k" 'org-kill-line)
17547 (defun org-yank (&optional arg)
17548 "Yank. If the kill is a subtree, treat it specially.
17549 This command will look at the current kill and check if is a single
17550 subtree, or a series of subtrees[1]. If it passes the test, and if the
17551 cursor is at the beginning of a line or after the stars of a currently
17552 empty headline, then the yank is handled specially. How exactly depends
17553 on the value of the following variables, both set by default.
17555 org-yank-folded-subtrees
17556 When set, the subtree(s) will be folded after insertion, but only
17557 if doing so would now swallow text after the yanked text.
17559 org-yank-adjusted-subtrees
17560 When set, the subtree will be promoted or demoted in order to
17561 fit into the local outline tree structure, which means that the level
17562 will be adjusted so that it becomes the smaller one of the two
17563 *visible* surrounding headings.
17565 Any prefix to this command will cause `yank' to be called directly with
17566 no special treatment. In particular, a simple `C-u' prefix will just
17567 plainly yank the text as it is.
17569 \[1] The test checks if the first non-white line is a heading
17570 and if there are no other headings with fewer stars."
17571 (interactive "P")
17572 (org-yank-generic 'yank arg))
17574 (defun org-yank-generic (command arg)
17575 "Perform some yank-like command.
17577 This function implements the behavior described in the `org-yank'
17578 documentation. However, it has been generalized to work for any
17579 interactive command with similar behavior."
17581 ;; pretend to be command COMMAND
17582 (setq this-command command)
17584 (if arg
17585 (call-interactively command)
17587 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17588 (and (org-kill-is-subtree-p)
17589 (or (bolp)
17590 (and (looking-at "[ \t]*$")
17591 (string-match
17592 "\\`\\*+\\'"
17593 (buffer-substring (point-at-bol) (point)))))))
17594 swallowp)
17595 (cond
17596 ((and subtreep org-yank-folded-subtrees)
17597 (let ((beg (point))
17598 end)
17599 (if (and subtreep org-yank-adjusted-subtrees)
17600 (org-paste-subtree nil nil 'for-yank)
17601 (call-interactively command))
17603 (setq end (point))
17604 (goto-char beg)
17605 (when (and (bolp) subtreep
17606 (not (setq swallowp
17607 (org-yank-folding-would-swallow-text beg end))))
17608 (or (looking-at outline-regexp)
17609 (re-search-forward (concat "^" outline-regexp) end t))
17610 (while (and (< (point) end) (looking-at outline-regexp))
17611 (hide-subtree)
17612 (org-cycle-show-empty-lines 'folded)
17613 (condition-case nil
17614 (outline-forward-same-level 1)
17615 (error (goto-char end)))))
17616 (when swallowp
17617 (message
17618 "Inserted text not folded because that would swallow text"))
17620 (goto-char end)
17621 (skip-chars-forward " \t\n\r")
17622 (beginning-of-line 1)
17623 (push-mark beg 'nomsg)))
17624 ((and subtreep org-yank-adjusted-subtrees)
17625 (let ((beg (point-at-bol)))
17626 (org-paste-subtree nil nil 'for-yank)
17627 (push-mark beg 'nomsg)))
17629 (call-interactively command))))))
17631 (defun org-yank-folding-would-swallow-text (beg end)
17632 "Would hide-subtree at BEG swallow any text after END?"
17633 (let (level)
17634 (save-excursion
17635 (goto-char beg)
17636 (when (or (looking-at outline-regexp)
17637 (re-search-forward (concat "^" outline-regexp) end t))
17638 (setq level (org-outline-level)))
17639 (goto-char end)
17640 (skip-chars-forward " \t\r\n\v\f")
17641 (if (or (eobp)
17642 (and (bolp) (looking-at org-outline-regexp)
17643 (<= (org-outline-level) level)))
17644 nil ; Nothing would be swallowed
17645 t)))) ; something would swallow
17647 (define-key org-mode-map "\C-y" 'org-yank)
17649 (defun org-invisible-p ()
17650 "Check if point is at a character currently not visible."
17651 ;; Early versions of noutline don't have `outline-invisible-p'.
17652 (if (fboundp 'outline-invisible-p)
17653 (outline-invisible-p)
17654 (get-char-property (point) 'invisible)))
17656 (defun org-invisible-p2 ()
17657 "Check if point is at a character currently not visible."
17658 (save-excursion
17659 (if (and (eolp) (not (bobp))) (backward-char 1))
17660 ;; Early versions of noutline don't have `outline-invisible-p'.
17661 (if (fboundp 'outline-invisible-p)
17662 (outline-invisible-p)
17663 (get-char-property (point) 'invisible))))
17665 (defun org-back-to-heading (&optional invisible-ok)
17666 "Call `outline-back-to-heading', but provide a better error message."
17667 (condition-case nil
17668 (outline-back-to-heading invisible-ok)
17669 (error (error "Before first headline at position %d in buffer %s"
17670 (point) (current-buffer)))))
17672 (defun org-before-first-heading-p ()
17673 "Before first heading?"
17674 (save-excursion
17675 (null (re-search-backward "^\\*+ " nil t))))
17677 (defun org-on-heading-p (&optional ignored)
17678 (outline-on-heading-p t))
17679 (defun org-at-heading-p (&optional ignored)
17680 (outline-on-heading-p t))
17682 (defun org-at-heading-or-item-p ()
17683 (or (org-on-heading-p) (org-at-item-p)))
17685 (defun org-on-target-p ()
17686 (or (org-in-regexp org-radio-target-regexp)
17687 (org-in-regexp org-target-regexp)))
17689 (defun org-up-heading-all (arg)
17690 "Move to the heading line of which the present line is a subheading.
17691 This function considers both visible and invisible heading lines.
17692 With argument, move up ARG levels."
17693 (if (fboundp 'outline-up-heading-all)
17694 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17695 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17697 (defun org-up-heading-safe ()
17698 "Move to the heading line of which the present line is a subheading.
17699 This version will not throw an error. It will return the level of the
17700 headline found, or nil if no higher level is found.
17702 Also, this function will be a lot faster than `outline-up-heading',
17703 because it relies on stars being the outline starters. This can really
17704 make a significant difference in outlines with very many siblings."
17705 (let (start-level re)
17706 (org-back-to-heading t)
17707 (setq start-level (funcall outline-level))
17708 (if (equal start-level 1)
17710 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17711 (if (re-search-backward re nil t)
17712 (funcall outline-level)))))
17714 (defun org-first-sibling-p ()
17715 "Is this heading the first child of its parents?"
17716 (interactive)
17717 (let ((re (concat "^" outline-regexp))
17718 level l)
17719 (unless (org-at-heading-p t)
17720 (error "Not at a heading"))
17721 (setq level (funcall outline-level))
17722 (save-excursion
17723 (if (not (re-search-backward re nil t))
17725 (setq l (funcall outline-level))
17726 (< l level)))))
17728 (defun org-goto-sibling (&optional previous)
17729 "Goto the next sibling, even if it is invisible.
17730 When PREVIOUS is set, go to the previous sibling instead. Returns t
17731 when a sibling was found. When none is found, return nil and don't
17732 move point."
17733 (let ((fun (if previous 're-search-backward 're-search-forward))
17734 (pos (point))
17735 (re (concat "^" outline-regexp))
17736 level l)
17737 (when (condition-case nil (org-back-to-heading t) (error nil))
17738 (setq level (funcall outline-level))
17739 (catch 'exit
17740 (or previous (forward-char 1))
17741 (while (funcall fun re nil t)
17742 (setq l (funcall outline-level))
17743 (when (< l level) (goto-char pos) (throw 'exit nil))
17744 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17745 (goto-char pos)
17746 nil))))
17748 (defun org-show-siblings ()
17749 "Show all siblings of the current headline."
17750 (save-excursion
17751 (while (org-goto-sibling) (org-flag-heading nil)))
17752 (save-excursion
17753 (while (org-goto-sibling 'previous)
17754 (org-flag-heading nil))))
17756 (defun org-show-hidden-entry ()
17757 "Show an entry where even the heading is hidden."
17758 (save-excursion
17759 (org-show-entry)))
17761 (defun org-flag-heading (flag &optional entry)
17762 "Flag the current heading. FLAG non-nil means make invisible.
17763 When ENTRY is non-nil, show the entire entry."
17764 (save-excursion
17765 (org-back-to-heading t)
17766 ;; Check if we should show the entire entry
17767 (if entry
17768 (progn
17769 (org-show-entry)
17770 (save-excursion
17771 (and (outline-next-heading)
17772 (org-flag-heading nil))))
17773 (outline-flag-region (max (point-min) (1- (point)))
17774 (save-excursion (outline-end-of-heading) (point))
17775 flag))))
17777 (defun org-get-next-sibling ()
17778 "Move to next heading of the same level, and return point.
17779 If there is no such heading, return nil.
17780 This is like outline-next-sibling, but invisible headings are ok."
17781 (let ((level (funcall outline-level)))
17782 (outline-next-heading)
17783 (while (and (not (eobp)) (> (funcall outline-level) level))
17784 (outline-next-heading))
17785 (if (or (eobp) (< (funcall outline-level) level))
17787 (point))))
17789 (defun org-get-last-sibling ()
17790 "Move to previous heading of the same level, and return point.
17791 If there is no such heading, return nil."
17792 (let ((opoint (point))
17793 (level (funcall outline-level)))
17794 (outline-previous-heading)
17795 (when (and (/= (point) opoint) (outline-on-heading-p t))
17796 (while (and (> (funcall outline-level) level)
17797 (not (bobp)))
17798 (outline-previous-heading))
17799 (if (< (funcall outline-level) level)
17801 (point)))))
17803 (defun org-end-of-subtree (&optional invisible-OK to-heading)
17804 ;; This contains an exact copy of the original function, but it uses
17805 ;; `org-back-to-heading', to make it work also in invisible
17806 ;; trees. And is uses an invisible-OK argument.
17807 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17808 ;; Furthermore, when used inside Org, finding the end of a large subtree
17809 ;; with many children and grandchildren etc, this can be much faster
17810 ;; than the outline version.
17811 (org-back-to-heading invisible-OK)
17812 (let ((first t)
17813 (level (funcall outline-level)))
17814 (if (and (org-mode-p) (< level 1000))
17815 ;; A true heading (not a plain list item), in Org-mode
17816 ;; This means we can easily find the end by looking
17817 ;; only for the right number of stars. Using a regexp to do
17818 ;; this is so much faster than using a Lisp loop.
17819 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
17820 (forward-char 1)
17821 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
17822 ;; something else, do it the slow way
17823 (while (and (not (eobp))
17824 (or first (> (funcall outline-level) level)))
17825 (setq first nil)
17826 (outline-next-heading)))
17827 (unless to-heading
17828 (if (memq (preceding-char) '(?\n ?\^M))
17829 (progn
17830 ;; Go to end of line before heading
17831 (forward-char -1)
17832 (if (memq (preceding-char) '(?\n ?\^M))
17833 ;; leave blank line before heading
17834 (forward-char -1))))))
17835 (point))
17837 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
17838 "Use Org version in org-mode, for dramatic speed-up."
17839 (if (eq major-mode 'org-mode)
17840 (progn
17841 (org-end-of-subtree nil t)
17842 (unless (eobp) (backward-char 1)))
17843 ad-do-it))
17845 (defun org-forward-same-level (arg &optional invisible-ok)
17846 "Move forward to the arg'th subheading at same level as this one.
17847 Stop at the first and last subheadings of a superior heading."
17848 (interactive "p")
17849 (org-back-to-heading invisible-ok)
17850 (org-on-heading-p)
17851 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17852 (re (format "^\\*\\{1,%d\\} " level))
17854 (forward-char 1)
17855 (while (> arg 0)
17856 (while (and (re-search-forward re nil 'move)
17857 (setq l (- (match-end 0) (match-beginning 0) 1))
17858 (= l level)
17859 (not invisible-ok)
17860 (progn (backward-char 1) (org-invisible-p)))
17861 (if (< l level) (setq arg 1)))
17862 (setq arg (1- arg)))
17863 (beginning-of-line 1)))
17865 (defun org-backward-same-level (arg &optional invisible-ok)
17866 "Move backward to the arg'th subheading at same level as this one.
17867 Stop at the first and last subheadings of a superior heading."
17868 (interactive "p")
17869 (org-back-to-heading)
17870 (org-on-heading-p)
17871 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17872 (re (format "^\\*\\{1,%d\\} " level))
17874 (while (> arg 0)
17875 (while (and (re-search-backward re nil 'move)
17876 (setq l (- (match-end 0) (match-beginning 0) 1))
17877 (= l level)
17878 (not invisible-ok)
17879 (org-invisible-p))
17880 (if (< l level) (setq arg 1)))
17881 (setq arg (1- arg)))))
17883 (defun org-show-subtree ()
17884 "Show everything after this heading at deeper levels."
17885 (outline-flag-region
17886 (point)
17887 (save-excursion
17888 (org-end-of-subtree t t))
17889 nil))
17891 (defun org-show-entry ()
17892 "Show the body directly following this heading.
17893 Show the heading too, if it is currently invisible."
17894 (interactive)
17895 (save-excursion
17896 (condition-case nil
17897 (progn
17898 (org-back-to-heading t)
17899 (outline-flag-region
17900 (max (point-min) (1- (point)))
17901 (save-excursion
17902 (if (re-search-forward
17903 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17904 (match-beginning 1)
17905 (point-max)))
17906 nil)
17907 (org-cycle-hide-drawers 'children))
17908 (error nil))))
17910 (defun org-make-options-regexp (kwds &optional extra)
17911 "Make a regular expression for keyword lines."
17912 (concat
17914 "#?[ \t]*\\+\\("
17915 (mapconcat 'regexp-quote kwds "\\|")
17916 (if extra (concat "\\|" extra))
17917 "\\):[ \t]*"
17918 "\\(.*\\)"))
17920 ;; Make isearch reveal the necessary context
17921 (defun org-isearch-end ()
17922 "Reveal context after isearch exits."
17923 (when isearch-success ; only if search was successful
17924 (if (featurep 'xemacs)
17925 ;; Under XEmacs, the hook is run in the correct place,
17926 ;; we directly show the context.
17927 (org-show-context 'isearch)
17928 ;; In Emacs the hook runs *before* restoring the overlays.
17929 ;; So we have to use a one-time post-command-hook to do this.
17930 ;; (Emacs 22 has a special variable, see function `org-mode')
17931 (unless (and (boundp 'isearch-mode-end-hook-quit)
17932 isearch-mode-end-hook-quit)
17933 ;; Only when the isearch was not quitted.
17934 (org-add-hook 'post-command-hook 'org-isearch-post-command
17935 'append 'local)))))
17937 (defun org-isearch-post-command ()
17938 "Remove self from hook, and show context."
17939 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17940 (org-show-context 'isearch))
17943 ;;;; Integration with and fixes for other packages
17945 ;;; Imenu support
17947 (defvar org-imenu-markers nil
17948 "All markers currently used by Imenu.")
17949 (make-variable-buffer-local 'org-imenu-markers)
17951 (defun org-imenu-new-marker (&optional pos)
17952 "Return a new marker for use by Imenu, and remember the marker."
17953 (let ((m (make-marker)))
17954 (move-marker m (or pos (point)))
17955 (push m org-imenu-markers)
17958 (defun org-imenu-get-tree ()
17959 "Produce the index for Imenu."
17960 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17961 (setq org-imenu-markers nil)
17962 (let* ((n org-imenu-depth)
17963 (re (concat "^" outline-regexp))
17964 (subs (make-vector (1+ n) nil))
17965 (last-level 0)
17966 m level head)
17967 (save-excursion
17968 (save-restriction
17969 (widen)
17970 (goto-char (point-max))
17971 (while (re-search-backward re nil t)
17972 (setq level (org-reduced-level (funcall outline-level)))
17973 (when (<= level n)
17974 (looking-at org-complex-heading-regexp)
17975 (setq head (org-link-display-format
17976 (org-match-string-no-properties 4))
17977 m (org-imenu-new-marker))
17978 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17979 (if (>= level last-level)
17980 (push (cons head m) (aref subs level))
17981 (push (cons head (aref subs (1+ level))) (aref subs level))
17982 (loop for i from (1+ level) to n do (aset subs i nil)))
17983 (setq last-level level)))))
17984 (aref subs 1)))
17986 (eval-after-load "imenu"
17987 '(progn
17988 (add-hook 'imenu-after-jump-hook
17989 (lambda ()
17990 (if (eq major-mode 'org-mode)
17991 (org-show-context 'org-goto))))))
17993 (defun org-link-display-format (link)
17994 "Replace a link with either the description, or the link target
17995 if no description is present"
17996 (save-match-data
17997 (if (string-match org-bracket-link-analytic-regexp link)
17998 (replace-match (if (match-end 5)
17999 (match-string 5 link)
18000 (concat (match-string 1 link)
18001 (match-string 3 link)))
18002 nil t link)
18003 link)))
18005 ;; Speedbar support
18007 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
18008 "Overlay marking the agenda restriction line in speedbar.")
18009 (org-overlay-put org-speedbar-restriction-lock-overlay
18010 'face 'org-agenda-restriction-lock)
18011 (org-overlay-put org-speedbar-restriction-lock-overlay
18012 'help-echo "Agendas are currently limited to this item.")
18013 (org-detach-overlay org-speedbar-restriction-lock-overlay)
18015 (defun org-speedbar-set-agenda-restriction ()
18016 "Restrict future agenda commands to the location at point in speedbar.
18017 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
18018 (interactive)
18019 (require 'org-agenda)
18020 (let (p m tp np dir txt)
18021 (cond
18022 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18023 'org-imenu t))
18024 (setq m (get-text-property p 'org-imenu-marker))
18025 (with-current-buffer (marker-buffer m)
18026 (goto-char m)
18027 (org-agenda-set-restriction-lock 'subtree)))
18028 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18029 'speedbar-function 'speedbar-find-file))
18030 (setq tp (previous-single-property-change
18031 (1+ p) 'speedbar-function)
18032 np (next-single-property-change
18033 tp 'speedbar-function)
18034 dir (speedbar-line-directory)
18035 txt (buffer-substring-no-properties (or tp (point-min))
18036 (or np (point-max))))
18037 (with-current-buffer (find-file-noselect
18038 (let ((default-directory dir))
18039 (expand-file-name txt)))
18040 (unless (org-mode-p)
18041 (error "Cannot restrict to non-Org-mode file"))
18042 (org-agenda-set-restriction-lock 'file)))
18043 (t (error "Don't know how to restrict Org-mode's agenda")))
18044 (org-move-overlay org-speedbar-restriction-lock-overlay
18045 (point-at-bol) (point-at-eol))
18046 (setq current-prefix-arg nil)
18047 (org-agenda-maybe-redo)))
18049 (eval-after-load "speedbar"
18050 '(progn
18051 (speedbar-add-supported-extension ".org")
18052 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
18053 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
18054 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
18055 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18056 (add-hook 'speedbar-visiting-tag-hook
18057 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
18060 ;;; Fixes and Hacks for problems with other packages
18062 ;; Make flyspell not check words in links, to not mess up our keymap
18063 (defun org-mode-flyspell-verify ()
18064 "Don't let flyspell put overlays at active buttons."
18065 (and (not (get-text-property (point) 'keymap))
18066 (not (get-text-property (point) 'org-no-flyspell))))
18068 (defun org-remove-flyspell-overlays-in (beg end)
18069 "Remove flyspell overlays in region."
18070 (and (org-bound-and-true-p flyspell-mode)
18071 (fboundp 'flyspell-delete-region-overlays)
18072 (flyspell-delete-region-overlays beg end))
18073 (add-text-properties beg end '(org-no-flyspell t)))
18075 ;; Make `bookmark-jump' shows the jump location if it was hidden.
18076 (eval-after-load "bookmark"
18077 '(if (boundp 'bookmark-after-jump-hook)
18078 ;; We can use the hook
18079 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
18080 ;; Hook not available, use advice
18081 (defadvice bookmark-jump (after org-make-visible activate)
18082 "Make the position visible."
18083 (org-bookmark-jump-unhide))))
18085 ;; Make sure saveplace shows the location if it was hidden
18086 (eval-after-load "saveplace"
18087 '(defadvice save-place-find-file-hook (after org-make-visible activate)
18088 "Make the position visible."
18089 (org-bookmark-jump-unhide)))
18091 ;; Make sure ecb shows the location if it was hidden
18092 (eval-after-load "ecb"
18093 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
18094 "Make hierarchy visible when jumping into location from ECB tree buffer."
18095 (if (eq major-mode 'org-mode)
18096 (org-show-context))))
18098 (defun org-bookmark-jump-unhide ()
18099 "Unhide the current position, to show the bookmark location."
18100 (and (org-mode-p)
18101 (or (org-invisible-p)
18102 (save-excursion (goto-char (max (point-min) (1- (point))))
18103 (org-invisible-p)))
18104 (org-show-context 'bookmark-jump)))
18106 ;; Make session.el ignore our circular variable
18107 (eval-after-load "session"
18108 '(add-to-list 'session-globals-exclude 'org-mark-ring))
18110 ;;;; Experimental code
18112 (defun org-closed-in-range ()
18113 "Sparse tree of items closed in a certain time range.
18114 Still experimental, may disappear in the future."
18115 (interactive)
18116 ;; Get the time interval from the user.
18117 (let* ((time1 (org-float-time
18118 (org-read-date nil 'to-time nil "Starting date: ")))
18119 (time2 (org-float-time
18120 (org-read-date nil 'to-time nil "End date:")))
18121 ;; callback function
18122 (callback (lambda ()
18123 (let ((time
18124 (org-float-time
18125 (apply 'encode-time
18126 (org-parse-time-string
18127 (match-string 1))))))
18128 ;; check if time in interval
18129 (and (>= time time1) (<= time time2))))))
18130 ;; make tree, check each match with the callback
18131 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
18133 ;;;; Finish up
18135 (provide 'org)
18137 (run-hooks 'org-load-hook)
18139 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
18141 ;;; org.el ends here