Intermediate state, I am just trying comiting now.
[org-mode.git] / EXPERIMENTAL / interactive-query / org.el.orig
blob276854ad59c5a7dfcfff7640e6df698a89c6415c
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 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 5.18a
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text.  Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured.  Visibility cycling and structure editing
37 ;; help to work with the tree.  Tables are easily created with a built-in
38 ;; table editor.  Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling.  It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects.  For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file.  It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;;   http://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file.  The
57 ;; distribution also contains a PDF version of it.  At the homepage of
58 ;; Org-mode, you can read the same text online as HTML.  There is also an
59 ;; excellent reference card made by Philip Rooke.  This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; A list of recent changes can be found at
63 ;; http://orgmode.org/Changes.html
65 ;;; Code:
67 ;;;; Require other packages
69 (eval-when-compile
70   (require 'cl)
71   (require 'gnus-sum)
72   (require 'calendar))
73 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
74 ;; the file noutline.el being loaded.
75 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
76 ;; We require noutline, which might be provided in outline.el
77 (require 'outline) (require 'noutline)
78 ;; Other stuff we need.
79 (require 'time-date)
80 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
81 (require 'easymenu)
83 ;;;; Customization variables
85 ;;; Version
87 (defconst org-version "5.17a"
88   "The version number of the file org.el.")
89 (defun org-version ()
90   (interactive)
91   (message "Org-mode version %s" org-version))
93 ;;; Compatibility constants
94 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
95 (defconst org-format-transports-properties-p
96   (let ((x "a"))
97     (add-text-properties 0 1 '(test t) x)
98     (get-text-property 0 'test (format "%s" x)))
99   "Does format transport text properties?")
101 (defmacro org-bound-and-true-p (var)
102   "Return the value of symbol VAR if it is bound, else nil."
103   `(and (boundp (quote ,var)) ,var))
105 (defmacro org-unmodified (&rest body)
106   "Execute body without changing buffer-modified-p."
107   `(set-buffer-modified-p
108     (prog1 (buffer-modified-p) ,@body)))
110 (defmacro org-re (s)
111   "Replace posix classes in regular expression."
112   (if (featurep 'xemacs)
113       (let ((ss s))
114         (save-match-data
115           (while (string-match "\\[:alnum:\\]" ss)
116             (setq ss (replace-match "a-zA-Z0-9" t t ss)))
117           (while (string-match "\\[:alpha:\\]" ss)
118             (setq ss (replace-match "a-zA-Z" t t ss)))
119           ss))
120     s))
122 (defmacro org-preserve-lc (&rest body)
123   `(let ((_line (org-current-line))
124          (_col (current-column)))
125      (unwind-protect
126          (progn ,@body)
127        (goto-line _line)
128        (move-to-column _col))))
130 (defmacro org-without-partial-completion (&rest body)
131   `(let ((pc-mode (and (boundp 'partial-completion-mode)
132                        partial-completion-mode)))
133      (unwind-protect
134          (progn
135            (if pc-mode (partial-completion-mode -1))
136            ,@body)
137        (if pc-mode (partial-completion-mode 1)))))
139 ;;; The custom variables
141 (defgroup org nil
142   "Outline-based notes management and organizer."
143   :tag "Org"
144   :group 'outlines
145   :group 'hypermedia
146   :group 'calendar)
148 ;; FIXME: Needs a separate group...
149 (defcustom org-completion-fallback-command 'hippie-expand
150   "The expansion command called by \\[org-complete] in normal context.
151 Normal means, no org-mode-specific context."
152   :group 'org
153   :type 'function)
155 (defgroup org-startup nil
156   "Options concerning startup of Org-mode."
157   :tag "Org Startup"
158   :group 'org)
160 (defcustom org-startup-folded t
161   "Non-nil means, entering Org-mode will switch to OVERVIEW.
162 This can also be configured on a per-file basis by adding one of
163 the following lines anywhere in the buffer:
165    #+STARTUP: fold
166    #+STARTUP: nofold
167    #+STARTUP: content"
168   :group 'org-startup
169   :type '(choice
170           (const :tag "nofold: show all" nil)
171           (const :tag "fold: overview" t)
172           (const :tag "content: all headlines" content)))
174 (defcustom org-startup-truncated t
175   "Non-nil means, entering Org-mode will set `truncate-lines'.
176 This is useful since some lines containing links can be very long and
177 uninteresting.  Also tables look terrible when wrapped."
178   :group 'org-startup
179   :type 'boolean)
181 (defcustom org-startup-align-all-tables nil
182   "Non-nil means, align all tables when visiting a file.
183 This is useful when the column width in tables is forced with <N> cookies
184 in table fields.  Such tables will look correct only after the first re-align.
185 This can also be configured on a per-file basis by adding one of
186 the following lines anywhere in the buffer:
187    #+STARTUP: align
188    #+STARTUP: noalign"
189   :group 'org-startup
190   :type 'boolean)
192 (defcustom org-insert-mode-line-in-empty-file nil
193   "Non-nil means insert the first line setting Org-mode in empty files.
194 When the function `org-mode' is called interactively in an empty file, this
195 normally means that the file name does not automatically trigger Org-mode.
196 To ensure that the file will always be in Org-mode in the future, a
197 line enforcing Org-mode will be inserted into the buffer, if this option
198 has been set."
199   :group 'org-startup
200   :type 'boolean)
202 (defcustom org-replace-disputed-keys nil
203   "Non-nil means use alternative key bindings for some keys.
204 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
205 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
206 If you want to use Org-mode together with one of these other modes,
207 or more generally if you would like to move some Org-mode commands to
208 other keys, set this variable and configure the keys with the variable
209 `org-disputed-keys'.
211 This option is only relevant at load-time of Org-mode, and must be set
212 *before* org.el is loaded.  Changing it requires a restart of Emacs to
213 become effective."
214   :group 'org-startup
215   :type 'boolean)
217 (if (fboundp 'defvaralias)
218     (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
220 (defcustom org-disputed-keys
221   '(([(shift up)]               . [(meta p)])
222     ([(shift down)]             . [(meta n)])
223     ([(shift left)]             . [(meta -)])
224     ([(shift right)]            . [(meta +)])
225     ([(control shift right)]    . [(meta shift +)])
226     ([(control shift left)]     . [(meta shift -)]))
227   "Keys for which Org-mode and other modes compete.
228 This is an alist, cars are the default keys, second element specifies
229 the alternative to use when `org-replace-disputed-keys' is t.
231 Keys can be specified in any syntax supported by `define-key'.
232 The value of this option takes effect only at Org-mode's startup,
233 therefore you'll have to restart Emacs to apply it after changing."
234   :group 'org-startup
235   :type 'alist)
237 (defun org-key (key)
238   "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
239 Or return the original if not disputed."
240   (if org-replace-disputed-keys
241       (let* ((nkey (key-description key))
242              (x (org-find-if (lambda (x)
243                                (equal (key-description (car x)) nkey))
244                              org-disputed-keys)))
245         (if x (cdr x) key))
246     key))
248 (defun org-find-if (predicate seq)
249   (catch 'exit
250     (while seq
251       (if (funcall predicate (car seq))
252           (throw 'exit (car seq))
253         (pop seq)))))
255 (defun org-defkey (keymap key def)
256   "Define a key, possibly translated, as returned by `org-key'."
257   (define-key keymap (org-key key) def))
259 (defcustom org-ellipsis nil
260   "The ellipsis to use in the Org-mode outline.
261 When nil, just use the standard three dots.  When a string, use that instead,
262 When a face, use the standart 3 dots, but with the specified face.
263 The change affects only Org-mode (which will then use its own display table).
264 Changing this requires executing `M-x org-mode' in a buffer to become
265 effective."
266   :group 'org-startup
267   :type '(choice (const :tag "Default" nil)
268                  (face :tag "Face" :value org-warning)
269                  (string :tag "String" :value "...#")))
271 (defvar org-display-table nil
272   "The display table for org-mode, in case `org-ellipsis' is non-nil.")
274 (defgroup org-keywords nil
275   "Keywords in Org-mode."
276   :tag "Org Keywords"
277   :group 'org)
279 (defcustom org-deadline-string "DEADLINE:"
280   "String to mark deadline entries.
281 A deadline is this string, followed by a time stamp.  Should be a word,
282 terminated by a colon.  You can insert a schedule keyword and
283 a timestamp with \\[org-deadline].
284 Changes become only effective after restarting Emacs."
285   :group 'org-keywords
286   :type 'string)
288 (defcustom org-scheduled-string "SCHEDULED:"
289   "String to mark scheduled TODO entries.
290 A schedule is this string, followed by a time stamp.  Should be a word,
291 terminated by a colon.  You can insert a schedule keyword and
292 a timestamp with \\[org-schedule].
293 Changes become only effective after restarting Emacs."
294   :group 'org-keywords
295   :type 'string)
297 (defcustom org-closed-string "CLOSED:"
298   "String used as the prefix for timestamps logging closing a TODO entry."
299   :group 'org-keywords
300   :type 'string)
302 (defcustom org-clock-string "CLOCK:"
303   "String used as prefix for timestamps clocking work hours on an item."
304   :group 'org-keywords
305   :type 'string)
307 (defcustom org-comment-string "COMMENT"
308   "Entries starting with this keyword will never be exported.
309 An entry can be toggled between COMMENT and normal with
310 \\[org-toggle-comment].
311 Changes become only effective after restarting Emacs."
312   :group 'org-keywords
313   :type 'string)
315 (defcustom org-quote-string "QUOTE"
316   "Entries starting with this keyword will be exported in fixed-width font.
317 Quoting applies only to the text in the entry following the headline, and does
318 not extend beyond the next headline, even if that is lower level.
319 An entry can be toggled between QUOTE and normal with
320 \\[org-toggle-fixed-width-section]."
321   :group 'org-keywords
322   :type 'string)
324 (defconst org-repeat-re
325   (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
326           " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
327   "Regular expression for specifying repeated events.
328 After a match, group 1 contains the repeat expression.")
330 (defgroup org-structure nil
331   "Options concerning the general structure of Org-mode files."
332   :tag "Org Structure"
333   :group 'org)
335 (defgroup org-reveal-location nil
336   "Options about how to make context of a location visible."
337   :tag "Org Reveal Location"
338   :group 'org-structure)
340 (defconst org-context-choice
341   '(choice
342     (const :tag "Always" t)
343     (const :tag "Never" nil)
344     (repeat :greedy t :tag "Individual contexts"
345             (cons
346              (choice :tag "Context"
347                      (const agenda)
348                      (const org-goto)
349                      (const occur-tree)
350                      (const tags-tree)
351                      (const link-search)
352                      (const mark-goto)
353                      (const bookmark-jump)
354                      (const isearch)
355                      (const default))
356              (boolean))))
357   "Contexts for the reveal options.")
359 (defcustom org-show-hierarchy-above '((default . t))
360   "Non-nil means, show full hierarchy when revealing a location.
361 Org-mode often shows locations in an org-mode file which might have
362 been invisible before.  When this is set, the hierarchy of headings
363 above the exposed location is shown.
364 Turning this off for example for sparse trees makes them very compact.
365 Instead of t, this can also be an alist specifying this option for different
366 contexts.  Valid contexts are
367   agenda         when exposing an entry from the agenda
368   org-goto       when using the command `org-goto' on key C-c C-j
369   occur-tree     when using the command `org-occur' on key C-c /
370   tags-tree      when constructing a sparse tree based on tags matches
371   link-search    when exposing search matches associated with a link
372   mark-goto      when exposing the jump goal of a mark
373   bookmark-jump  when exposing a bookmark location
374   isearch        when exiting from an incremental search
375   default        default for all contexts not set explicitly"
376   :group 'org-reveal-location
377   :type org-context-choice)
379 (defcustom org-show-following-heading '((default . nil))
380   "Non-nil means, show following heading when revealing a location.
381 Org-mode often shows locations in an org-mode file which might have
382 been invisible before.  When this is set, the heading following the
383 match is shown.
384 Turning this off for example for sparse trees makes them very compact,
385 but makes it harder to edit the location of the match.  In such a case,
386 use the command \\[org-reveal] to show more context.
387 Instead of t, this can also be an alist specifying this option for different
388 contexts.  See `org-show-hierarchy-above' for valid contexts."
389   :group 'org-reveal-location
390   :type org-context-choice)
392 (defcustom org-show-siblings '((default . nil) (isearch t))
393   "Non-nil means, show all sibling heading when revealing a location.
394 Org-mode often shows locations in an org-mode file which might have
395 been invisible before.  When this is set, the sibling of the current entry
396 heading are all made visible.  If `org-show-hierarchy-above' is t,
397 the same happens on each level of the hierarchy above the current entry.
399 By default this is on for the isearch context, off for all other contexts.
400 Turning this off for example for sparse trees makes them very compact,
401 but makes it harder to edit the location of the match.  In such a case,
402 use the command \\[org-reveal] to show more context.
403 Instead of t, this can also be an alist specifying this option for different
404 contexts.  See `org-show-hierarchy-above' for valid contexts."
405   :group 'org-reveal-location
406   :type org-context-choice)
408 (defcustom org-show-entry-below '((default . nil))
409   "Non-nil means, show the entry below a headline when revealing a location.
410 Org-mode often shows locations in an org-mode file which might have
411 been invisible before.  When this is set, the text below the headline that is
412 exposed is also shown.
414 By default this is off for all contexts.
415 Instead of t, this can also be an alist specifying this option for different
416 contexts.  See `org-show-hierarchy-above' for valid contexts."
417   :group 'org-reveal-location
418   :type org-context-choice)
420 (defgroup org-cycle nil
421   "Options concerning visibility cycling in Org-mode."
422   :tag "Org Cycle"
423   :group 'org-structure)
425 (defcustom org-drawers '("PROPERTIES" "CLOCK")
426   "Names of drawers.  Drawers are not opened by cycling on the headline above.
427 Drawers only open with a TAB on the drawer line itself.  A drawer looks like
428 this:
429    :DRAWERNAME:
430    .....
431    :END:
432 The drawer \"PROPERTIES\" is special for capturing properties through
433 the property API.
435 Drawers can be defined on the per-file basis with a line like:
437 #+DRAWERS: HIDDEN STATE PROPERTIES"
438   :group 'org-structure
439   :type '(repeat (string :tag "Drawer Name")))
441 (defcustom org-cycle-global-at-bob nil
442   "Cycle globally if cursor is at beginning of buffer and not at a headline.
443 This makes it possible to do global cycling without having to use S-TAB or
444 C-u TAB.  For this special case to work, the first line of the buffer
445 must not be a headline - it may be empty ot some other text.  When used in
446 this way, `org-cycle-hook' is disables temporarily, to make sure the
447 cursor stays at the beginning of the buffer.
448 When this option is nil, don't do anything special at the beginning
449 of the buffer."
450   :group 'org-cycle
451   :type 'boolean)
453 (defcustom org-cycle-emulate-tab t
454   "Where should `org-cycle' emulate TAB.
455 nil         Never
456 white       Only in completely white lines
457 whitestart  Only at the beginning of lines, before the first non-white char.
458 t           Everywhere except in headlines
459 exc-hl-bol  Everywhere except at the start of a headline
460 If TAB is used in a place where it does not emulate TAB, the current subtree
461 visibility is cycled."
462   :group 'org-cycle
463   :type '(choice (const :tag "Never" nil)
464                  (const :tag "Only in completely white lines" white)
465                  (const :tag "Before first char in a line" whitestart)
466                  (const :tag "Everywhere except in headlines" t)
467                  (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
468                  ))
470 (defcustom org-cycle-separator-lines 2
471   "Number of empty lines needed to keep an empty line between collapsed trees.
472 If you leave an empty line between the end of a subtree and the following
473 headline, this empty line is hidden when the subtree is folded.
474 Org-mode will leave (exactly) one empty line visible if the number of
475 empty lines is equal or larger to the number given in this variable.
476 So the default 2 means, at least 2 empty lines after the end of a subtree
477 are needed to produce free space between a collapsed subtree and the
478 following headline.
480 Special case: when 0, never leave empty lines in collapsed view."
481   :group 'org-cycle
482   :type 'integer)
484 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
485                             org-cycle-hide-drawers
486                             org-cycle-show-empty-lines
487                             org-optimize-window-after-visibility-change)
488   "Hook that is run after `org-cycle' has changed the buffer visibility.
489 The function(s) in this hook must accept a single argument which indicates
490 the new state that was set by the most recent `org-cycle' command.  The
491 argument is a symbol.  After a global state change, it can have the values
492 `overview', `content', or `all'.  After a local state change, it can have
493 the values `folded', `children', or `subtree'."
494   :group 'org-cycle
495   :type 'hook)
497 (defgroup org-edit-structure nil
498   "Options concerning structure editing in Org-mode."
499   :tag "Org Edit Structure"
500   :group 'org-structure)
502 (defcustom org-special-ctrl-a/e nil
503   "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
504 When t, `C-a' will bring back the cursor to the beginning of the
505 headline text, i.e. after the stars and after a possible TODO keyword.
506 In an item, this will be the position after the bullet.
507 When the cursor is already at that position, another `C-a' will bring
508 it to the beginning of the line.
509 `C-e' will jump to the end of the headline, ignoring the presence of tags
510 in the headline.  A second `C-e' will then jump to the true end of the
511 line, after any tags.
512 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
513 and only a directly following, identical keypress will bring the cursor
514 to the special positions."
515   :group 'org-edit-structure
516   :type '(choice
517           (const :tag "off" nil)
518           (const :tag "after bullet first" t)
519           (const :tag "border first" reversed)))
521 (if (fboundp 'defvaralias)
522     (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
524 (defcustom org-odd-levels-only nil
525   "Non-nil means, skip even levels and only use odd levels for the outline.
526 This has the effect that two stars are being added/taken away in
527 promotion/demotion commands.  It also influences how levels are
528 handled by the exporters.
529 Changing it requires restart of `font-lock-mode' to become effective
530 for fontification also in regions already fontified.
531 You may also set this on a per-file basis by adding one of the following
532 lines to the buffer:
534    #+STARTUP: odd
535    #+STARTUP: oddeven"
536   :group 'org-edit-structure
537   :group 'org-font-lock
538   :type 'boolean)
540 (defcustom org-adapt-indentation t
541   "Non-nil means, adapt indentation when promoting and demoting.
542 When this is set and the *entire* text in an entry is indented, the
543 indentation is increased by one space in a demotion command, and
544 decreased by one in a promotion command.  If any line in the entry
545 body starts at column 0, indentation is not changed at all."
546   :group 'org-edit-structure
547   :type 'boolean)
549 (defcustom org-blank-before-new-entry '((heading . nil)
550                                         (plain-list-item . nil))
551   "Should `org-insert-heading' leave a blank line before new heading/item?
552 The value is an alist, with `heading' and `plain-list-item' as car,
553 and a boolean flag as cdr."
554   :group 'org-edit-structure
555   :type '(list
556           (cons (const heading) (boolean))
557           (cons (const plain-list-item) (boolean))))
559 (defcustom org-insert-heading-hook nil
560   "Hook being run after inserting a new heading."
561   :group 'org-edit-structure
562   :type 'hook)
564 (defcustom org-enable-fixed-width-editor t
565   "Non-nil means, lines starting with \":\" are treated as fixed-width.
566 This currently only means, they are never auto-wrapped.
567 When nil, such lines will be treated like ordinary lines.
568 See also the QUOTE keyword."
569   :group 'org-edit-structure
570   :type 'boolean)
572 (defgroup org-sparse-trees nil
573   "Options concerning sparse trees in Org-mode."
574   :tag "Org Sparse Trees"
575   :group 'org-structure)
577 (defcustom org-highlight-sparse-tree-matches t
578   "Non-nil means, highlight all matches that define a sparse tree.
579 The highlights will automatically disappear the next time the buffer is
580 changed by an edit command."
581   :group 'org-sparse-trees
582   :type 'boolean)
584 (defcustom org-remove-highlights-with-change t
585   "Non-nil means, any change to the buffer will remove temporary highlights.
586 Such highlights are created by `org-occur' and `org-clock-display'.
587 When nil, `C-c C-c needs to be used to get rid of the highlights.
588 The highlights created by `org-preview-latex-fragment' always need
589 `C-c C-c' to be removed."
590   :group 'org-sparse-trees
591   :group 'org-time
592   :type 'boolean)
595 (defcustom org-occur-hook '(org-first-headline-recenter)
596   "Hook that is run after `org-occur' has constructed a sparse tree.
597 This can be used to recenter the window to show as much of the structure
598 as possible."
599   :group 'org-sparse-trees
600   :type 'hook)
602 (defgroup org-plain-lists nil
603   "Options concerning plain lists in Org-mode."
604   :tag "Org Plain lists"
605   :group 'org-structure)
607 (defcustom org-cycle-include-plain-lists nil
608   "Non-nil means, include plain lists into visibility cycling.
609 This means that during cycling, plain list items will *temporarily* be
610 interpreted as outline headlines with a level given by 1000+i where i is the
611 indentation of the bullet.  In all other operations, plain list items are
612 not seen as headlines.  For example, you cannot assign a TODO keyword to
613 such an item."
614   :group 'org-plain-lists
615   :type 'boolean)
617 (defcustom org-plain-list-ordered-item-terminator t
618   "The character that makes a line with leading number an ordered list item.
619 Valid values are ?. and ?\).  To get both terminators, use t.  While
620 ?. may look nicer, it creates the danger that a line with leading
621 number may be incorrectly interpreted as an item.  ?\) therefore is
622 the safe choice."
623   :group 'org-plain-lists
624   :type '(choice (const :tag "dot like in \"2.\"" ?.)
625                  (const :tag "paren like in \"2)\"" ?\))
626                  (const :tab "both" t)))
628 (defcustom org-auto-renumber-ordered-lists t
629   "Non-nil means, automatically renumber ordered plain lists.
630 Renumbering happens when the sequence have been changed with
631 \\[org-shiftmetaup] or \\[org-shiftmetadown].  After other editing commands,
632 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
633   :group 'org-plain-lists
634   :type 'boolean)
636 (defcustom org-provide-checkbox-statistics t
637   "Non-nil means, update checkbox statistics after insert and toggle.
638 When this is set, checkbox statistics is updated each time you either insert
639 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
640 with \\[org-ctrl-c-ctrl-c\\]."
641   :group 'org-plain-lists
642   :type 'boolean)
644 (defgroup org-archive nil
645   "Options concerning archiving in Org-mode."
646   :tag "Org Archive"
647   :group 'org-structure)
649 (defcustom org-archive-tag "ARCHIVE"
650   "The tag that marks a subtree as archived.
651 An archived subtree does not open during visibility cycling, and does
652 not contribute to the agenda listings.
653 After changing this, font-lock must be restarted in the relevant buffers to
654 get the proper fontification."
655   :group 'org-archive
656   :group 'org-keywords
657   :type 'string)
659 (defcustom org-agenda-skip-archived-trees t
660   "Non-nil means, the agenda will skip any items located in archived trees.
661 An archived tree is a tree marked with the tag ARCHIVE."
662   :group 'org-archive
663   :group 'org-agenda-skip
664   :type 'boolean)
666 (defcustom org-cycle-open-archived-trees nil
667   "Non-nil means, `org-cycle' will open archived trees.
668 An archived tree is a tree marked with the tag ARCHIVE.
669 When nil, archived trees will stay folded.  You can still open them with
670 normal outline commands like `show-all', but not with the cycling commands."
671   :group 'org-archive
672   :group 'org-cycle
673   :type 'boolean)
675 (defcustom org-sparse-tree-open-archived-trees nil
676   "Non-nil means sparse tree construction shows matches in archived trees.
677 When nil, matches in these trees are highlighted, but the trees are kept in
678 collapsed state."
679   :group 'org-archive
680   :group 'org-sparse-trees
681   :type 'boolean)
683 (defcustom org-archive-location "%s_archive::"
684   "The location where subtrees should be archived.
685 This string consists of two parts, separated by a double-colon.
687 The first part is a file name - when omitted, archiving happens in the same
688 file.  %s will be replaced by the current file name (without directory part).
689 Archiving to a different file is useful to keep archived entries from
690 contributing to the Org-mode Agenda.
692 The part after the double colon is a headline.  The archived entries will be
693 filed under that headline.  When omitted, the subtrees are simply filed away
694 at the end of the file, as top-level entries.
696 Here are a few examples:
697 \"%s_archive::\"
698         If the current file is Projects.org, archive in file
699         Projects.org_archive, as top-level trees.  This is the default.
701 \"::* Archived Tasks\"
702         Archive in the current file, under the top-level headline
703         \"* Archived Tasks\".
705 \"~/org/archive.org::\"
706         Archive in file ~/org/archive.org (absolute path), as top-level trees.
708 \"basement::** Finished Tasks\"
709         Archive in file ./basement (relative path), as level 3 trees
710         below the level 2 heading \"** Finished Tasks\".
712 You may set this option on a per-file basis by adding to the buffer a
713 line like
715 #+ARCHIVE: basement::** Finished Tasks"
716   :group 'org-archive
717   :type 'string)
719 (defcustom org-archive-mark-done t
720   "Non-nil means, mark entries as DONE when they are moved to the archive file.
721 This can be a string to set the keyword to use.  When t, Org-mode will
722 use the first keyword in its list that means done."
723   :group 'org-archive
724   :type '(choice
725           (const :tag "No" nil)
726           (const :tag "Yes" t)
727           (string :tag "Use this keyword")))
729 (defcustom org-archive-stamp-time t
730   "Non-nil means, add a time stamp to entries moved to an archive file.
731 This variable is obsolete and has no effect anymore, instead add ot remove
732 `time' from the variablle `org-archive-save-context-info'."
733   :group 'org-archive
734   :type 'boolean)
736 (defcustom org-archive-save-context-info '(time file category todo itags)
737   "Parts of context info that should be stored as properties when archiving.
738 When a subtree is moved to an archive file, it looses information given by
739 context, like inherited tags, the category, and possibly also the TODO
740 state (depending on the variable `org-archive-mark-done').
741 This variable can be a list of any of the following symbols:
743 time       The time of archiving.
744 file       The file where the entry originates.
745 itags      The local tags, in the headline of the subtree.
746 ltags      The tags the subtree inherits from further up the hierarchy.
747 todo       The pre-archive TODO state.
748 category   The category, taken from file name or #+CATEGORY lines.
750 For each symbol present in the list, a property will be created in
751 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
752 information."
753   :group 'org-archive
754   :type '(set :greedy t
755           (const :tag "Time" time)
756           (const :tag "File" file)
757           (const :tag "Category" category)
758           (const :tag "TODO state" todo)
759           (const :tag "TODO state" priority)
760           (const :tag "Inherited tags" itags)
761           (const :tag "Local tags" ltags)))
763 (defgroup org-imenu-and-speedbar nil
764   "Options concerning imenu and speedbar in Org-mode."
765   :tag "Org Imenu and Speedbar"
766   :group 'org-structure)
768 (defcustom org-imenu-depth 2
769   "The maximum level for Imenu access to Org-mode headlines.
770 This also applied for speedbar access."
771   :group 'org-imenu-and-speedbar
772   :type 'number)
774 (defgroup org-table nil
775   "Options concerning tables in Org-mode."
776   :tag "Org Table"
777   :group 'org)
779 (defcustom org-enable-table-editor 'optimized
780   "Non-nil means, lines starting with \"|\" are handled by the table editor.
781 When nil, such lines will be treated like ordinary lines.
783 When equal to the symbol `optimized', the table editor will be optimized to
784 do the following:
785 - Automatic overwrite mode in front of whitespace in table fields.
786   This makes the structure of the table stay in tact as long as the edited
787   field does not exceed the column width.
788 - Minimize the number of realigns.  Normally, the table is aligned each time
789   TAB or RET are pressed to move to another field.  With optimization this
790   happens only if changes to a field might have changed the column width.
791 Optimization requires replacing the functions `self-insert-command',
792 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
793 slight (in fact: unnoticeable) speed impact for normal typing.  Org-mode is
794 very good at guessing when a re-align will be necessary, but you can always
795 force one with \\[org-ctrl-c-ctrl-c].
797 If you would like to use the optimized version in Org-mode, but the
798 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
800 This variable can be used to turn on and off the table editor during a session,
801 but in order to toggle optimization, a restart is required.
803 See also the variable `org-table-auto-blank-field'."
804   :group 'org-table
805   :type '(choice
806           (const :tag "off" nil)
807           (const :tag "on" t)
808           (const :tag "on, optimized" optimized)))
810 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
811   "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
812 In the optimized version, the table editor takes over all simple keys that
813 normally just insert a character.  In tables, the characters are inserted
814 in a way to minimize disturbing the table structure (i.e. in overwrite mode
815 for empty fields).  Outside tables, the correct binding of the keys is
816 restored.
818 The default for this option is t if the optimized version is also used in
819 Org-mode.  See the variable `org-enable-table-editor' for details.  Changing
820 this variable requires a restart of Emacs to become effective."
821   :group 'org-table
822   :type 'boolean)
824 (defcustom orgtbl-radio-table-templates
825   '((latex-mode "% BEGIN RECEIVE ORGTBL %n
826 % END RECEIVE ORGTBL %n
827 \\begin{comment}
828 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
829 | | |
830 \\end{comment}\n")
831     (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
832 @c END RECEIVE ORGTBL %n
833 @ignore
834 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
835 | | |
836 @end ignore\n")
837     (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
838 <!-- END RECEIVE ORGTBL %n -->
839 <!--
840 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
841 | | |
842 -->\n"))
843   "Templates for radio tables in different major modes.
844 All occurrences of %n in a template will be replaced with the name of the
845 table, obtained by prompting the user."
846   :group 'org-table
847   :type '(repeat
848           (list (symbol :tag "Major mode")
849                 (string :tag "Format"))))
851 (defgroup org-table-settings nil
852   "Settings for tables in Org-mode."
853   :tag "Org Table Settings"
854   :group 'org-table)
856 (defcustom org-table-default-size "5x2"
857   "The default size for newly created tables, Columns x Rows."
858   :group 'org-table-settings
859    :type 'string)
861 (defcustom org-table-number-regexp
862   "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
863   "Regular expression for recognizing numbers in table columns.
864 If a table column contains mostly numbers, it will be aligned to the
865 right.  If not, it will be aligned to the left.
867 The default value of this option is a regular expression which allows
868 anything which looks remotely like a number as used in scientific
869 context.  For example, all of the following will be considered a
870 number:
871     12    12.2    2.4e-08    2x10^12    4.034+-0.02    2.7(10)  >3.5
873 Other options offered by the customize interface are more restrictive."
874   :group 'org-table-settings
875   :type '(choice
876           (const :tag "Positive Integers"
877                  "^[0-9]+$")
878           (const :tag "Integers"
879                  "^[-+]?[0-9]+$")
880           (const :tag "Floating Point Numbers"
881                  "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
882           (const :tag "Floating Point Number or Integer"
883                  "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
884           (const :tag "Exponential, Floating point, Integer"
885                  "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
886           (const :tag "Very General Number-Like, including hex"
887                  "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
888           (string :tag "Regexp:")))
890 (defcustom org-table-number-fraction 0.5
891   "Fraction of numbers in a column required to make the column align right.
892 In a column all non-white fields are considered.  If at least this
893 fraction of fields is matched by `org-table-number-fraction',
894 alignment to the right border applies."
895   :group 'org-table-settings
896   :type 'number)
898 (defgroup org-table-editing nil
899   "Behavior of tables during editing in Org-mode."
900   :tag "Org Table Editing"
901   :group 'org-table)
903 (defcustom org-table-automatic-realign t
904   "Non-nil means, automatically re-align table when pressing TAB or RETURN.
905 When nil, aligning is only done with \\[org-table-align], or after column
906 removal/insertion."
907   :group 'org-table-editing
908   :type 'boolean)
910 (defcustom org-table-auto-blank-field t
911   "Non-nil means, automatically blank table field when starting to type into it.
912 This only happens when typing immediately after a field motion
913 command (TAB, S-TAB or RET).
914 Only relevant when `org-enable-table-editor' is equal to `optimized'."
915   :group 'org-table-editing
916   :type 'boolean)
918 (defcustom org-table-tab-jumps-over-hlines t
919   "Non-nil means, tab in the last column of a table with jump over a hline.
920 If a horizontal separator line is following the current line,
921 `org-table-next-field' can either create a new row before that line, or jump
922 over the line.  When this option is nil, a new line will be created before
923 this line."
924   :group 'org-table-editing
925   :type 'boolean)
927 (defcustom org-table-tab-recognizes-table.el t
928   "Non-nil means, TAB will automatically notice a table.el table.
929 When it sees such a table, it moves point into it and - if necessary -
930 calls `table-recognize-table'."
931   :group 'org-table-editing
932   :type 'boolean)
934 (defgroup org-table-calculation nil
935   "Options concerning tables in Org-mode."
936   :tag "Org Table Calculation"
937   :group 'org-table)
939 (defcustom org-table-use-standard-references t
940   "Should org-mode work with table refrences like B3 instead of @3$2?
941 Possible values are:
942 nil     never use them
943 from    accept as input, do not present for editing
944 t:      accept as input and present for editing"
945   :group 'org-table-calculation
946   :type '(choice
947           (const :tag "Never, don't even check unser input for them" nil)
948           (const :tag "Always, both as user input, and when editing" t)
949           (const :tag "Convert user input, don't offer during editing" 'from)))
951 (defcustom org-table-copy-increment t
952   "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
953   :group 'org-table-calculation
954   :type 'boolean)
956 (defcustom org-calc-default-modes
957   '(calc-internal-prec 12
958     calc-float-format  (float 5)
959     calc-angle-mode    deg
960     calc-prefer-frac   nil
961     calc-symbolic-mode nil
962     calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
963     calc-display-working-message t
964     )
965   "List with Calc mode settings for use in calc-eval for table formulas.
966 The list must contain alternating symbols (Calc modes variables and values).
967 Don't remove any of the default settings, just change the values.  Org-mode
968 relies on the variables to be present in the list."
969   :group 'org-table-calculation
970   :type 'plist)
972 (defcustom org-table-formula-evaluate-inline t
973   "Non-nil means, TAB and RET evaluate a formula in current table field.
974 If the current field starts with an equal sign, it is assumed to be a formula
975 which should be evaluated as described in the manual and in the documentation
976 string of the command `org-table-eval-formula'.  This feature requires the
977 Emacs calc package.
978 When this variable is nil, formula calculation is only available through
979 the command \\[org-table-eval-formula]."
980   :group 'org-table-calculation
981   :type 'boolean)
983 (defcustom org-table-formula-use-constants t
984   "Non-nil means, interpret constants in formulas in tables.
985 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
986 by the value given in `org-table-formula-constants', or by a value obtained
987 from the `constants.el' package."
988   :group 'org-table-calculation
989   :type 'boolean)
991 (defcustom org-table-formula-constants nil
992   "Alist with constant names and values, for use in table formulas.
993 The car of each element is a name of a constant, without the `$' before it.
994 The cdr is the value as a string.  For example, if you'd like to use the
995 speed of light in a formula, you would configure
997   (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
999 and then use it in an equation like `$1*$c'.
1001 Constants can also be defined on a per-file basis using a line like
1003 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1004   :group 'org-table-calculation
1005   :type '(repeat
1006           (cons (string :tag "name")
1007                 (string :tag "value"))))
1009 (defvar org-table-formula-constants-local nil
1010   "Local version of `org-table-formula-constants'.")
1011 (make-variable-buffer-local 'org-table-formula-constants-local)
1013 (defcustom org-table-allow-automatic-line-recalculation t
1014   "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1015 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1016   :group 'org-table-calculation
1017   :type 'boolean)
1019 (defgroup org-link nil
1020   "Options concerning links in Org-mode."
1021   :tag "Org Link"
1022   :group 'org)
1024 (defvar org-link-abbrev-alist-local nil
1025   "Buffer-local version of `org-link-abbrev-alist', which see.
1026 The value of this is taken from the #+LINK lines.")
1027 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1029 (defcustom org-link-abbrev-alist nil
1030   "Alist of link abbreviations.
1031 The car of each element is a string, to be replaced at the start of a link.
1032 The cdrs are replacement values, like (\"linkkey\" . REPLACE).  Abbreviated
1033 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1035      [[linkkey:tag][description]]
1037 If REPLACE is a string, the tag will simply be appended to create the link.
1038 If the string contains \"%s\", the tag will be inserted there.
1040 REPLACE may also be a function that will be called with the tag as the
1041 only argument to create the link, which should be returned as a string.
1043 See the manual for examples."
1044   :group 'org-link
1045   :type 'alist)
1047 (defcustom org-descriptive-links t
1048   "Non-nil means, hide link part and only show description of bracket links.
1049 Bracket links are like [[link][descritpion]]. This variable sets the initial
1050 state in new org-mode buffers.  The setting can then be toggled on a
1051 per-buffer basis from the Org->Hyperlinks menu."
1052   :group 'org-link
1053   :type 'boolean)
1055 (defcustom org-link-file-path-type 'adaptive
1056   "How the path name in file links should be stored.
1057 Valid values are:
1059 relative  relative to the current directory, i.e. the directory of the file
1060           into which the link is being inserted.
1061 absolute  absolute path, if possible with ~ for home directory.
1062 noabbrev  absolute path, no abbreviation of home directory.
1063 adaptive  Use relative path for files in the current directory and sub-
1064           directories of it.  For other files, use an absolute path."
1065   :group 'org-link
1066   :type '(choice
1067           (const relative)
1068           (const absolute)
1069           (const noabbrev)
1070           (const adaptive)))
1072 (defcustom org-activate-links '(bracket angle plain radio tag date)
1073   "Types of links that should be activated in Org-mode files.
1074 This is a list of symbols, each leading to the activation of a certain link
1075 type.  In principle, it does not hurt to turn on most link types - there may
1076 be a small gain when turning off unused link types.  The types are:
1078 bracket   The recommended [[link][description]] or [[link]] links with hiding.
1079 angular   Links in angular brackes that may contain whitespace like
1080           <bbdb:Carsten Dominik>.
1081 plain     Plain links in normal text, no whitespace, like http://google.com.
1082 radio     Text that is matched by a radio target, see manual for details.
1083 tag       Tag settings in a headline (link to tag search).
1084 date      Time stamps (link to calendar).
1086 Changing this variable requires a restart of Emacs to become effective."
1087   :group 'org-link
1088   :type '(set (const :tag "Double bracket links (new style)" bracket)
1089               (const :tag "Angular bracket links (old style)" angular)
1090               (const :tag "plain text links" plain)
1091               (const :tag "Radio target matches" radio)
1092               (const :tag "Tags" tag)
1093               (const :tag "Tags" target)
1094               (const :tag "Timestamps" date)))
1096 (defgroup org-link-store nil
1097   "Options concerning storing links in Org-mode"
1098   :tag "Org Store Link"
1099   :group 'org-link)
1101 (defcustom org-email-link-description-format "Email %c: %.30s"
1102   "Format of the description part of a link to an email or usenet message.
1103 The following %-excapes will be replaced by corresponding information:
1105 %F   full \"From\" field
1106 %f   name, taken from \"From\" field, address if no name
1107 %T   full \"To\" field
1108 %t   first name in \"To\" field, address if no name
1109 %c   correspondent.  Unually \"from NAME\", but if you sent it yourself, it
1110      will be \"to NAME\".  See also the variable `org-from-is-user-regexp'.
1111 %s   subject
1112 %m   message-id.
1114 You may use normal field width specification between the % and the letter.
1115 This is for example useful to limit the length of the subject.
1117 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1118   :group 'org-link-store
1119   :type 'string)
1121 (defcustom org-from-is-user-regexp
1122   (let (r1 r2)
1123     (when (and user-mail-address (not (string= user-mail-address "")))
1124       (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1125     (when (and user-full-name (not (string= user-full-name "")))
1126       (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1127     (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1128   "Regexp mached against the \"From:\" header of an email or usenet message.
1129 It should match if the message is from the user him/herself."
1130   :group 'org-link-store
1131   :type 'regexp)
1133 (defcustom org-context-in-file-links t
1134   "Non-nil means, file links from `org-store-link' contain context.
1135 A search string will be added to the file name with :: as separator and
1136 used to find the context when the link is activated by the command
1137 `org-open-at-point'.
1138 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1139 negates this setting for the duration of the command."
1140   :group 'org-link-store
1141   :type 'boolean)
1143 (defcustom org-keep-stored-link-after-insertion nil
1144   "Non-nil means, keep link in list for entire session.
1146 The command `org-store-link' adds a link pointing to the current
1147 location to an internal list.  These links accumulate during a session.
1148 The command `org-insert-link' can be used to insert links into any
1149 Org-mode file (offering completion for all stored links).  When this
1150 option is nil, every link which has been inserted once using \\[org-insert-link]
1151 will be removed from the list, to make completing the unused links
1152 more efficient."
1153   :group 'org-link-store
1154   :type 'boolean)
1156 (defcustom org-usenet-links-prefer-google nil
1157   "Non-nil means, `org-store-link' will create web links to Google groups.
1158 When nil, Gnus will be used for such links.
1159 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1160 negates this setting for the duration of the command."
1161   :group 'org-link-store
1162   :type 'boolean)
1164 (defgroup org-link-follow nil
1165   "Options concerning following links in Org-mode"
1166   :tag "Org Follow Link"
1167   :group 'org-link)
1169 (defcustom org-tab-follows-link nil
1170   "Non-nil means, on links TAB will follow the link.
1171 Needs to be set before org.el is loaded."
1172   :group 'org-link-follow
1173   :type 'boolean)
1175 (defcustom org-return-follows-link nil
1176   "Non-nil means, on links RET will follow the link.
1177 Needs to be set before org.el is loaded."
1178   :group 'org-link-follow
1179   :type 'boolean)
1181 (defcustom org-mouse-1-follows-link t
1182   "Non-nil means, mouse-1 on a link will follow the link.
1183 A longer mouse click will still set point.  Does not wortk on XEmacs.
1184 Needs to be set before org.el is loaded."
1185   :group 'org-link-follow
1186   :type 'boolean)
1188 (defcustom org-mark-ring-length 4
1189   "Number of different positions to be recorded in the ring
1190 Changing this requires a restart of Emacs to work correctly."
1191   :group 'org-link-follow
1192   :type 'interger)
1194 (defcustom org-link-frame-setup
1195   '((vm . vm-visit-folder-other-frame)
1196     (gnus . gnus-other-frame)
1197     (file . find-file-other-window))
1198   "Setup the frame configuration for following links.
1199 When following a link with Emacs, it may often be useful to display
1200 this link in another window or frame.  This variable can be used to
1201 set this up for the different types of links.
1202 For VM, use any of
1203     `vm-visit-folder'
1204     `vm-visit-folder-other-frame'
1205 For Gnus, use any of
1206     `gnus'
1207     `gnus-other-frame'
1208 For FILE, use any of
1209     `find-file'
1210     `find-file-other-window'
1211     `find-file-other-frame'
1212 For the calendar, use the variable `calendar-setup'.
1213 For BBDB, it is currently only possible to display the matches in
1214 another window."
1215   :group 'org-link-follow
1216   :type '(list
1217           (cons (const vm)
1218                 (choice
1219                  (const vm-visit-folder)
1220                  (const vm-visit-folder-other-window)
1221                  (const vm-visit-folder-other-frame)))
1222           (cons (const gnus)
1223                 (choice
1224                  (const gnus)
1225                  (const gnus-other-frame)))
1226           (cons (const file)
1227                 (choice
1228                  (const find-file)
1229                  (const find-file-other-window)
1230                  (const find-file-other-frame)))))
1232 (defcustom org-display-internal-link-with-indirect-buffer nil
1233   "Non-nil means, use indirect buffer to display infile links.
1234 Activating internal links (from one location in a file to another location
1235 in the same file) normally just jumps to the location.  When the link is
1236 activated with a C-u prefix (or with mouse-3), the link is displayed in
1237 another window.  When this option is set, the other window actually displays
1238 an indirect buffer clone of the current buffer, to avoid any visibility
1239 changes to the current buffer."
1240   :group 'org-link-follow
1241   :type 'boolean)
1243 (defcustom org-open-non-existing-files nil
1244   "Non-nil means, `org-open-file' will open non-existing files.
1245 When nil, an error will be generated."
1246   :group 'org-link-follow
1247   :type 'boolean)
1249 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1250   "Function and arguments to call for following mailto links.
1251 This is a list with the first element being a lisp function, and the
1252 remaining elements being arguments to the function.  In string arguments,
1253 %a will be replaced by the address, and %s will be replaced by the subject
1254 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1255   :group 'org-link-follow
1256   :type '(choice
1257           (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1258           (const :tag "compose-mail" (compose-mail "%a" "%s"))
1259           (const :tag "message-mail" (message-mail "%a" "%s"))
1260           (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1262 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1263   "Non-nil means, ask for confirmation before executing shell links.
1264 Shell links can be dangerous: just think about a link
1266      [[shell:rm -rf ~/*][Google Search]]
1268 This link would show up in your Org-mode document as \"Google Search\",
1269 but really it would remove your entire home directory.
1270 Therefore we advise against setting this variable to nil.
1271 Just change it to `y-or-n-p' of you want to confirm with a
1272 single keystroke rather than having to type \"yes\"."
1273   :group 'org-link-follow
1274   :type '(choice
1275           (const :tag "with yes-or-no (safer)" yes-or-no-p)
1276           (const :tag "with y-or-n (faster)" y-or-n-p)
1277           (const :tag "no confirmation (dangerous)" nil)))
1279 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1280   "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1281 Elisp links can be dangerous: just think about a link
1283      [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1285 This link would show up in your Org-mode document as \"Google Search\",
1286 but really it would remove your entire home directory.
1287 Therefore we advise against setting this variable to nil.
1288 Just change it to `y-or-n-p' of you want to confirm with a
1289 single keystroke rather than having to type \"yes\"."
1290   :group 'org-link-follow
1291   :type '(choice
1292           (const :tag "with yes-or-no (safer)" yes-or-no-p)
1293           (const :tag "with y-or-n (faster)" y-or-n-p)
1294           (const :tag "no confirmation (dangerous)" nil)))
1296 (defconst org-file-apps-defaults-gnu
1297   '((remote . emacs)
1298     (t . mailcap))
1299   "Default file applications on a UNIX or GNU/Linux system.
1300 See `org-file-apps'.")
1302 (defconst org-file-apps-defaults-macosx
1303   '((remote . emacs)
1304     (t . "open %s")
1305     ("ps"     . "gv %s")
1306     ("ps.gz"  . "gv %s")
1307     ("eps"    . "gv %s")
1308     ("eps.gz" . "gv %s")
1309     ("dvi"    . "xdvi %s")
1310     ("fig"    . "xfig %s"))
1311   "Default file applications on a MacOS X system.
1312 The system \"open\" is known as a default, but we use X11 applications
1313 for some files for which the OS does not have a good default.
1314 See `org-file-apps'.")
1316 (defconst org-file-apps-defaults-windowsnt
1317   (list
1318    '(remote . emacs)
1319    (cons t
1320          (list (if (featurep 'xemacs)
1321                    'mswindows-shell-execute
1322                  'w32-shell-execute)
1323                "open" 'file)))
1324   "Default file applications on a Windows NT system.
1325 The system \"open\" is used for most files.
1326 See `org-file-apps'.")
1328 (defcustom org-file-apps
1329   '(
1330     ("txt" . emacs)
1331     ("tex" . emacs)
1332     ("ltx" . emacs)
1333     ("org" . emacs)
1334     ("el"  . emacs)
1335     ("bib" . emacs)
1336     )
1337   "External applications for opening `file:path' items in a document.
1338 Org-mode uses system defaults for different file types, but
1339 you can use this variable to set the application for a given file
1340 extension.  The entries in this list are cons cells where the car identifies
1341 files and the cdr the corresponding command.  Possible values for the
1342 file identifier are
1343  \"ext\"         A string identifying an extension
1344  `directory'   Matches a directory
1345  `remote'      Matches a remote file, accessible through tramp or efs.
1346                Remote files most likely should be visited through Emacs
1347                because external applications cannot handle such paths.
1348  t             Default for all remaining files
1350 Possible values for the command are:
1351  `emacs'       The file will be visited by the current Emacs process.
1352  `default'     Use the default application for this file type.
1353  string        A command to be executed by a shell; %s will be replaced
1354                by the path to the file.
1355  sexp          A Lisp form which will be evaluated.  The file path will
1356                be available in the Lisp variable `file'.
1357 For more examples, see the system specific constants
1358 `org-file-apps-defaults-macosx'
1359 `org-file-apps-defaults-windowsnt'
1360 `org-file-apps-defaults-gnu'."
1361   :group 'org-link-follow
1362   :type '(repeat
1363           (cons (choice :value ""
1364                         (string :tag "Extension")
1365                         (const :tag "Default for unrecognized files" t)
1366                         (const :tag "Remote file" remote)
1367                         (const :tag "Links to a directory" directory))
1368                 (choice :value ""
1369                         (const :tag "Visit with Emacs" emacs)
1370                         (const :tag "Use system default" default)
1371                         (string :tag "Command")
1372                         (sexp :tag "Lisp form")))))
1374 (defcustom org-mhe-search-all-folders nil
1375   "Non-nil means, that the search for the mh-message will be extended to
1376 all folders if the message cannot be found in the folder given in the link.
1377 Searching all folders is very efficient with one of the search engines
1378 supported by MH-E, but will be slow with pick."
1379   :group 'org-link-follow
1380   :type 'boolean)
1382 (defgroup org-remember nil
1383   "Options concerning interaction with remember.el."
1384   :tag "Org Remember"
1385   :group 'org)
1387 (defcustom org-directory "~/org"
1388   "Directory with org files.
1389 This directory will be used as default to prompt for org files.
1390 Used by the hooks for remember.el."
1391   :group 'org-remember
1392   :type 'directory)
1394 (defcustom org-default-notes-file "~/.notes"
1395   "Default target for storing notes.
1396 Used by the hooks for remember.el.  This can be a string, or nil to mean
1397 the value of `remember-data-file'.
1398 You can set this on a per-template basis with the variable
1399 `org-remember-templates'."
1400   :group 'org-remember
1401   :type '(choice
1402           (const :tag "Default from remember-data-file" nil)
1403           file))
1405 (defcustom org-remember-store-without-prompt t
1406   "Non-nil means, `C-c C-c' stores remember note without further promts.
1407 In this case, you need `C-u C-c C-c' to get the prompts for
1408 note file and headline.
1409 When this variable is nil, `C-c C-c' give you the prompts, and
1410 `C-u C-c C-c' trigger the fasttrack."
1411   :group 'org-remember
1412   :type 'boolean)
1414 (defcustom org-remember-default-headline ""
1415   "The headline that should be the default location in the notes file.
1416 When filing remember notes, the cursor will start at that position.
1417 You can set this on a per-template basis with the variable
1418 `org-remember-templates'."
1419   :group 'org-remember
1420   :type 'string)
1422 (defcustom org-remember-templates nil
1423   "Templates for the creation of remember buffers.
1424 When nil, just let remember make the buffer.
1425 When not nil, this is a list of 5-element lists.  In each entry, the first
1426 element is a the name of the template, It should be a single short word.
1427 The second element is a character, a unique key to select this template.
1428 The third element is the template.  The forth element is optional and can
1429 specify a destination file for remember items created with this template.
1430 The default file is given by `org-default-notes-file'.  An optional fifth
1431 element can specify the headline in that file that should be offered
1432 first when the user is asked to file the entry.  The default headline is
1433 given in the variable `org-remember-default-headline'.
1435 The template specifies the structure of the remember buffer.  It should have
1436 a first line starting with a star, to act as the org-mode headline.
1437 Furthermore, the following %-escapes will be replaced with content:
1439   %^{prompt}  Prompt the user for a string and replace this sequence with it.
1440               A default value and a completion table ca be specified like this:
1441               %^{prompt|default|completion2|completion3|...}
1442   %t          time stamp, date only
1443   %T          time stamp with date and time
1444   %u, %U      like the above, but inactive time stamps
1445   %^t         like %t, but prompt for date.  Similarly %^T, %^u, %^U
1446               You may define a prompt like %^{Please specify birthday}t
1447   %n          user name (taken from `user-full-name')
1448   %a          annotation, normally the link created with org-store-link
1449   %i          initial content, the region when remember is called with C-u.
1450               If %i is indented, the entire inserted text will be indented
1451               as well.
1452   %c          content of the clipboard, or current kill ring head
1453   %^g         prompt for tags, with completion on tags in target file
1454   %^G         prompt for tags, with completion all tags in all agenda files
1455   %:keyword   specific information for certain link types, see below
1456   %[pathname] insert the contents of the file given by `pathname'
1457   %(sexp)     evaluate elisp `(sexp)' and replace with the result
1458   %!          Store this note immediately after filling the template
1460   %?          After completing the template, position cursor here.
1462 Apart from these general escapes, you can access information specific to the
1463 link type that is created.  For example, calling `remember' in emails or gnus
1464 will record the author and the subject of the message, which you can access
1465 with %:author and %:subject, respectively.  Here is a complete list of what
1466 is recorded for each link type.
1468 Link type          |  Available information
1469 -------------------+------------------------------------------------------
1470 bbdb               |  %:type %:name %:company
1471 vm, wl, mh, rmail  |  %:type %:subject %:message-id
1472                    |  %:from %:fromname %:fromaddress
1473                    |  %:to   %:toname   %:toaddress
1474                    |  %:fromto (either \"to NAME\" or \"from NAME\")
1475 gnus               |  %:group, for messages also all email fields
1476 w3, w3m            |  %:type %:url
1477 info               |  %:type %:file %:node
1478 calendar           |  %:type %:date"
1479   :group 'org-remember
1480   :get (lambda (var) ; Make sure all entries have 5 elements
1481          (mapcar (lambda (x)
1482                    (if (not (stringp (car x))) (setq x (cons "" x)))
1483                    (cond ((= (length x) 4) (append x '("")))
1484                          ((= (length x) 3) (append x '("" "")))
1485                          (t x)))
1486                  (default-value var)))
1487   :type '(repeat
1488           :tag "enabled"
1489           (list :value ("" ?a "\n" nil nil)
1490                 (string :tag "Name")
1491                 (character :tag "Selection Key")
1492                 (string :tag "Template")
1493                 (choice
1494                  (file :tag "Destination file")
1495                  (const :tag "Prompt for file" nil))
1496                 (choice
1497                  (string :tag "Destination headline")
1498                  (const :tag "Selection interface for heading")))))
1500 (defcustom org-reverse-note-order nil
1501   "Non-nil means, store new notes at the beginning of a file or entry.
1502 When nil, new notes will be filed to the end of a file or entry.
1503 This can also be a list with cons cells of regular expressions that
1504 are matched against file names, and values."
1505   :group 'org-remember
1506   :type '(choice
1507           (const :tag "Reverse always" t)
1508           (const :tag "Reverse never" nil)
1509           (repeat :tag "By file name regexp"
1510                   (cons regexp boolean))))
1512 (defcustom org-refile-targets '((nil . (:level . 1)))
1513   "Targets for refiling entries with \\[org-refile].
1514 This is list of cons cells.  Each cell contains:
1515 - a specification of the files to be considered, either a list of files,
1516   or a symbol whose function or value fields will be used to retrieve
1517   a file name or a list of file names.  Nil means, refile to a different
1518   heading in the current buffer.
1519 - A specification of how to find candidate refile targets.  This may be
1520   any of
1521   - a cons cell (:tag . \"TAG\") to identify refile targes by a tag.
1522     This tag has to be present in all target headlines, inheritance will
1523     not be considered.
1524   - a cons cell (:todo . \"KEYWORD\" to identify refile targets by
1525     todo keyword.
1526   - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1527     headlines that are refiling targets.
1528   - a cons cell (:level . N).  Any headline of level N is considered a target.
1529   - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1530 ;; FIXME: what if there are a var and func with same name???
1531   :group 'org-remember
1532   :type '(repeat
1533           (cons
1534            (choice :value org-agenda-files
1535                    (const :tag "All agenda files" org-agenda-files)
1536                    (const :tag "Current buffer" nil)
1537                    (function) (variable) (file))
1538            (choice :tag "Identify target headline by"
1539             (cons :tag "Specific tag" (const :tag) (string))
1540             (cons :tag "TODO keyword" (const :todo) (string))
1541             (cons :tag "Regular expression" (const :regexp) (regexp))
1542             (cons :tag "Level number" (const :level) (integer))
1543             (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1545 (defcustom org-refile-use-outline-path nil
1546   "Non-nil means, provide refile targets as paths.
1547 So a level 3 headline will be available as level1/level2/level3.
1548 When the value is `file', also include the file name (without directory)
1549 into the path.  When `full-file-path', include the full file path."
1550   :group 'org-remember
1551   :type '(choice
1552           (const :tag "Not" nil)
1553           (const :tag "Yes" t)
1554           (const :tag "Start with file name" file)
1555           (const :tag "Start with full file path" full-file-path)))
1557 (defgroup org-todo nil
1558   "Options concerning TODO items in Org-mode."
1559   :tag "Org TODO"
1560   :group 'org)
1562 (defgroup org-progress nil
1563   "Options concerning Progress logging in Org-mode."
1564   :tag "Org Progress"
1565   :group 'org-time)
1567 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1568   "List of TODO entry keyword sequences and their interpretation.
1569 \\<org-mode-map>This is a list of sequences.
1571 Each sequence starts with a symbol, either `sequence' or `type',
1572 indicating if the keywords should be interpreted as a sequence of
1573 action steps, or as different types of TODO items.  The first
1574 keywords are states requiring action - these states will select a headline
1575 for inclusion into the global TODO list Org-mode produces.  If one of
1576 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1577 signify that no further action is necessary.  If \"|\" is not found,
1578 the last keyword is treated as the only DONE state of the sequence.
1580 The command \\[org-todo] cycles an entry through these states, and one
1581 additional state where no keyword is present.  For details about this
1582 cycling, see the manual.
1584 TODO keywords and interpretation can also be set on a per-file basis with
1585 the special #+SEQ_TODO and #+TYP_TODO lines.
1587 For backward compatibility, this variable may also be just a list
1588 of keywords - in this case the interptetation (sequence or type) will be
1589 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1590   :group 'org-todo
1591   :group 'org-keywords
1592   :type '(choice
1593           (repeat :tag "Old syntax, just keywords"
1594                   (string :tag "Keyword"))
1595           (repeat :tag "New syntax"
1596                   (cons
1597                    (choice
1598                     :tag "Interpretation"
1599                     (const :tag "Sequence (cycling hits every state)" sequence)
1600                     (const :tag "Type     (cycling directly to DONE)" type))
1601                    (repeat
1602                     (string :tag "Keyword"))))))
1604 (defvar org-todo-keywords-1 nil)
1605 (make-variable-buffer-local 'org-todo-keywords-1)
1606 (defvar org-todo-keywords-for-agenda nil)
1607 (defvar org-done-keywords-for-agenda nil)
1608 (defvar org-not-done-keywords nil)
1609 (make-variable-buffer-local 'org-not-done-keywords)
1610 (defvar org-done-keywords nil)
1611 (make-variable-buffer-local 'org-done-keywords)
1612 (defvar org-todo-heads nil)
1613 (make-variable-buffer-local 'org-todo-heads)
1614 (defvar org-todo-sets nil)
1615 (make-variable-buffer-local 'org-todo-sets)
1616 (defvar org-todo-log-states nil)
1617 (make-variable-buffer-local 'org-todo-log-states)
1618 (defvar org-todo-kwd-alist nil)
1619 (make-variable-buffer-local 'org-todo-kwd-alist)
1620 (defvar org-todo-key-alist nil)
1621 (make-variable-buffer-local 'org-todo-key-alist)
1622 (defvar org-todo-key-trigger nil)
1623 (make-variable-buffer-local 'org-todo-key-trigger)
1625 (defcustom org-todo-interpretation 'sequence
1626   "Controls how TODO keywords are interpreted.
1627 This variable is in principle obsolete and is only used for
1628 backward compatibility, if the interpretation of todo keywords is
1629 not given already in `org-todo-keywords'.  See that variable for
1630 more information."
1631   :group 'org-todo
1632   :group 'org-keywords
1633   :type '(choice (const sequence)
1634                  (const type)))
1636 (defcustom org-use-fast-todo-selection 'prefix
1637   "Non-nil means, use the fast todo selection scheme with C-c C-t.
1638 This variable describes if and under what circumstances the cycling
1639 mechanism for TODO keywords will be replaced by a single-key, direct
1640 selection scheme.
1642 When nil, fast selection is never used.
1644 When the symbol `prefix', it will be used when `org-todo' is called with
1645 a prefix argument,  i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1646 in an agenda buffer.
1648 When t, fast selection is used by default.  In this case, the prefix
1649 argument forces cycling instead.
1651 In all cases, the special interface is only used if access keys have actually
1652 been assigned by the user, i.e. if keywords in the configuration are followed
1653 by a letter in parenthesis, like TODO(t)."
1654   :group 'org-todo
1655   :type '(choice
1656           (const :tag "Never" nil)
1657           (const :tag "By default" t)
1658           (const :tag "Only with C-u C-c C-t" prefix)))
1660 (defcustom org-after-todo-state-change-hook nil
1661   "Hook which is run after the state of a TODO item was changed.
1662 The new state (a string with a TODO keyword, or nil) is available in the
1663 Lisp variable `state'."
1664   :group 'org-todo
1665   :type 'hook)
1667 (defcustom org-log-done nil
1668   "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1669 When the state of an entry is changed from nothing or a DONE state to
1670 a not-done TODO state, remove a previous closing date.
1672 This can also be a list of symbols indicating under which conditions
1673 the time stamp recording the action should be annotated with a short note.
1674 Valid members of this list are
1676   done       Offer to record a note when marking entries done
1677   state      Offer to record a note whenever changing the TODO state
1678              of an item.  This is only relevant if TODO keywords are
1679              interpreted as sequence, see variable `org-todo-interpretation'.
1680              When `state' is set, this includes tracking `done'.
1681   clock-out  Offer to record a note when clocking out of an item.
1683 A separate window will then pop up and allow you to type a note.
1684 After finishing with C-c C-c, the note will be added directly after the
1685 timestamp, as a plain list item.  See also the variable
1686 `org-log-note-headings'.
1688 Logging can also be configured on a per-file basis by adding one of
1689 the following lines anywhere in the buffer:
1691    #+STARTUP: logdone
1692    #+STARTUP: nologging
1693    #+STARTUP: lognotedone
1694    #+STARTUP: lognotestate
1695    #+STARTUP: lognoteclock-out
1697 You can have local logging settings for a subtree by setting the LOGGING
1698 property to one or more of these keywords."
1699   :group 'org-todo
1700   :group 'org-progress
1701   :type '(choice
1702           (const :tag "off" nil)
1703           (const :tag "on" t)
1704           (set :tag "on, with notes, detailed control" :greedy t :value (done)
1705                (const :tag "when item is marked DONE" done)
1706                (const :tag "when TODO state changes" state)
1707                (const :tag "when clocking out" clock-out))))
1709 (defcustom org-log-done-with-time t
1710   "Non-nil means, the CLOSED time stamp will contain date and time.
1711 When nil, only the date will be recorded."
1712   :group 'org-progress
1713   :type 'boolean)
1715 (defcustom org-log-note-headings
1716   '((done . "CLOSING NOTE %t")
1717     (state . "State %-12s %t")
1718     (clock-out . ""))
1719   "Headings for notes added when clocking out or closing TODO items.
1720 The value is an alist, with the car being a symbol indicating the note
1721 context, and the cdr is the heading to be used.  The heading may also be the
1722 empty string.
1723 %t in the heading will be replaced by a time stamp.
1724 %s will be replaced by the new TODO state, in double quotes.
1725 %u will be replaced by the user name.
1726 %U will be replaced by the full user name."
1727   :group  'org-todo
1728   :group  'org-progress
1729   :type '(list :greedy t
1730           (cons (const :tag "Heading when closing an item" done) string)
1731           (cons (const :tag
1732                        "Heading when changing todo state (todo sequence only)"
1733                        state) string)
1734           (cons (const :tag "Heading when clocking out" clock-out) string)))
1736 (defcustom org-log-states-order-reversed t
1737   "Non-nil means, the latest state change note will be directly after heading.
1738 When nil, the notes will be orderer according to time."
1739   :group 'org-todo
1740   :group 'org-progress
1741   :type 'boolean)
1743 (defcustom org-log-repeat t
1744   "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1745 When nil, no note will be taken.
1746 This option can also be set with on a per-file-basis with
1748    #+STARTUP: logrepeat
1749    #+STARTUP: nologrepeat
1751 You can have local logging settings for a subtree by setting the LOGGING
1752 property to one or more of these keywords."
1753   :group 'org-todo
1754   :group 'org-progress
1755   :type 'boolean)
1757 (defcustom org-clock-into-drawer 2
1758   "Should clocking info be wrapped into a drawer?
1759 When t, clocking info will always be inserted into a :CLOCK: drawer.
1760 If necessary, the drawer will be created.
1761 When nil, the drawer will not be created, but used when present.
1762 When an integer and the number of clocking entries in an item
1763 reaches or exceeds this number, a drawer will be created."
1764   :group 'org-todo
1765   :group 'org-progress
1766   :type '(choice
1767           (const :tag "Always" t)
1768           (const :tag "Only when drawer exists" nil)
1769           (integer :tag "When at least N clock entries")))
1771 (defcustom org-clock-out-when-done t
1772   "When t, the clock will be stopped when the relevant entry is marked DONE.
1773 Nil means, clock will keep running until stopped explicitly with
1774 `C-c C-x C-o', or until the clock is started in a different item."
1775   :group 'org-progress
1776   :type 'boolean)
1778 (defcustom org-clock-in-switch-to-state nil
1779   "Set task to a special todo state while clocking it.
1780 The value should be the state to which the entry should be switched."
1781   :group 'org-progress
1782   :group 'org-todo
1783   :type '(choice
1784           (const :tag "Don't force a state" nil)
1785           (string :tag "State")))
1787 (defgroup org-priorities nil
1788   "Priorities in Org-mode."
1789   :tag "Org Priorities"
1790   :group 'org-todo)
1792 (defcustom org-highest-priority ?A
1793   "The highest priority of TODO items.  A character like ?A, ?B etc.
1794 Must have a smaller ASCII number than `org-lowest-priority'."
1795   :group 'org-priorities
1796   :type 'character)
1798 (defcustom org-lowest-priority ?C
1799   "The lowest priority of TODO items.  A character like ?A, ?B etc.
1800 Must have a larger ASCII number than `org-highest-priority'."
1801   :group 'org-priorities
1802   :type 'character)
1804 (defcustom org-default-priority ?B
1805   "The default priority of TODO items.
1806 This is the priority an item get if no explicit priority is given."
1807   :group 'org-priorities
1808   :type 'character)
1810 (defcustom org-priority-start-cycle-with-default t
1811   "Non-nil means, start with default priority when starting to cycle.
1812 When this is nil, the first step in the cycle will be (depending on the
1813 command used) one higher or lower that the default priority."
1814   :group 'org-priorities
1815   :type 'boolean)
1817 (defgroup org-time nil
1818   "Options concerning time stamps and deadlines in Org-mode."
1819   :tag "Org Time"
1820   :group 'org)
1822 (defcustom org-insert-labeled-timestamps-at-point nil
1823   "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1824 When nil, these labeled time stamps are forces into the second line of an
1825 entry, just after the headline.  When scheduling from the global TODO list,
1826 the time stamp will always be forced into the second line."
1827   :group 'org-time
1828   :type 'boolean)
1830 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1831   "Formats for `format-time-string' which are used for time stamps.
1832 It is not recommended to change this constant.")
1834 (defcustom org-time-stamp-rounding-minutes 0
1835   "Number of minutes to round time stamps to upon insertion.
1836 When zero, insert the time unmodified.  Useful rounding numbers
1837 should be factors of 60, so for example 5, 10, 15.
1838 When this is not zero, you can still force an exact time-stamp by using
1839 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1840   :group 'org-time
1841   :type 'integer)
1843 (defcustom org-display-custom-times nil
1844   "Non-nil means, overlay custom formats over all time stamps.
1845 The formats are defined through the variable `org-time-stamp-custom-formats'.
1846 To turn this on on a per-file basis, insert anywhere in the file:
1847    #+STARTUP: customtime"
1848   :group 'org-time
1849   :set 'set-default
1850   :type 'sexp)
1851 (make-variable-buffer-local 'org-display-custom-times)
1853 (defcustom org-time-stamp-custom-formats
1854   '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1855   "Custom formats for time stamps.  See `format-time-string' for the syntax.
1856 These are overlayed over the default ISO format if the variable
1857 `org-display-custom-times' is set.  Time like %H:%M should be at the
1858 end of the second format."
1859   :group 'org-time
1860   :type 'sexp)
1862 (defun org-time-stamp-format (&optional long inactive)
1863   "Get the right format for a time string."
1864   (let ((f (if long (cdr org-time-stamp-formats)
1865              (car org-time-stamp-formats))))
1866     (if inactive
1867         (concat "[" (substring f 1 -1) "]")
1868       f)))
1870 (defcustom org-read-date-prefer-future t
1871   "Non-nil means, assume future for incomplete date input from user.
1872 This affects the following situations:
1873 1. The user gives a day, but no month.
1874    For example, if today is the 15th, and you enter \"3\", Org-mode will
1875    read this as the third of *next* month.  However, if you enter \"17\",
1876    it will be considered as *this* month.
1877 2. The user gives a month but not a year.
1878    For example, if it is april and you enter \"feb 2\", this will be read
1879    as feb 2, *next* year.  \"May 5\", however, will be this year.
1881 When this option is nil, the current month and year will always be used
1882 as defaults."
1883   :group 'org-time
1884   :type 'boolean)
1886 (defcustom org-read-date-display-live t
1887   "Non-nil means, display current interpretation of date prompt live.
1888 This display will be in an overlay, in the minibuffer."
1889   :group 'org-time
1890   :type 'boolean)
1892 (defcustom org-read-date-popup-calendar t
1893   "Non-nil means, pop up a calendar when prompting for a date.
1894 In the calendar, the date can be selected with mouse-1.  However, the
1895 minibuffer will also be active, and you can simply enter the date as well.
1896 When nil, only the minibuffer will be available."
1897   :group 'org-time
1898   :type 'boolean)
1899 (if (fboundp 'defvaralias)
1900     (defvaralias 'org-popup-calendar-for-date-prompt
1901       'org-read-date-popup-calendar))
1903 (defcustom org-extend-today-until 0
1904   "The hour when your day really ends.
1905 This has influence for the following applications:
1906 - When switching the agenda to \"today\".  It it is still earlier than
1907   the time given here, the day recognized as TODAY is actually yesterday.
1908 - When a date is read from the user and it is still before the time given
1909   here, the current date and time will be assumed to be yesterday, 23:59.
1911 FIXME:
1912 IMPORTANT:  This is still a very experimental feature, it may disappear
1913 again or it may be extended to mean more things."
1914   :group 'org-time
1915   :type 'number)
1917 (defcustom org-edit-timestamp-down-means-later nil
1918   "Non-nil means, S-down will increase the time in a time stamp.
1919 When nil, S-up will increase."
1920   :group 'org-time
1921   :type 'boolean)
1923 (defcustom org-calendar-follow-timestamp-change t
1924   "Non-nil means, make the calendar window follow timestamp changes.
1925 When a timestamp is modified and the calendar window is visible, it will be
1926 moved to the new date."
1927   :group 'org-time
1928   :type 'boolean)
1930 (defcustom org-clock-heading-function nil
1931   "When non-nil, should be a function to create `org-clock-heading'.
1932 This is the string shown in the mode line when a clock is running.
1933 The function is called with point at the beginning of the headline."
1934   :group 'org-time ; FIXME: Should we have a separate group????
1935   :type 'function)
1937 (defgroup org-tags nil
1938   "Options concerning tags in Org-mode."
1939   :tag "Org Tags"
1940   :group 'org)
1942 (defcustom org-tag-alist nil
1943   "List of tags allowed in Org-mode files.
1944 When this list is nil, Org-mode will base TAG input on what is already in the
1945 buffer.
1946 The value of this variable is an alist, the car of each entry must be a
1947 keyword as a string, the cdr may be a character that is used to select
1948 that tag through the fast-tag-selection interface.
1949 See the manual for details."
1950   :group 'org-tags
1951   :type '(repeat
1952           (choice
1953            (cons   (string    :tag "Tag name")
1954                    (character :tag "Access char"))
1955            (const :tag "Start radio group" (:startgroup))
1956            (const :tag "End radio group" (:endgroup)))))
1958 (defcustom org-use-fast-tag-selection 'auto
1959   "Non-nil means, use fast tag selection scheme.
1960 This is a special interface to select and deselect tags with single keys.
1961 When nil, fast selection is never used.
1962 When the symbol `auto', fast selection is used if and only if selection
1963 characters for tags have been configured, either through the variable
1964 `org-tag-alist' or through a #+TAGS line in the buffer.
1965 When t, fast selection is always used and selection keys are assigned
1966 automatically if necessary."
1967   :group 'org-tags
1968   :type '(choice
1969           (const :tag "Always" t)
1970           (const :tag "Never" nil)
1971           (const :tag "When selection characters are configured" 'auto)))
1973 (defcustom org-fast-tag-selection-single-key nil
1974   "Non-nil means, fast tag selection exits after first change.
1975 When nil, you have to press RET to exit it.
1976 During fast tag selection, you can toggle this flag with `C-c'.
1977 This variable can also have the value `expert'.  In this case, the window
1978 displaying the tags menu is not even shown, until you press C-c again."
1979   :group 'org-tags
1980   :type '(choice
1981           (const :tag "No" nil)
1982           (const :tag "Yes" t)
1983           (const :tag "Expert" expert)))
1985 (defvar org-fast-tag-selection-include-todo nil
1986   "Non-nil means, fast tags selection interface will also offer TODO states.
1987 This is an undocumented feature, you should not rely on it.")
1989 (defcustom org-tags-column -80
1990   "The column to which tags should be indented in a headline.
1991 If this number is positive, it specifies the column.  If it is negative,
1992 it means that the tags should be flushright to that column.  For example,
1993 -80 works well for a normal 80 character screen."
1994   :group 'org-tags
1995   :type 'integer)
1997 (defcustom org-auto-align-tags t
1998   "Non-nil means, realign tags after pro/demotion of TODO state change.
1999 These operations change the length of a headline and therefore shift
2000 the tags around.  With this options turned on, after each such operation
2001 the tags are again aligned to `org-tags-column'."
2002   :group 'org-tags
2003   :type 'boolean)
2005 (defcustom org-use-tag-inheritance t
2006   "Non-nil means, tags in levels apply also for sublevels.
2007 When nil, only the tags directly given in a specific line apply there.
2008 If you turn off this option, you very likely want to turn on the
2009 companion option `org-tags-match-list-sublevels'."
2010   :group 'org-tags
2011   :type 'boolean)
2013 (defcustom org-tags-match-list-sublevels nil
2014   "Non-nil means list also sublevels of headlines matching tag search.
2015 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2016 the sublevels of a headline matching a tag search often also match
2017 the same search.  Listing all of them can create very long lists.
2018 Setting this variable to nil causes subtrees of a match to be skipped.
2019 This option is off by default, because inheritance in on.  If you turn
2020 inheritance off, you very likely want to turn this option on.
2022 As a special case, if the tag search is restricted to TODO items, the
2023 value of this variable is ignored and sublevels are always checked, to
2024 make sure all corresponding TODO items find their way into the list."
2025   :group 'org-tags
2026   :type 'boolean)
2028 (defvar org-tags-history nil
2029   "History of minibuffer reads for tags.")
2030 (defvar org-last-tags-completion-table nil
2031   "The last used completion table for tags.")
2032 (defvar org-after-tags-change-hook nil
2033   "Hook that is run after the tags in a line have changed.")
2035 (defgroup org-properties nil
2036   "Options concerning properties in Org-mode."
2037   :tag "Org Properties"
2038   :group 'org)
2040 (defcustom org-property-format "%-10s %s"
2041   "How property key/value pairs should be formatted by `indent-line'.
2042 When `indent-line' hits a property definition, it will format the line
2043 according to this format, mainly to make sure that the values are
2044 lined-up with respect to each other."
2045   :group 'org-properties
2046   :type 'string)
2048 (defcustom org-use-property-inheritance nil
2049   "Non-nil means, properties apply also for sublevels.
2050 This setting is only relevant during property searches, not when querying
2051 an entry with `org-entry-get'.  To retrieve a property with inheritance,
2052 you need to call `org-entry-get' with the inheritance flag.
2053 Turning this on can cause significant overhead when doing a search, so
2054 this is turned off by default.
2055 When nil, only the properties directly given in the current entry count.
2056 The value may also be a list of properties that shouldhave inheritance.
2058 However, note that some special properties use inheritance under special
2059 circumstances (not in searches).  Examples are CATEGORY, ARCHIVE, COLUMNS,
2060 and the properties ending in \"_ALL\" when they are used as descriptor
2061 for valid values of a property."
2062   :group 'org-properties
2063   :type '(choice
2064           (const :tag "Not" nil)
2065           (const :tag "Always" nil)
2066           (repeat :tag "Specific properties" (string :tag "Property"))))
2068 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2069   "The default column format, if no other format has been defined.
2070 This variable can be set on the per-file basis by inserting a line
2072 #+COLUMNS: %25ITEM ....."
2073   :group 'org-properties
2074   :type 'string)
2076 (defcustom org-global-properties nil
2077   "List of property/value pairs that can be inherited by any entry.
2078 You can set buffer-local values for this by adding lines like
2080 #+PROPERTY: NAME VALUE"
2081   :group 'org-properties
2082   :type '(repeat
2083           (cons (string :tag "Property")
2084                 (string :tag "Value"))))
2086 (defvar org-local-properties nil
2087   "List of property/value pairs that can be inherited by any entry.
2088 Valid for the current buffer.
2089 This variable is populated from #+PROPERTY lines.")
2091 (defgroup org-agenda nil
2092   "Options concerning agenda views in Org-mode."
2093   :tag "Org Agenda"
2094   :group 'org)
2096 (defvar org-category nil
2097   "Variable used by org files to set a category for agenda display.
2098 Such files should use a file variable to set it, for example
2100 #   -*- mode: org; org-category: \"ELisp\"
2102 or contain a special line
2104 #+CATEGORY: ELisp
2106 If the file does not specify a category, then file's base name
2107 is used instead.")
2108 (make-variable-buffer-local 'org-category)
2110 (defcustom org-agenda-files nil
2111   "The files to be used for agenda display.
2112 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2113 \\[org-remove-file].  You can also use customize to edit the list.
2115 If an entry is a directory, all files in that directory that are matched by
2116 `org-agenda-file-regexp' will be part of the file list.
2118 If the value of the variable is not a list but a single file name, then
2119 the list of agenda files is actually stored and maintained in that file, one
2120 agenda file per line."
2121   :group 'org-agenda
2122   :type '(choice
2123           (repeat :tag "List of files and directories" file)
2124           (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2126 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2127   "Regular expression to match files for `org-agenda-files'.
2128 If any element in the list in that variable contains a directory instead
2129 of a normal file, all files in that directory that are matched by this
2130 regular expression will be included."
2131   :group 'org-agenda
2132   :type 'regexp)
2134 (defcustom org-agenda-skip-unavailable-files nil
2135   "t means to just skip non-reachable files in `org-agenda-files'.
2136 Nil means to remove them, after a query, from the list."
2137   :group 'org-agenda
2138   :type 'boolean)
2140 (defcustom org-agenda-multi-occur-extra-files nil
2141   "List of extra files to be searched by `org-occur-in-agenda-files'.
2142 The files in `org-agenda-files' are always searched."
2143   :group 'org-agenda
2144   :type '(repeat file))
2146 (defcustom org-agenda-confirm-kill 1
2147   "When set, remote killing from the agenda buffer needs confirmation.
2148 When t, a confirmation is always needed.  When a number N, confirmation is
2149 only needed when the text to be killed contains more than N non-white lines."
2150   :group 'org-agenda
2151   :type '(choice
2152           (const :tag "Never" nil)
2153           (const :tag "Always" t)
2154           (number :tag "When more than N lines")))
2156 (defcustom org-calendar-to-agenda-key [?c]
2157   "The key to be installed in `calendar-mode-map' for switching to the agenda.
2158 The command `org-calendar-goto-agenda' will be bound to this key.  The
2159 default is the character `c' because then `c' can be used to switch back and
2160 forth between agenda and calendar."
2161   :group 'org-agenda
2162   :type 'sexp)
2164 (defcustom org-agenda-compact-blocks nil
2165   "Non-nil means, make the block agenda more compact.
2166 This is done by leaving out unnecessary lines."
2167   :group 'org-agenda
2168   :type nil)
2170 (defgroup org-agenda-export nil
2171  "Options concerning exporting agenda views in Org-mode."
2172  :tag "Org Agenda Export"
2173  :group 'org-agenda)
2175 (defcustom org-agenda-with-colors t
2176   "Non-nil means, use colors in agenda views."
2177   :group 'org-agenda-export
2178   :type 'boolean)
2180 (defcustom org-agenda-exporter-settings nil
2181   "Alist of variable/value pairs that should be active during agenda export.
2182 This is a good place to set uptions for ps-print and for htmlize."
2183   :group 'org-agenda-export
2184   :type '(repeat
2185           (list
2186            (variable)
2187            (sexp :tag "Value"))))
2189 (defcustom org-agenda-export-html-style ""
2190   "The style specification for exported HTML Agenda files.
2191 If this variable contains a string, it will replace the default <style>
2192 section as produced by `htmlize'.
2193 Since there are different ways of setting style information, this variable
2194 needs to contain the full HTML structure to provide a style, including the
2195 surrounding HTML tags.  The style specifications should include definitions
2196 the fonts used by the agenda, here is an example:
2198    <style type=\"text/css\">
2199        p { font-weight: normal; color: gray; }
2200        .org-agenda-structure {
2201           font-size: 110%;
2202           color: #003399;
2203           font-weight: 600;
2204        }
2205        .org-todo {
2206           color: #cc6666;Week-agenda:
2207           font-weight: bold;
2208        }
2209        .org-done {
2210           color: #339933;
2211        }
2212        .title { text-align: center; }
2213        .todo, .deadline { color: red; }
2214        .done { color: green; }
2215     </style>
2217 or, if you want to keep the style in a file,
2219    <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2221 As the value of this option simply gets inserted into the HTML <head> header,
2222 you can \"misuse\" it to also add other text to the header.  However,
2223 <style>...</style> is required, if not present the variable will be ignored."
2224   :group 'org-agenda-export
2225   :group 'org-export-html
2226   :type 'string)
2228 (defgroup org-agenda-custom-commands nil
2229  "Options concerning agenda views in Org-mode."
2230  :tag "Org Agenda Custom Commands"
2231  :group 'org-agenda)
2233 (defcustom org-agenda-custom-commands nil
2234   "Custom commands for the agenda.
2235 These commands will be offered on the splash screen displayed by the
2236 agenda dispatcher \\[org-agenda].  Each entry is a list like this:
2238    (key desc type match options files)
2240 key     The key (one or more characters as a string) to be associated
2241         with the command.
2242 desc    A description of the commend, when omitted or nil, a default
2243         description is built using MATCH.
2244 type    The command type, any of the following symbols:
2245          todo        Entries with a specific TODO keyword, in all agenda files.
2246          tags        Tags match in all agenda files.
2247          tags-todo   Tags match in all agenda files, TODO entries only.
2248          todo-tree   Sparse tree of specific TODO keyword in *current* file.
2249          tags-tree   Sparse tree with all tags matches in *current* file.
2250          occur-tree  Occur sparse tree for *current* file.
2251          ...         A user-defined function.
2252 match   What to search for:
2253          - a single keyword for TODO keyword searches
2254          - a tags match expression for tags searches
2255          - a regular expression for occur searches
2256 options  A list of option settings, similar to that in a let form, so like
2257          this: ((opt1 val1) (opt2 val2) ...)
2258 files    A list of files file to write the produced agenda buffer to
2259          with the command `org-store-agenda-views'.
2260          If a file name ends in \".html\", an HTML version of the buffer
2261          is written out.  If it ends in \".ps\", a postscript version is
2262          produced.  Otherwide, only the plain text is written to the file.
2264 You can also define a set of commands, to create a composite agenda buffer.
2265 In this case, an entry looks like this:
2267   (key desc (cmd1 cmd2 ...) general-options file)
2269 where
2271 desc   A description string to be displayed in the dispatcher menu.
2272 cmd    An agenda command, similar to the above.  However, tree commands
2273        are no allowed, but instead you can get agenda and global todo list.
2274        So valid commands for a set are:
2275        (agenda)
2276        (alltodo)
2277        (stuck)
2278        (todo \"match\" options files)
2279        (tags \"match\" options files)
2280        (tags-todo \"match\" options files)
2282 Each command can carry a list of options, and another set of options can be
2283 given for the whole set of commands.  Individual command options take
2284 precedence over the general options.
2286 When using several characters as key to a command, the first characters
2287 are prefix commands.  For the dispatcher to display useful information, you
2288 should provide a description for the prefix, like
2290  (setq org-agenda-custom-commands
2291    '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2292      (\"hl\" tags \"+HOME+Lisa\")
2293      (\"hp\" tags \"+HOME+Peter\")
2294      (\"hk\" tags \"+HOME+Kim\")))"
2295   :group 'org-agenda-custom-commands
2296   :type '(repeat
2297           (choice :value ("a" "" tags "" nil)
2298            (list :tag "Single command"
2299                  (string :tag "Access Key(s) ")
2300                  (option (string :tag "Description"))
2301                  (choice
2302                   (const :tag "Agenda" agenda)
2303                   (const :tag "TODO list" alltodo)
2304                   (const :tag "Stuck projects" stuck)
2305                   (const :tag "Tags search (all agenda files)" tags)
2306                   (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2307                   (const :tag "TODO keyword search (all agenda files)" todo)
2308                   (const :tag "Tags sparse tree (current buffer)" tags-tree)
2309                   (const :tag "TODO keyword tree (current buffer)" todo-tree)
2310                   (const :tag "Occur tree (current buffer)" occur-tree)
2311                   (sexp :tag "Other, user-defined function"))
2312                  (string :tag "Match")
2313                  (repeat :tag "Local options"
2314                          (list (variable :tag "Option") (sexp :tag "Value")))
2315                  (option (repeat :tag "Export" (file :tag "Export to"))))
2316            (list :tag "Command series, all agenda files"
2317                  (string :tag "Access Key(s)")
2318                  (string :tag "Description  ")
2319                  (repeat
2320                   (choice
2321                    (const :tag "Agenda" (agenda))
2322                    (const :tag "TODO list" (alltodo))
2323                    (const :tag "Stuck projects" (stuck))
2324                    (list :tag "Tags search"
2325                          (const :format "" tags)
2326                          (string :tag "Match")
2327                          (repeat :tag "Local options"
2328                                  (list (variable :tag "Option")
2329                                        (sexp :tag "Value"))))
2331                    (list :tag "Tags search, TODO entries only"
2332                          (const :format "" tags-todo)
2333                          (string :tag "Match")
2334                          (repeat :tag "Local options"
2335                                  (list (variable :tag "Option")
2336                                        (sexp :tag "Value"))))
2338                    (list :tag "TODO keyword search"
2339                          (const :format "" todo)
2340                          (string :tag "Match")
2341                          (repeat :tag "Local options"
2342                                  (list (variable :tag "Option")
2343                                        (sexp :tag "Value"))))
2345                    (list :tag "Other, user-defined function"
2346                          (symbol :tag "function")
2347                          (string :tag "Match")
2348                          (repeat :tag "Local options"
2349                                  (list (variable :tag "Option")
2350                                        (sexp :tag "Value"))))))
2352                  (repeat :tag "General options"
2353                          (list (variable :tag "Option")
2354                                (sexp :tag "Value")))
2355                  (option (repeat :tag "Export" (file :tag "Export to"))))
2356            (cons :tag "Prefix key documentation"
2357                  (string :tag "Access Key(s)")
2358                  (string :tag "Description  ")))))
2360 (defcustom org-stuck-projects
2361   '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2362   "How to identify stuck projects.
2363 This is a list of four items:
2364 1. A tags/todo matcher string that is used to identify a project.
2365    The entire tree below a headline matched by this is considered one project.
2366 2. A list of TODO keywords identifying non-stuck projects.
2367    If the project subtree contains any headline with one of these todo
2368    keywords, the project is considered to be not stuck.  If you specify
2369    \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2370 3. A list of tags identifying non-stuck projects.
2371    If the project subtree contains any headline with one of these tags,
2372    the project is considered to be not stuck.  If you specify \"*\" as
2373    a tag, any tag will mark the project unstuck.
2374 4. An arbitrary regular expression matching non-stuck projects.
2376 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2377 or `C-c a #' to produce the list."
2378   :group 'org-agenda-custom-commands
2379   :type '(list
2380           (string :tag "Tags/TODO match to identify a project")
2381           (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2382           (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2383           (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2386 (defgroup org-agenda-skip nil
2387  "Options concerning skipping parts of agenda files."
2388  :tag "Org Agenda Skip"
2389  :group 'org-agenda)
2391 (defcustom org-agenda-todo-list-sublevels t
2392   "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2393 When nil, the sublevels of a TODO entry are not checked, resulting in
2394 potentially much shorter TODO lists."
2395   :group 'org-agenda-skip
2396   :group 'org-todo
2397   :type 'boolean)
2399 (defcustom org-agenda-todo-ignore-with-date nil
2400   "Non-nil means, don't show entries with a date in the global todo list.
2401 You can use this if you prefer to mark mere appointments with a TODO keyword,
2402 but don't want them to show up in the TODO list.
2403 When this is set, it also covers deadlines and scheduled items, the settings
2404 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2405 will be ignored."
2406   :group 'org-agenda-skip
2407   :group 'org-todo
2408   :type 'boolean)
2410 (defcustom org-agenda-todo-ignore-scheduled nil
2411   "Non-nil means, don't show scheduled entries in the global todo list.
2412 The idea behind this is that by scheduling it, you have already taken care
2413 of this item.
2414 See also `org-agenda-todo-ignore-with-date'."
2415   :group 'org-agenda-skip
2416   :group 'org-todo
2417   :type 'boolean)
2419 (defcustom org-agenda-todo-ignore-deadlines nil
2420   "Non-nil means, don't show near deadline entries in the global todo list.
2421 Near means closer than `org-deadline-warning-days' days.
2422 The idea behind this is that such items will appear in the agenda anyway.
2423 See also `org-agenda-todo-ignore-with-date'."
2424   :group 'org-agenda-skip
2425   :group 'org-todo
2426   :type 'boolean)
2428 (defcustom org-agenda-skip-scheduled-if-done nil
2429   "Non-nil means don't show scheduled items in agenda when they are done.
2430 This is relevant for the daily/weekly agenda, not for the TODO list.  And
2431 it applies only to the actual date of the scheduling.  Warnings about
2432 an item with a past scheduling dates are always turned off when the item
2433 is DONE."
2434   :group 'org-agenda-skip
2435   :type 'boolean)
2437 (defcustom org-agenda-skip-deadline-if-done nil
2438   "Non-nil means don't show deadines when the corresponding item is done.
2439 When nil, the deadline is still shown and should give you a happy feeling.
2440 This is relevant for the daily/weekly agenda.  And it applied only to the
2441 actualy date of the deadline.  Warnings about approching and past-due
2442 deadlines are always turned off when the item is DONE."
2443   :group 'org-agenda-skip
2444   :type 'boolean)
2446 (defcustom org-agenda-skip-timestamp-if-done nil
2447   "Non-nil means don't don't select item by timestamp or -range if it is DONE."
2448   :group 'org-agenda-skip
2449   :type 'boolean)
2451 (defcustom org-timeline-show-empty-dates 3
2452   "Non-nil means, `org-timeline' also shows dates without an entry.
2453 When nil, only the days which actually have entries are shown.
2454 When t, all days between the first and the last date are shown.
2455 When an integer, show also empty dates, but if there is a gap of more than
2456 N days, just insert a special line indicating the size of the gap."
2457   :group 'org-agenda-skip
2458   :type '(choice
2459           (const :tag "None" nil)
2460           (const :tag "All" t)
2461           (number :tag "at most")))
2464 (defgroup org-agenda-startup nil
2465   "Options concerning initial settings in the Agenda in Org Mode."
2466   :tag "Org Agenda Startup"
2467   :group 'org-agenda)
2469 (defcustom org-finalize-agenda-hook nil
2470   "Hook run just before displaying an agenda buffer."
2471   :group 'org-agenda-startup
2472   :type 'hook)
2474 (defcustom org-agenda-mouse-1-follows-link nil
2475   "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2476 A longer mouse click will still set point.  Does not wortk on XEmacs.
2477 Needs to be set before org.el is loaded."
2478   :group 'org-agenda-startup
2479   :type 'boolean)
2481 (defcustom org-agenda-start-with-follow-mode nil
2482   "The initial value of follow-mode in a newly created agenda window."
2483   :group 'org-agenda-startup
2484   :type 'boolean)
2486 (defgroup org-agenda-windows nil
2487   "Options concerning the windows used by the Agenda in Org Mode."
2488   :tag "Org Agenda Windows"
2489   :group 'org-agenda)
2491 (defcustom org-agenda-window-setup 'reorganize-frame
2492   "How the agenda buffer should be displayed.
2493 Possible values for this option are:
2495 current-window    Show agenda in the current window, keeping all other windows.
2496 other-frame       Use `switch-to-buffer-other-frame' to display agenda.
2497 other-window      Use `switch-to-buffer-other-window' to display agenda.
2498 reorganize-frame  Show only two windows on the current frame, the current
2499                   window and the agenda.
2500 See also the variable `org-agenda-restore-windows-after-quit'."
2501   :group 'org-agenda-windows
2502   :type '(choice
2503           (const current-window)
2504           (const other-frame)
2505           (const other-window)
2506           (const reorganize-frame)))
2508 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2509   "The min and max height of the agenda window as a fraction of frame height.
2510 The value of the variable is a cons cell with two numbers between 0 and 1.
2511 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2512   :group 'org-agenda-windows
2513   :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2515 (defcustom org-agenda-restore-windows-after-quit nil
2516   "Non-nil means, restore window configuration open exiting agenda.
2517 Before the window configuration is changed for displaying the agenda,
2518 the current status is recorded.  When the agenda is exited with
2519 `q' or `x' and this option is set, the old state is restored.  If
2520 `org-agenda-window-setup' is `other-frame', the value of this
2521 option will be ignored.."
2522   :group 'org-agenda-windows
2523   :type 'boolean)
2525 (defcustom org-indirect-buffer-display 'other-window
2526   "How should indirect tree buffers be displayed?
2527 This applies to indirect buffers created with the commands
2528 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2529 Valid values are:
2530 current-window   Display in the current window
2531 other-window     Just display in another window.
2532 dedicated-frame  Create one new frame, and re-use it each time.
2533 new-frame        Make a new frame each time.  Note that in this case
2534                  previously-made indirect buffers are kept, and you need to
2535                  kill these buffers yourself."
2536   :group 'org-structure
2537   :group 'org-agenda-windows
2538   :type '(choice
2539           (const :tag "In current window" current-window)
2540           (const :tag "In current frame, other window" other-window)
2541           (const :tag "Each time a new frame" new-frame)
2542           (const :tag "One dedicated frame" dedicated-frame)))
2544 (defgroup org-agenda-daily/weekly nil
2545   "Options concerning the daily/weekly agenda."
2546   :tag "Org Agenda Daily/Weekly"
2547   :group 'org-agenda)
2549 (defcustom org-agenda-ndays 7
2550   "Number of days to include in overview display.
2551 Should be 1 or 7."
2552   :group 'org-agenda-daily/weekly
2553   :type 'number)
2555 (defcustom org-agenda-start-on-weekday 1
2556   "Non-nil means, start the overview always on the specified weekday.
2557 0 denotes Sunday, 1 denotes Monday etc.
2558 When nil, always start on the current day."
2559   :group 'org-agenda-daily/weekly
2560   :type '(choice (const :tag "Today" nil)
2561                  (number :tag "Weekday No.")))
2563 (defcustom org-agenda-show-all-dates t
2564   "Non-nil means, `org-agenda' shows every day in the selected range.
2565 When nil, only the days which actually have entries are shown."
2566   :group 'org-agenda-daily/weekly
2567   :type 'boolean)
2569 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2570   "Format string for displaying dates in the agenda.
2571 Used by the daily/weekly agenda and by the timeline.  This should be
2572 a format string understood by `format-time-string', or a function returning
2573 the formatted date as a string.  The function must take a single argument,
2574 a calendar-style date list like (month day year)."
2575   :group 'org-agenda-daily/weekly
2576   :type '(choice
2577           (string :tag "Format string")
2578           (function :tag "Function")))
2580 (defun org-agenda-format-date-aligned (date)
2581   "Format a date string for display in the daily/weekly agenda, or timeline.
2582 This function makes sure that dates are aligned for easy reading."
2583   (format "%-9s %2d %s %4d"
2584           (calendar-day-name date)
2585           (extract-calendar-day date)
2586           (calendar-month-name (extract-calendar-month date))
2587           (extract-calendar-year date)))
2589 (defcustom org-agenda-include-diary nil
2590   "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2591   :group 'org-agenda-daily/weekly
2592   :type 'boolean)
2594 (defcustom org-agenda-include-all-todo nil
2595   "Set  means weekly/daily agenda will always contain all TODO entries.
2596 The TODO entries will be listed at the top of the agenda, before
2597 the entries for specific days."
2598   :group 'org-agenda-daily/weekly
2599   :type 'boolean)
2601 (defcustom org-agenda-repeating-timestamp-show-all t
2602   "Non-nil means, show all occurences of a repeating stamp in the agenda.
2603 When nil, only one occurence is shown, either today or the
2604 nearest into the future."
2605   :group 'org-agenda-daily/weekly
2606   :type 'boolean)
2608 (defcustom org-deadline-warning-days 14
2609   "No. of days before expiration during which a deadline becomes active.
2610 This variable governs the display in sparse trees and in the agenda.
2611 When negative, it means use this number (the absolute value of it)
2612 even if a deadline has a different individual lead time specified."
2613   :group 'org-time
2614   :group 'org-agenda-daily/weekly
2615   :type 'number)
2617 (defcustom org-scheduled-past-days 10000
2618   "No. of days to continue listing scheduled items that are not marked DONE.
2619 When an item is scheduled on a date, it shows up in the agenda on this
2620 day and will be listed until it is marked done for the number of days
2621 given here."
2622   :group 'org-agenda-daily/weekly
2623   :type 'number)
2625 (defgroup org-agenda-time-grid nil
2626   "Options concerning the time grid in the Org-mode Agenda."
2627   :tag "Org Agenda Time Grid"
2628   :group 'org-agenda)
2630 (defcustom org-agenda-use-time-grid t
2631   "Non-nil means, show a time grid in the agenda schedule.
2632 A time grid is a set of lines for specific times (like every two hours between
2633 8:00 and 20:00).  The items scheduled for a day at specific times are
2634 sorted in between these lines.
2635 For details about when the grid will be shown, and what it will look like, see
2636 the variable `org-agenda-time-grid'."
2637   :group 'org-agenda-time-grid
2638   :type 'boolean)
2640 (defcustom org-agenda-time-grid
2641   '((daily today require-timed)
2642     "----------------"
2643     (800 1000 1200 1400 1600 1800 2000))
2645   "The settings for time grid for agenda display.
2646 This is a list of three items.  The first item is again a list.  It contains
2647 symbols specifying conditions when the grid should be displayed:
2649  daily         if the agenda shows a single day
2650  weekly        if the agenda shows an entire week
2651  today         show grid on current date, independent of daily/weekly display
2652  require-timed show grid only if at least one item has a time specification
2654 The second item is a string which will be places behing the grid time.
2656 The third item is a list of integers, indicating the times that should have
2657 a grid line."
2658   :group 'org-agenda-time-grid
2659   :type
2660   '(list
2661     (set :greedy t :tag "Grid Display Options"
2662          (const :tag "Show grid in single day agenda display" daily)
2663          (const :tag "Show grid in weekly agenda display" weekly)
2664          (const :tag "Always show grid for today" today)
2665          (const :tag "Show grid only if any timed entries are present"
2666                 require-timed)
2667          (const :tag "Skip grid times already present in an entry"
2668                 remove-match))
2669     (string :tag "Grid String")
2670     (repeat :tag "Grid Times" (integer :tag "Time"))))
2672 (defgroup org-agenda-sorting nil
2673   "Options concerning sorting in the Org-mode Agenda."
2674   :tag "Org Agenda Sorting"
2675   :group 'org-agenda)
2677 (defconst org-sorting-choice
2678   '(choice
2679     (const time-up) (const time-down)
2680     (const category-keep) (const category-up) (const category-down)
2681     (const tag-down) (const tag-up)
2682     (const priority-up) (const priority-down))
2683   "Sorting choices.")
2685 (defcustom org-agenda-sorting-strategy
2686   '((agenda time-up category-keep priority-down)
2687     (todo category-keep priority-down)
2688     (tags category-keep priority-down))
2689   "Sorting structure for the agenda items of a single day.
2690 This is a list of symbols which will be used in sequence to determine
2691 if an entry should be listed before another entry.  The following
2692 symbols are recognized:
2694 time-up         Put entries with time-of-day indications first, early first
2695 time-down       Put entries with time-of-day indications first, late first
2696 category-keep   Keep the default order of categories, corresponding to the
2697                 sequence in `org-agenda-files'.
2698 category-up     Sort alphabetically by category, A-Z.
2699 category-down   Sort alphabetically by category, Z-A.
2700 tag-up          Sort alphabetically by last tag, A-Z.
2701 tag-down        Sort alphabetically by last tag, Z-A.
2702 priority-up     Sort numerically by priority, high priority last.
2703 priority-down   Sort numerically by priority, high priority first.
2705 The different possibilities will be tried in sequence, and testing stops
2706 if one comparison returns a \"not-equal\".  For example, the default
2707     '(time-up category-keep priority-down)
2708 means: Pull out all entries having a specified time of day and sort them,
2709 in order to make a time schedule for the current day the first thing in the
2710 agenda listing for the day.  Of the entries without a time indication, keep
2711 the grouped in categories, don't sort the categories, but keep them in
2712 the sequence given in `org-agenda-files'.  Within each category sort by
2713 priority.
2715 Leaving out `category-keep' would mean that items will be sorted across
2716 categories by priority.
2718 Instead of a single list, this can also be a set of list for specific
2719 contents, with a context symbol in the car of the list, any of
2720 `agenda', `todo', `tags' for the corresponding agenda views."
2721   :group 'org-agenda-sorting
2722   :type `(choice
2723           (repeat :tag "General" ,org-sorting-choice)
2724           (list :tag "Individually"
2725                 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2726                       (repeat ,org-sorting-choice))
2727                 (cons (const :tag "Strategy for TODO lists" todo)
2728                       (repeat ,org-sorting-choice))
2729                 (cons (const :tag "Strategy for Tags matches" tags)
2730                       (repeat ,org-sorting-choice)))))
2732 (defcustom org-sort-agenda-notime-is-late t
2733   "Non-nil means, items without time are considered late.
2734 This is only relevant for sorting.  When t, items which have no explicit
2735 time like 15:30 will be considered as 99:01, i.e. later than any items which
2736 do have a time.  When nil, the default time is before 0:00.  You can use this
2737 option to decide if the schedule for today should come before or after timeless
2738 agenda entries."
2739   :group 'org-agenda-sorting
2740   :type 'boolean)
2742 (defgroup org-agenda-line-format nil
2743   "Options concerning the entry prefix in the Org-mode agenda display."
2744   :tag "Org Agenda Line Format"
2745   :group 'org-agenda)
2747 (defcustom org-agenda-prefix-format
2748   '((agenda  . "  %-12:c%?-12t% s")
2749     (timeline  . "  % s")
2750     (todo  . "  %-12:c")
2751     (tags  . "  %-12:c"))
2752   "Format specifications for the prefix of items in the agenda views.
2753 An alist with four entries, for the different agenda types.  The keys to the
2754 sublists are `agenda', `timeline', `todo', and `tags'.  The values
2755 are format strings.
2756 This format works similar to a printf format, with the following meaning:
2758   %c   the category of the item, \"Diary\" for entries from the diary, or
2759        as given by the CATEGORY keyword or derived from the file name.
2760   %T   the *last* tag of the item.  Last because inherited tags come
2761        first in the list.
2762   %t   the time-of-day specification if one applies to the entry, in the
2763        format HH:MM
2764   %s   Scheduling/Deadline information, a short string
2766 All specifiers work basically like the standard `%s' of printf, but may
2767 contain two additional characters:  A question mark just after the `%' and
2768 a whitespace/punctuation character just before the final letter.
2770 If the first character after `%' is a question mark, the entire field
2771 will only be included if the corresponding value applies to the
2772 current entry.  This is useful for fields which should have fixed
2773 width when present, but zero width when absent.  For example,
2774 \"%?-12t\" will result in a 12 character time field if a time of the
2775 day is specified, but will completely disappear in entries which do
2776 not contain a time.
2778 If there is punctuation or whitespace character just before the final
2779 format letter, this character will be appended to the field value if
2780 the value is not empty.  For example, the format \"%-12:c\" leads to
2781 \"Diary: \" if the category is \"Diary\".  If the category were be
2782 empty, no additional colon would be interted.
2784 The default value of this option is \"  %-12:c%?-12t% s\", meaning:
2785 - Indent the line with two space characters
2786 - Give the category in a 12 chars wide field, padded with whitespace on
2787   the right (because of `-').  Append a colon if there is a category
2788   (because of `:').
2789 - If there is a time-of-day, put it into a 12 chars wide field.  If no
2790   time, don't put in an empty field, just skip it (because of '?').
2791 - Finally, put the scheduling information and append a whitespace.
2793 As another example, if you don't want the time-of-day of entries in
2794 the prefix, you could use:
2796   (setq org-agenda-prefix-format \"  %-11:c% s\")
2798 See also the variables `org-agenda-remove-times-when-in-prefix' and
2799 `org-agenda-remove-tags'."
2800   :type '(choice
2801           (string :tag "General format")
2802           (list :greedy t :tag "View dependent"
2803                 (cons  (const agenda) (string :tag "Format"))
2804                 (cons  (const timeline) (string :tag "Format"))
2805                 (cons  (const todo) (string :tag "Format"))
2806                 (cons  (const tags) (string :tag "Format"))))
2807   :group 'org-agenda-line-format)
2809 (defvar org-prefix-format-compiled nil
2810   "The compiled version of the most recently used prefix format.
2811 See the variable `org-agenda-prefix-format'.")
2813 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2814   "Text preceeding scheduled items in the agenda view.
2815 THis is a list with two strings.  The first applies when the item is
2816 scheduled on the current day.  The second applies when it has been scheduled
2817 previously, it may contain a %d to capture how many days ago the item was
2818 scheduled."
2819   :group 'org-agenda-line-format
2820   :type '(list
2821           (string :tag "Scheduled today     ")
2822           (string :tag "Scheduled previously")))
2824 (defcustom org-agenda-deadline-leaders '("Deadline:  " "In %3d d.: ")
2825   "Text preceeding deadline items in the agenda view.
2826 This is a list with two strings.  The first applies when the item has its
2827 deadline on the current day.  The second applies when it is in the past or
2828 in the future, it may contain %d to capture how many days away the deadline
2829 is (was)."
2830   :group 'org-agenda-line-format
2831   :type '(list
2832           (string :tag "Deadline today   ")
2833           (string :tag "Deadline relative")))
2835 (defcustom org-agenda-remove-times-when-in-prefix t
2836   "Non-nil means, remove duplicate time specifications in agenda items.
2837 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2838 time-of-day specification in a headline or diary entry is extracted and
2839 placed into the prefix.  If this option is non-nil, the original specification
2840 \(a timestamp or -range, or just a plain time(range) specification like
2841 11:30-4pm) will be removed for agenda display.  This makes the agenda less
2842 cluttered.
2843 The option can be t or nil.  It may also be the symbol `beg', indicating
2844 that the time should only be removed what it is located at the beginning of
2845 the headline/diary entry."
2846   :group 'org-agenda-line-format
2847   :type '(choice
2848           (const :tag "Always" t)
2849           (const :tag "Never" nil)
2850           (const :tag "When at beginning of entry" beg)))
2853 (defcustom org-agenda-default-appointment-duration nil
2854   "Default duration for appointments that only have a starting time.
2855 When nil, no duration is specified in such cases.
2856 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2857   :group 'org-agenda-line-format
2858   :type '(choice
2859           (integer :tag "Minutes")
2860           (const :tag "No default duration")))
2863 (defcustom org-agenda-remove-tags nil
2864   "Non-nil means, remove the tags from the headline copy in the agenda.
2865 When this is the symbol `prefix', only remove tags when
2866 `org-agenda-prefix-format' contains a `%T' specifier."
2867   :group 'org-agenda-line-format
2868   :type '(choice
2869           (const :tag "Always" t)
2870           (const :tag "Never" nil)
2871           (const :tag "When prefix format contains %T" prefix)))
2873 (if (fboundp 'defvaralias)
2874     (defvaralias 'org-agenda-remove-tags-when-in-prefix
2875       'org-agenda-remove-tags))
2877 (defcustom org-agenda-tags-column -80
2878   "Shift tags in agenda items to this column.
2879 If this number is positive, it specifies the column.  If it is negative,
2880 it means that the tags should be flushright to that column.  For example,
2881 -80 works well for a normal 80 character screen."
2882   :group 'org-agenda-line-format
2883   :type 'integer)
2885 (if (fboundp 'defvaralias)
2886     (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2888 (defcustom org-agenda-fontify-priorities t
2889   "Non-nil means, highlight low and high priorities in agenda.
2890 When t, the highest priority entries are bold, lowest priority italic.
2891 This may also be an association list of priority faces.  The face may be
2892 a names face, or a list like `(:background \"Red\")'."
2893   :group 'org-agenda-line-format
2894   :type '(choice
2895           (const :tag "Never" nil)
2896           (const :tag "Defaults" t)
2897           (repeat :tag "Specify"
2898                   (list (character :tag "Priority" :value ?A)
2899                         (sexp :tag "face")))))
2901 (defgroup org-latex nil
2902   "Options for embedding LaTeX code into Org-mode"
2903   :tag "Org LaTeX"
2904   :group 'org)
2906 (defcustom org-format-latex-options
2907   '(:foreground default :background default :scale 1.0
2908     :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2909     :matchers ("begin" "$" "$$" "\\(" "\\["))
2910   "Options for creating images from LaTeX fragments.
2911 This is a property list with the following properties:
2912 :foreground  the foreground color for images embedded in emacs, e.g. \"Black\".
2913              `default' means use the forground of the default face.
2914 :background  the background color, or \"Transparent\".
2915              `default' means use the background of the default face.
2916 :scale       a scaling factor for the size of the images
2917 :html-foreground, :html-background, :html-scale
2918              The same numbers for HTML export.
2919 :matchers    a list indicating which matchers should be used to
2920              find LaTeX fragments.  Valid members of this list are:
2921              \"begin\"  find environments
2922              \"$\"      find math expressions surrounded by $...$
2923              \"$$\"     find math expressions surrounded by $$....$$
2924              \"\\(\"     find math expressions surrounded by \\(...\\)
2925              \"\\ [\"    find math expressions surrounded by \\ [...\\]"
2926   :group 'org-latex
2927   :type 'plist)
2929 (defcustom org-format-latex-header "\\documentclass{article}
2930 \\usepackage{fullpage}         % do not remove
2931 \\usepackage{amssymb}
2932 \\usepackage[usenames]{color}
2933 \\usepackage{amsmath}
2934 \\usepackage{latexsym}
2935 \\usepackage[mathscr]{eucal}
2936 \\pagestyle{empty}             % do not remove"
2937   "The document header used for processing LaTeX fragments."
2938   :group 'org-latex
2939   :type 'string)
2941 (defgroup org-export nil
2942   "Options for exporting org-listings."
2943   :tag "Org Export"
2944   :group 'org)
2946 (defgroup org-export-general nil
2947   "General options for exporting Org-mode files."
2948   :tag "Org Export General"
2949   :group 'org-export)
2951 ;; FIXME
2952 (defvar org-export-publishing-directory nil)
2954 (defcustom org-export-with-special-strings t
2955   "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
2956 When this option is turned on, these strings will be exported as:
2958   Org   HTML       LaTeX
2959  -----+----------+--------
2960   \\-    &shy;      \\-
2961   --    &ndash;    --
2962   ---   &mdash;    ---
2963   ...   &hellip;   \ldots
2965 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
2966   :group 'org-export-translation
2967   :type 'boolean)
2969 (defcustom org-export-language-setup
2970   '(("en"  "Author"          "Date"  "Table of Contents")
2971     ("cs"  "Autor"           "Datum" "Obsah")
2972     ("da"  "Ophavsmand"      "Dato"  "Indhold")
2973     ("de"  "Autor"           "Datum" "Inhaltsverzeichnis")
2974     ("es"  "Autor"           "Fecha" "\xcdndice")
2975     ("fr"  "Auteur"          "Date"  "Table des mati\xe8res")
2976     ("it"  "Autore"          "Data"  "Indice")
2977     ("nl"  "Auteur"          "Datum" "Inhoudsopgave")
2978     ("nn"  "Forfattar"       "Dato"  "Innhold")  ;; nn = Norsk (nynorsk)
2979     ("sv"  "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2980   "Terms used in export text, translated to different languages.
2981 Use the variable `org-export-default-language' to set the language,
2982 or use the +OPTION lines for a per-file setting."
2983   :group 'org-export-general
2984   :type '(repeat
2985           (list
2986            (string :tag "HTML language tag")
2987            (string :tag "Author")
2988            (string :tag "Date")
2989            (string :tag "Table of Contents"))))
2991 (defcustom org-export-default-language "en"
2992   "The default language of HTML export, as a string.
2993 This should have an association in `org-export-language-setup'."
2994   :group 'org-export-general
2995   :type 'string)
2997 (defcustom org-export-skip-text-before-1st-heading t
2998   "Non-nil means, skip all text before the first headline when exporting.
2999 When nil, that text is exported as well."
3000   :group 'org-export-general
3001   :type 'boolean)
3003 (defcustom org-export-headline-levels 3
3004   "The last level which is still exported as a headline.
3005 Inferior levels will produce itemize lists when exported.
3006 Note that a numeric prefix argument to an exporter function overrides
3007 this setting.
3009 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3010   :group 'org-export-general
3011   :type 'number)
3013 (defcustom org-export-with-section-numbers t
3014   "Non-nil means, add section numbers to headlines when exporting.
3016 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3017   :group 'org-export-general
3018   :type 'boolean)
3020 (defcustom org-export-with-toc t
3021   "Non-nil means, create a table of contents in exported files.
3022 The TOC contains headlines with levels up to`org-export-headline-levels'.
3023 When an integer, include levels up to N in the toc, this may then be
3024 different from `org-export-headline-levels', but it will not be allowed
3025 to be larger than the number of headline levels.
3026 When nil, no table of contents is made.
3028 Headlines which contain any TODO items will be marked with \"(*)\" in
3029 ASCII export, and with red color in HTML output, if the option
3030 `org-export-mark-todo-in-toc' is set.
3032 In HTML output, the TOC will be clickable.
3034 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3035 or \"toc:3\"."
3036   :group 'org-export-general
3037   :type '(choice
3038           (const :tag "No Table of Contents" nil)
3039           (const :tag "Full Table of Contents" t)
3040           (integer :tag "TOC to level")))
3042 (defcustom org-export-mark-todo-in-toc nil
3043   "Non-nil means, mark TOC lines that contain any open TODO items."
3044   :group 'org-export-general
3045   :type 'boolean)
3047 (defcustom org-export-preserve-breaks nil
3048   "Non-nil means, preserve all line breaks when exporting.
3049 Normally, in HTML output paragraphs will be reformatted.  In ASCII
3050 export, line breaks will always be preserved, regardless of this variable.
3052 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3053   :group 'org-export-general
3054   :type 'boolean)
3056 (defcustom org-export-with-archived-trees 'headline
3057   "Whether subtrees with the ARCHIVE tag should be exported.
3058 This can have three different values
3059 nil       Do not export, pretend this tree is not present
3060 t         Do export the entire tree
3061 headline  Only export the headline, but skip the tree below it."
3062   :group 'org-export-general
3063   :group 'org-archive
3064   :type '(choice
3065           (const :tag "not at all" nil)
3066           (const :tag "headline only" 'headline)
3067           (const :tag "entirely" t)))
3069 (defcustom org-export-author-info t
3070   "Non-nil means, insert author name and email into the exported file.
3072 This option can also be set with the +OPTIONS line,
3073 e.g. \"author-info:nil\"."
3074   :group 'org-export-general
3075   :type 'boolean)
3077 (defcustom org-export-time-stamp-file t
3078   "Non-nil means, insert a time stamp into the exported file.
3079 The time stamp shows when the file was created.
3081 This option can also be set with the +OPTIONS line,
3082 e.g. \"timestamp:nil\"."
3083   :group 'org-export-general
3084   :type 'boolean)
3086 (defcustom org-export-with-timestamps t
3087   "If nil, do not export time stamps and associated keywords."
3088   :group 'org-export-general
3089   :type 'boolean)
3091 (defcustom org-export-remove-timestamps-from-toc t
3092   "If nil, remove timestamps from the table of contents entries."
3093   :group 'org-export-general
3094   :type 'boolean)
3096 (defcustom org-export-with-tags 'not-in-toc
3097   "If nil, do not export tags, just remove them from headlines.
3098 If this is the symbol `not-in-toc', tags will be removed from table of
3099 contents entries, but still be shown in the headlines of the document.
3101 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3102   :group 'org-export-general
3103   :type '(choice
3104           (const :tag "Off" nil)
3105           (const :tag "Not in TOC" not-in-toc)
3106           (const :tag "On" t)))
3108 (defcustom org-export-with-drawers nil
3109   "Non-nil means, export with drawers like the property drawer.
3110 When t, all drawers are exported.  This may also be a list of
3111 drawer names to export."
3112   :group 'org-export-general
3113   :type '(choice
3114           (const :tag "All drawers" t)
3115           (const :tag "None" nil)
3116           (repeat :tag "Selected drawers"
3117                   (string :tag "Drawer name"))))
3119 (defgroup org-export-translation nil
3120   "Options for translating special ascii sequences for the export backends."
3121   :tag "Org Export Translation"
3122   :group 'org-export)
3124 (defcustom org-export-with-emphasize t
3125   "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3126 If the export target supports emphasizing text, the word will be
3127 typeset in bold, italic, or underlined, respectively.  Works only for
3128 single words, but you can say: I *really* *mean* *this*.
3129 Not all export backends support this.
3131 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3132   :group 'org-export-translation
3133   :type 'boolean)
3135 (defcustom org-export-with-footnotes t
3136   "If nil, export [1] as a footnote marker.
3137 Lines starting with [1] will be formatted as footnotes.
3139 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3140   :group 'org-export-translation
3141   :type 'boolean)
3143 (defcustom org-export-with-sub-superscripts t
3144   "Non-nil means, interpret \"_\" and \"^\" for export.
3145 When this option is turned on, you can use TeX-like syntax for sub- and
3146 superscripts.  Several characters after \"_\" or \"^\" will be
3147 considered as a single item - so grouping with {} is normally not
3148 needed.  For example, the following things will be parsed as single
3149 sub- or superscripts.
3151  10^24   or   10^tau     several digits will be considered 1 item.
3152  10^-12  or   10^-tau    a leading sign with digits or a word
3153  x^2-y^3                 will be read as x^2 - y^3, because items are
3154                          terminated by almost any nonword/nondigit char.
3155  x_{i^2} or   x^(2-i)    braces or parenthesis do grouping.
3157 Still, ambiguity is possible - so when in doubt use {} to enclose the
3158 sub/superscript.  If you set this variable to the symbol `{}',
3159 the braces are *required* in order to trigger interpretations as
3160 sub/superscript.  This can be helpful in documents that need \"_\"
3161 frequently in plain text.
3163 Not all export backends support this, but HTML does.
3165 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3166   :group 'org-export-translation
3167   :type '(choice
3168           (const :tag "Always interpret" t)
3169           (const :tag "Only with braces" {})
3170           (const :tag "Never interpret" nil)))
3172 (defcustom org-export-with-special-strings t
3173   "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3174 When this option is turned on, these strings will be exported as:
3176 \\-  : &shy;
3177 --  : &ndash;
3178 --- :  &mdash;
3180 Not all export backends support this, but HTML does.
3182 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3183   :group 'org-export-translation
3184   :type 'boolean)
3186 (defcustom org-export-with-TeX-macros t
3187   "Non-nil means, interpret simple TeX-like macros when exporting.
3188 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3189 No only real TeX macros will work here, but the standard HTML entities
3190 for math can be used as macro names as well.  For a list of supported
3191 names in HTML export, see the constant `org-html-entities'.
3192 Not all export backends support this.
3194 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3195   :group 'org-export-translation
3196   :group 'org-export-latex
3197   :type 'boolean)
3199 (defcustom org-export-with-LaTeX-fragments nil
3200   "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3201 When set, the exporter will find LaTeX environments if the \\begin line is
3202 the first non-white thing on a line.  It will also find the math delimiters
3203 like $a=b$ and \\( a=b \\) for inline math,  $$a=b$$ and \\[ a=b \\] for
3204 display math.
3206 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3207   :group 'org-export-translation
3208   :group 'org-export-latex
3209   :type 'boolean)
3211 (defcustom org-export-with-fixed-width t
3212   "Non-nil means, lines starting with \":\" will be in fixed width font.
3213 This can be used to have pre-formatted text, fragments of code etc.  For
3214 example:
3215   : ;; Some Lisp examples
3216   : (while (defc cnt)
3217   :   (ding))
3218 will be looking just like this in also HTML.  See also the QUOTE keyword.
3219 Not all export backends support this.
3221 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3222   :group 'org-export-translation
3223   :type 'boolean)
3225 (defcustom org-match-sexp-depth 3
3226   "Number of stacked braces for sub/superscript matching.
3227 This has to be set before loading org.el to be effective."
3228   :group 'org-export-translation
3229   :type 'integer)
3231 (defgroup org-export-tables nil
3232   "Options for exporting tables in Org-mode."
3233   :tag "Org Export Tables"
3234   :group 'org-export)
3236 (defcustom org-export-with-tables t
3237   "If non-nil, lines starting with \"|\" define a table.
3238 For example:
3240   | Name        | Address  | Birthday  |
3241   |-------------+----------+-----------|
3242   | Arthur Dent | England  | 29.2.2100 |
3244 Not all export backends support this.
3246 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3247   :group 'org-export-tables
3248   :type 'boolean)
3250 (defcustom org-export-highlight-first-table-line t
3251   "Non-nil means, highlight the first table line.
3252 In HTML export, this means use <th> instead of <td>.
3253 In tables created with table.el, this applies to the first table line.
3254 In Org-mode tables, all lines before the first horizontal separator
3255 line will be formatted with <th> tags."
3256   :group 'org-export-tables
3257   :type 'boolean)
3259 (defcustom org-export-table-remove-special-lines t
3260   "Remove special lines and marking characters in calculating tables.
3261 This removes the special marking character column from tables that are set
3262 up for spreadsheet calculations.  It also removes the entire lines
3263 marked with `!', `_', or `^'.  The lines with `$' are kept, because
3264 the values of constants may be useful to have."
3265   :group 'org-export-tables
3266   :type 'boolean)
3268 (defcustom org-export-prefer-native-exporter-for-tables nil
3269   "Non-nil means, always export tables created with table.el natively.
3270 Natively means, use the HTML code generator in table.el.
3271 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3272 the table does not use row- or column-spanning).  This has the
3273 advantage, that the automatic HTML conversions for math symbols and
3274 sub/superscripts can be applied.  Org-mode's HTML generator is also
3275 much faster."
3276   :group 'org-export-tables
3277   :type 'boolean)
3279 (defgroup org-export-ascii nil
3280   "Options specific for ASCII export of Org-mode files."
3281   :tag "Org Export ASCII"
3282   :group 'org-export)
3284 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3285   "Characters for underlining headings in ASCII export.
3286 In the given sequence, these characters will be used for level 1, 2, ..."
3287   :group 'org-export-ascii
3288   :type '(repeat character))
3290 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3291   "Bullet characters for headlines converted to lists in ASCII export.
3292 The first character is is used for the first lest level generated in this
3293 way, and so on.  If there are more levels than characters given here,
3294 the list will be repeated.
3295 Note that plain lists will keep the same bullets as the have in the
3296 Org-mode file."
3297   :group 'org-export-ascii
3298   :type '(repeat character))
3300 (defgroup org-export-xml nil
3301   "Options specific for XML export of Org-mode files."
3302   :tag "Org Export XML"
3303   :group 'org-export)
3305 (defgroup org-export-html nil
3306   "Options specific for HTML export of Org-mode files."
3307   :tag "Org Export HTML"
3308   :group 'org-export)
3310 (defcustom org-export-html-coding-system nil
3311   ""
3312   :group 'org-export-html
3313   :type 'coding-system)
3315 (defcustom org-export-html-extension "html"
3316   "The extension for exported HTML files."
3317   :group 'org-export-html
3318   :type 'string)
3320 (defcustom org-export-html-style
3321 "<style type=\"text/css\">
3322   html {
3323         font-family: Times, serif;
3324         font-size: 12pt;
3325   }
3326   .title { text-align: center; }
3327   .todo  { color: red; }
3328   .done { color: green; }
3329   .timestamp { color: grey }
3330   .timestamp-kwd { color: CadetBlue }
3331   .tag { background-color:lightblue; font-weight:normal }
3332   .target { background-color: lavender; }
3333   pre {
3334         border: 1pt solid #AEBDCC;
3335         background-color: #F3F5F7;
3336         padding: 5pt;
3337         font-family: courier, monospace;
3338   }
3339   table { border-collapse: collapse; }
3340   td, th {
3341         vertical-align: top;
3342         <!--border: 1pt solid #ADB9CC;-->
3343   }
3344 </style>"
3345   "The default style specification for exported HTML files.
3346 Since there are different ways of setting style information, this variable
3347 needs to contain the full HTML structure to provide a style, including the
3348 surrounding HTML tags.  The style specifications should include definitions
3349 for new classes todo, done, title, and deadline.  For example, legal values
3350 would be:
3352    <style type=\"text/css\">
3353        p { font-weight: normal; color: gray; }
3354        h1 { color: black; }
3355       .title { text-align: center; }
3356       .todo, .deadline { color: red; }
3357       .done { color: green; }
3358    </style>
3360 or, if you want to keep the style in a file,
3362    <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3364 As the value of this option simply gets inserted into the HTML <head> header,
3365 you can \"misuse\" it to add arbitrary text to the header."
3366   :group 'org-export-html
3367   :type 'string)
3370 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3371   "Format for typesetting the document title in HTML export."
3372   :group 'org-export-html
3373   :type 'string)
3375 (defcustom org-export-html-toplevel-hlevel 2
3376   "The <H> level for level 1 headings in HTML export."
3377   :group 'org-export-html
3378   :type 'string)
3380 (defcustom org-export-html-link-org-files-as-html t
3381   "Non-nil means, make file links to `file.org' point to `file.html'.
3382 When org-mode is exporting an org-mode file to HTML, links to
3383 non-html files are directly put into a href tag in HTML.
3384 However, links to other Org-mode files (recognized by the
3385 extension `.org.) should become links to the corresponding html
3386 file, assuming that the linked org-mode file will also be
3387 converted to HTML.
3388 When nil, the links still point to the plain `.org' file."
3389   :group 'org-export-html
3390   :type 'boolean)
3392 (defcustom org-export-html-inline-images 'maybe
3393   "Non-nil means, inline images into exported HTML pages.
3394 This is done using an <img> tag.  When nil, an anchor with href is used to
3395 link to the image.  If this option is `maybe', then images in links with
3396 an empty description will be inlined, while images with a description will
3397 be linked only."
3398   :group 'org-export-html
3399   :type '(choice (const :tag "Never" nil)
3400                  (const :tag "Always" t)
3401                  (const :tag "When there is no description" maybe)))
3403 ;; FIXME: rename
3404 (defcustom org-export-html-expand t
3405   "Non-nil means, for HTML export, treat @<...> as HTML tag.
3406 When nil, these tags will be exported as plain text and therefore
3407 not be interpreted by a browser.
3409 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3410   :group 'org-export-html
3411   :type 'boolean)
3413 (defcustom org-export-html-table-tag
3414   "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3415   "The HTML tag that is used to start a table.
3416 This must be a <table> tag, but you may change the options like
3417 borders and spacing."
3418   :group 'org-export-html
3419   :type 'string)
3421 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3422   "The opening tag for table header fields.
3423 This is customizable so that alignment options can be specified."
3424   :group 'org-export-tables
3425   :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3427 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3428   "The opening tag for table data fields.
3429 This is customizable so that alignment options can be specified."
3430   :group 'org-export-tables
3431   :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3433 (defcustom org-export-html-with-timestamp nil
3434   "If non-nil, write `org-export-html-html-helper-timestamp'
3435 into the exported HTML text.  Otherwise, the buffer will just be saved
3436 to a file."
3437   :group 'org-export-html
3438   :type 'boolean)
3440 (defcustom org-export-html-html-helper-timestamp
3441   "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3442   "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3443   :group 'org-export-html
3444   :type 'string)
3446 (defgroup org-export-icalendar nil
3447   "Options specific for iCalendar export of Org-mode files."
3448   :tag "Org Export iCalendar"
3449   :group 'org-export)
3451 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3452   "The file name for the iCalendar file covering all agenda files.
3453 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3454 The file name should be absolute, the file will be overwritten without warning."
3455   :group 'org-export-icalendar
3456   :type 'file)
3458 (defcustom org-icalendar-include-todo nil
3459   "Non-nil means, export to iCalendar files should also cover TODO items."
3460   :group 'org-export-icalendar
3461   :type '(choice
3462           (const :tag "None" nil)
3463           (const :tag "Unfinished" t)
3464           (const :tag "All" all)))
3466 (defcustom org-icalendar-include-sexps t
3467   "Non-nil means, export to iCalendar files should also cover sexp entries.
3468 These are entries like in the diary, but directly in an Org-mode file."
3469   :group 'org-export-icalendar
3470   :type 'boolean)
3472 (defcustom org-icalendar-include-body 100
3473   "Amount of text below headline to be included in iCalendar export.
3474 This is a number of characters that should maximally be included.
3475 Properties, scheduling and clocking lines will always be removed.
3476 The text will be inserted into the DESCRIPTION field."
3477   :group 'org-export-icalendar
3478   :type '(choice
3479           (const :tag "Nothing" nil)
3480           (const :tag "Everything" t)
3481           (integer :tag "Max characters")))
3483 (defcustom org-icalendar-combined-name "OrgMode"
3484   "Calendar name for the combined iCalendar representing all agenda files."
3485   :group 'org-export-icalendar
3486   :type 'string)
3488 (defgroup org-font-lock nil
3489   "Font-lock settings for highlighting in Org-mode."
3490   :tag "Org Font Lock"
3491   :group 'org)
3493 (defcustom org-level-color-stars-only nil
3494   "Non-nil means fontify only the stars in each headline.
3495 When nil, the entire headline is fontified.
3496 Changing it requires restart of `font-lock-mode' to become effective
3497 also in regions already fontified."
3498   :group 'org-font-lock
3499   :type 'boolean)
3501 (defcustom org-hide-leading-stars nil
3502   "Non-nil means, hide the first N-1 stars in a headline.
3503 This works by using the face `org-hide' for these stars.  This
3504 face is white for a light background, and black for a dark
3505 background.  You may have to customize the face `org-hide' to
3506 make this work.
3507 Changing it requires restart of `font-lock-mode' to become effective
3508 also in regions already fontified.
3509 You may also set this on a per-file basis by adding one of the following
3510 lines to the buffer:
3512    #+STARTUP: hidestars
3513    #+STARTUP: showstars"
3514   :group 'org-font-lock
3515   :type 'boolean)
3517 (defcustom org-fontify-done-headline nil
3518   "Non-nil means, change the face of a headline if it is marked DONE.
3519 Normally, only the TODO/DONE keyword indicates the state of a headline.
3520 When this is non-nil, the headline after the keyword is set to the
3521 `org-headline-done' as an additional indication."
3522   :group 'org-font-lock
3523   :type 'boolean)
3525 (defcustom org-fontify-emphasized-text t
3526   "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3527 Changing this variable requires a restart of Emacs to take effect."
3528   :group 'org-font-lock
3529   :type 'boolean)
3531 (defcustom org-highlight-latex-fragments-and-specials nil
3532   "Non-nil means, fontify what is treated specially by the exporters."
3533   :group 'org-font-lock
3534   :type 'boolean)
3536 (defcustom org-hide-emphasis-markers nil
3537   "Non-nil mean font-lock should hide the emphasis marker characters."
3538   :group 'org-font-lock
3539   :type 'boolean)
3541 (defvar org-emph-re nil
3542   "Regular expression for matching emphasis.")
3543 (defvar org-verbatim-re nil
3544   "Regular expression for matching verbatim text.")
3545 (defvar org-emphasis-regexp-components) ; defined just below
3546 (defvar org-emphasis-alist) ; defined just below
3547 (defun org-set-emph-re (var val)
3548   "Set variable and compute the emphasis regular expression."
3549   (set var val)
3550   (when (and (boundp 'org-emphasis-alist)
3551              (boundp 'org-emphasis-regexp-components)
3552              org-emphasis-alist org-emphasis-regexp-components)
3553     (let* ((e org-emphasis-regexp-components)
3554            (pre (car e))
3555            (post (nth 1 e))
3556            (border (nth 2 e))
3557            (body (nth 3 e))
3558            (nl (nth 4 e))
3559            (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3560            (body1 (concat body "*?"))
3561            (markers (mapconcat 'car org-emphasis-alist ""))
3562            (vmarkers (mapconcat
3563                       (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3564                       org-emphasis-alist "")))
3565       ;; make sure special characters appear at the right position in the class
3566       (if (string-match "\\^" markers)
3567           (setq markers (concat (replace-match "" t t markers) "^")))
3568       (if (string-match "-" markers)
3569           (setq markers (concat (replace-match "" t t markers) "-")))
3570       (if (string-match "\\^" vmarkers)
3571           (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3572       (if (string-match "-" vmarkers)
3573           (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3574       (if (> nl 0)
3575           (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3576                               (int-to-string nl) "\\}")))
3577       ;; Make the regexp
3578       (setq org-emph-re
3579             (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3580                     "\\("
3581                     "\\([" markers "]\\)"
3582                     "\\("
3583                     "[^" border "]\\|"
3584                     "[^" border (if (and nil stacked) markers) "]"
3585                     body1
3586                     "[^" border (if (and nil stacked) markers) "]"
3587                     "\\)"
3588                     "\\3\\)"
3589                     "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3590       (setq org-verbatim-re
3591             (concat "\\([" pre "]\\|^\\)"
3592                     "\\("
3593                     "\\([" vmarkers "]\\)"
3594                     "\\("
3595                     "[^" border "]\\|"
3596                     "[^" border "]"
3597                     body1
3598                     "[^" border "]"
3599                     "\\)"
3600                     "\\3\\)"
3601                     "\\([" post  "]\\|$\\)")))))
3603 (defcustom org-emphasis-regexp-components
3604   '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3605   "Components used to build the regular expression for emphasis.
3606 This is a list with 6 entries.  Terminology:  In an emphasis string
3607 like \" *strong word* \", we call the initial space PREMATCH, the final
3608 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3609 and \"trong wor\" is the body.  The different components in this variable
3610 specify what is allowed/forbidden in each part:
3612 pre          Chars allowed as prematch.  Beginning of line will be allowed too.
3613 post         Chars allowed as postmatch.  End of line will be allowed too.
3614 border       The chars *forbidden* as border characters.
3615 body-regexp  A regexp like \".\" to match a body character.  Don't use
3616              non-shy groups here, and don't allow newline here.
3617 newline      The maximum number of newlines allowed in an emphasis exp.
3619 Use customize to modify this, or restart Emacs after changing it."
3620   :group 'org-font-lock
3621   :set 'org-set-emph-re
3622   :type '(list
3623           (sexp    :tag "Allowed chars in pre      ")
3624           (sexp    :tag "Allowed chars in post     ")
3625           (sexp    :tag "Forbidden chars in border ")
3626           (sexp    :tag "Regexp for body           ")
3627           (integer :tag "number of newlines allowed")
3628           (option (boolean :tag "Stacking (DISABLED)       "))))
3630 (defcustom org-emphasis-alist
3631   '(("*" bold "<b>" "</b>")
3632     ("/" italic "<i>" "</i>")
3633     ("_" underline "<u>" "</u>")
3634     ("=" org-code "<code>" "</code>" verbatim)
3635     ("~" org-verbatim "" "" verbatim)
3636     ("+" (:strike-through t) "<del>" "</del>")
3637     )
3638   "Special syntax for emphasized text.
3639 Text starting and ending with a special character will be emphasized, for
3640 example *bold*, _underlined_ and /italic/.  This variable sets the marker
3641 characters, the face to be used by font-lock for highlighting in Org-mode
3642 Emacs buffers, and the HTML tags to be used for this.
3643 Use customize to modify this, or restart Emacs after changing it."
3644   :group 'org-font-lock
3645   :set 'org-set-emph-re
3646   :type '(repeat
3647           (list
3648            (string :tag "Marker character")
3649            (choice
3650             (face :tag "Font-lock-face")
3651             (plist :tag "Face property list"))
3652            (string :tag "HTML start tag")
3653            (string :tag "HTML end tag")
3654            (option (const verbatim)))))
3656 ;;; The faces
3658 (defgroup org-faces nil
3659   "Faces in Org-mode."
3660   :tag "Org Faces"
3661   :group 'org-font-lock)
3663 (defun org-compatible-face (inherits specs)
3664   "Make a compatible face specification.
3665 If INHERITS is an existing face and if the Emacs version supports it,
3666 just inherit the face.  If not, use SPECS to define the face.
3667 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3668 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3669 to the top of the list.  The `min-colors' attribute will be removed from
3670 any other entries, and any resulting duplicates will be removed entirely."
3671   (cond
3672    ((and inherits (facep inherits)
3673          (not (featurep 'xemacs)) (> emacs-major-version 22))
3674     ;; In Emacs 23, we use inheritance where possible.
3675     ;; We only do this in Emacs 23, because only there the outline
3676     ;; faces have been changed to the original org-mode-level-faces.
3677     (list (list t :inherit inherits)))
3678    ((or (featurep 'xemacs) (< emacs-major-version 22))
3679     ;; These do not understand the `min-colors' attribute.
3680     (let (r e a)
3681       (while (setq e (pop specs))
3682         (cond
3683          ((memq (car e) '(t default)) (push e r))
3684          ((setq a (member '(min-colors 8) (car e)))
3685           (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3686                                (cdr e)))))
3687          ((setq a (assq 'min-colors (car e)))
3688           (setq e (cons (delq a (car e)) (cdr e)))
3689           (or (assoc (car e) r) (push e r)))
3690          (t (or (assoc (car e) r) (push e r)))))
3691       (nreverse r)))
3692    (t specs)))
3693 (put 'org-compatible-face 'lisp-indent-function 1)
3695 (defface org-hide
3696   '((((background light)) (:foreground "white"))
3697     (((background dark)) (:foreground "black")))
3698   "Face used to hide leading stars in headlines.
3699 The forground color of this face should be equal to the background
3700 color of the frame."
3701   :group 'org-faces)
3703 (defface org-level-1 ;; font-lock-function-name-face
3704   (org-compatible-face 'outline-1
3705     '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3706       (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3707       (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3708       (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3709       (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3710       (t (:bold t))))
3711   "Face used for level 1 headlines."
3712   :group 'org-faces)
3714 (defface org-level-2 ;; font-lock-variable-name-face
3715   (org-compatible-face 'outline-2
3716     '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3717       (((class color) (min-colors 16) (background dark))  (:foreground "LightGoldenrod"))
3718       (((class color) (min-colors 8)  (background light)) (:foreground "yellow"))
3719       (((class color) (min-colors 8)  (background dark))  (:foreground "yellow" :bold t))
3720       (t (:bold t))))
3721   "Face used for level 2 headlines."
3722   :group 'org-faces)
3724 (defface org-level-3 ;; font-lock-keyword-face
3725   (org-compatible-face 'outline-3
3726     '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3727       (((class color) (min-colors 88) (background dark))  (:foreground "Cyan1"))
3728       (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3729       (((class color) (min-colors 16) (background dark))  (:foreground "Cyan"))
3730       (((class color) (min-colors 8)  (background light)) (:foreground "purple" :bold t))
3731       (((class color) (min-colors 8)  (background dark))  (:foreground "cyan" :bold t))
3732       (t (:bold t))))
3733   "Face used for level 3 headlines."
3734   :group 'org-faces)
3736 (defface org-level-4   ;; font-lock-comment-face
3737   (org-compatible-face 'outline-4
3738     '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3739       (((class color) (min-colors 88) (background dark))  (:foreground "chocolate1"))
3740       (((class color) (min-colors 16) (background light)) (:foreground "red"))
3741       (((class color) (min-colors 16) (background dark))  (:foreground "red1"))
3742       (((class color) (min-colors 8) (background light))  (:foreground "red" :bold t))
3743       (((class color) (min-colors 8) (background dark))   (:foreground "red" :bold t))
3744       (t (:bold t))))
3745   "Face used for level 4 headlines."
3746   :group 'org-faces)
3748 (defface org-level-5 ;; font-lock-type-face
3749   (org-compatible-face 'outline-5
3750     '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3751       (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3752       (((class color) (min-colors 8)) (:foreground "green"))))
3753   "Face used for level 5 headlines."
3754   :group 'org-faces)
3756 (defface org-level-6 ;; font-lock-constant-face
3757   (org-compatible-face 'outline-6
3758     '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3759       (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3760       (((class color) (min-colors 8)) (:foreground "magenta"))))
3761   "Face used for level 6 headlines."
3762   :group 'org-faces)
3764 (defface org-level-7 ;; font-lock-builtin-face
3765   (org-compatible-face 'outline-7
3766     '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3767       (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3768       (((class color) (min-colors 8)) (:foreground "blue"))))
3769   "Face used for level 7 headlines."
3770   :group 'org-faces)
3772 (defface org-level-8 ;; font-lock-string-face
3773   (org-compatible-face 'outline-8
3774     '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3775       (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3776       (((class color) (min-colors 8)) (:foreground "green"))))
3777   "Face used for level 8 headlines."
3778   :group 'org-faces)
3780 (defface org-special-keyword ;; font-lock-string-face
3781   (org-compatible-face nil
3782     '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3783       (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3784       (t (:italic t))))
3785   "Face used for special keywords."
3786   :group 'org-faces)
3788 (defface org-drawer ;; font-lock-function-name-face
3789   (org-compatible-face nil
3790     '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3791       (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3792       (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3793       (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3794       (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3795       (t (:bold t))))
3796   "Face used for drawers."
3797   :group 'org-faces)
3799 (defface org-property-value nil
3800   "Face used for the value of a property."
3801   :group 'org-faces)
3803 (defface org-column
3804   (org-compatible-face nil
3805     '((((class color) (min-colors 16) (background light))
3806        (:background "grey90"))
3807       (((class color) (min-colors 16) (background dark))
3808        (:background "grey30"))
3809       (((class color) (min-colors 8))
3810        (:background "cyan" :foreground "black"))
3811       (t (:inverse-video t))))
3812   "Face for column display of entry properties."
3813   :group 'org-faces)
3815 (when (fboundp 'set-face-attribute)
3816   ;; Make sure that a fixed-width face is used when we have a column table.
3817   (set-face-attribute 'org-column nil
3818                       :height (face-attribute 'default :height)
3819                       :family (face-attribute 'default :family)))
3821 (defface org-warning
3822   (org-compatible-face 'font-lock-warning-face
3823     '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3824       (((class color) (min-colors 16) (background dark))  (:foreground "Pink" :bold t))
3825       (((class color) (min-colors 8)  (background light)) (:foreground "red"  :bold t))
3826       (((class color) (min-colors 8)  (background dark))  (:foreground "red"  :bold t))
3827       (t (:bold t))))
3828   "Face for deadlines and TODO keywords."
3829   :group 'org-faces)
3831 (defface org-archived    ; similar to shadow
3832   (org-compatible-face 'shadow
3833     '((((class color grayscale) (min-colors 88) (background light))
3834        (:foreground "grey50"))
3835       (((class color grayscale) (min-colors 88) (background dark))
3836        (:foreground "grey70"))
3837       (((class color) (min-colors 8) (background light))
3838        (:foreground "green"))
3839       (((class color) (min-colors 8) (background dark))
3840        (:foreground "yellow"))))
3841   "Face for headline with the ARCHIVE tag."
3842   :group 'org-faces)
3844 (defface org-link
3845   '((((class color) (background light)) (:foreground "Purple" :underline t))
3846     (((class color) (background dark)) (:foreground "Cyan" :underline t))
3847     (t (:underline t)))
3848   "Face for links."
3849   :group 'org-faces)
3851 (defface org-ellipsis
3852   '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
3853     (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
3854     (t (:strike-through t)))
3855   "Face for the ellipsis in folded text."
3856   :group 'org-faces)
3858 (defface org-target
3859   '((((class color) (background light)) (:underline t))
3860     (((class color) (background dark)) (:underline t))
3861     (t (:underline t)))
3862   "Face for links."
3863   :group 'org-faces)
3865 (defface org-date
3866   '((((class color) (background light)) (:foreground "Purple" :underline t))
3867     (((class color) (background dark)) (:foreground "Cyan" :underline t))
3868     (t (:underline t)))
3869   "Face for links."
3870   :group 'org-faces)
3872 (defface org-sexp-date
3873   '((((class color) (background light)) (:foreground "Purple"))
3874     (((class color) (background dark)) (:foreground "Cyan"))
3875     (t (:underline t)))
3876   "Face for links."
3877   :group 'org-faces)
3879 (defface org-tag
3880   '((t (:bold t)))
3881   "Face for tags."
3882   :group 'org-faces)
3884 (defface org-todo ; font-lock-warning-face
3885   (org-compatible-face nil
3886     '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3887       (((class color) (min-colors 16) (background dark))  (:foreground "Pink" :bold t))
3888       (((class color) (min-colors 8)  (background light)) (:foreground "red"  :bold t))
3889       (((class color) (min-colors 8)  (background dark))  (:foreground "red"  :bold t))
3890       (t (:inverse-video t :bold t))))
3891   "Face for TODO keywords."
3892   :group 'org-faces)
3894 (defface org-done ;; font-lock-type-face
3895   (org-compatible-face nil
3896     '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3897       (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3898       (((class color) (min-colors 8)) (:foreground "green"))
3899       (t (:bold t))))
3900   "Face used for todo keywords that indicate DONE items."
3901   :group 'org-faces)
3903 (defface org-headline-done ;; font-lock-string-face
3904   (org-compatible-face nil
3905     '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3906       (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3907       (((class color) (min-colors 8)  (background light)) (:bold nil))))
3908   "Face used to indicate that a headline is DONE.
3909 This face is only used if `org-fontify-done-headline' is set.  If applies
3910 to the part of the headline after the DONE keyword."
3911   :group 'org-faces)
3913 (defcustom org-todo-keyword-faces nil
3914   "Faces for specific TODO keywords.
3915 This is a list of cons cells, with TODO keywords in the car
3916 and faces in the cdr.  The face can be a symbol, or a property
3917 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3918   :group 'org-faces
3919   :group 'org-todo
3920   :type '(repeat
3921           (cons
3922            (string :tag "keyword")
3923            (sexp :tag "face"))))
3925 (defface org-table ;; font-lock-function-name-face
3926   (org-compatible-face nil
3927     '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3928       (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3929       (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3930       (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3931       (((class color) (min-colors 8)  (background light)) (:foreground "blue"))
3932       (((class color) (min-colors 8)  (background dark)))))
3933   "Face used for tables."
3934   :group 'org-faces)
3936 (defface org-formula
3937   (org-compatible-face nil
3938     '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3939       (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3940       (((class color) (min-colors 8)  (background light)) (:foreground "red"))
3941       (((class color) (min-colors 8)  (background dark)) (:foreground "red"))
3942       (t (:bold t :italic t))))
3943   "Face for formulas."
3944   :group 'org-faces)
3946 (defface org-code
3947   (org-compatible-face nil
3948     '((((class color grayscale) (min-colors 88) (background light))
3949        (:foreground "grey50"))
3950       (((class color grayscale) (min-colors 88) (background dark))
3951        (:foreground "grey70"))
3952       (((class color) (min-colors 8) (background light))
3953        (:foreground "green"))
3954       (((class color) (min-colors 8) (background dark))
3955        (:foreground "yellow"))))
3956   "Face for fixed-with text like code snippets."
3957   :group 'org-faces
3958   :version "22.1")
3960 (defface org-verbatim
3961   (org-compatible-face nil
3962     '((((class color grayscale) (min-colors 88) (background light))
3963        (:foreground "grey50" :underline t))
3964       (((class color grayscale) (min-colors 88) (background dark))
3965        (:foreground "grey70" :underline t))
3966       (((class color) (min-colors 8) (background light))
3967        (:foreground "green" :underline t))
3968       (((class color) (min-colors 8) (background dark))
3969        (:foreground "yellow" :underline t))))
3970   "Face for fixed-with text like code snippets."
3971   :group 'org-faces
3972   :version "22.1")
3974 (defface org-agenda-structure ;; font-lock-function-name-face
3975   (org-compatible-face nil
3976     '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3977       (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3978       (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3979       (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3980       (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3981       (t (:bold t))))
3982   "Face used in agenda for captions and dates."
3983   :group 'org-faces)
3985 (defface org-scheduled-today
3986   (org-compatible-face nil
3987     '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
3988       (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
3989       (((class color) (min-colors 8)) (:foreground "green"))
3990       (t (:bold t :italic t))))
3991   "Face for items scheduled for a certain day."
3992   :group 'org-faces)
3994 (defface org-scheduled-previously
3995   (org-compatible-face nil
3996     '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3997       (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3998       (((class color) (min-colors 8)  (background light)) (:foreground "red"))
3999       (((class color) (min-colors 8)  (background dark)) (:foreground "red" :bold t))
4000       (t (:bold t))))
4001   "Face for items scheduled previously, and not yet done."
4002   :group 'org-faces)
4004 (defface org-upcoming-deadline
4005   (org-compatible-face nil
4006     '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4007       (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4008       (((class color) (min-colors 8)  (background light)) (:foreground "red"))
4009       (((class color) (min-colors 8)  (background dark)) (:foreground "red" :bold t))
4010       (t (:bold t))))
4011   "Face for items scheduled previously, and not yet done."
4012   :group 'org-faces)
4014 (defcustom org-agenda-deadline-faces
4015   '((1.0 . org-warning)
4016     (0.5 . org-upcoming-deadline)
4017     (0.0 . default))
4018   "Faces for showing deadlines in the agenda.
4019 This is a list of cons cells.  The cdr of each cess is a face to be used,
4020 and it can also just be a like like '(:foreground \"yellow\").
4021 Each car is a fraction of the head-warning time that must have passed for
4022 this the face in the cdr to be used for display.  The numbers must be
4023 given in descending order.  The head-warning time is normally taken
4024 from `org-deadline-warning-days', but can also be specified in the deadline
4025 timestamp itself, like this:
4027    DEADLINE: <2007-08-13 Mon -8d>
4029 You may use d for days, w for weeks, m for months and y for years.  Months
4030 and years will only be treated in an approximate fashion (30.4 days for a
4031 month and 365.24 days for a year)."
4032   :group 'org-faces
4033   :group 'org-agenda-daily/weekly
4034   :type '(repeat
4035           (cons
4036            (number :tag "Fraction of head-warning time passed")
4037            (sexp :tag "Face"))))
4039 ;; FIXME: this is not a good face yet.
4040 (defface org-agenda-restriction-lock
4041   (org-compatible-face nil
4042     '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4043       (((class color) (min-colors 88) (background dark))  (:background "skyblue4"))
4044       (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4045       (((class color) (min-colors 16) (background dark))  (:background "skyblue4"))
4046       (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4047       (t (:inverse-video t))))
4048   "Face for showing the agenda restriction lock."
4049   :group 'org-faces)
4051 (defface org-time-grid ;; font-lock-variable-name-face
4052   (org-compatible-face nil
4053     '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4054       (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4055       (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4056   "Face used for time grids."
4057   :group 'org-faces)
4059 (defconst org-level-faces
4060   '(org-level-1 org-level-2 org-level-3 org-level-4
4061     org-level-5 org-level-6 org-level-7 org-level-8
4062     ))
4064 (defcustom org-n-level-faces (length org-level-faces)
4065   "The number different faces to be used for headlines.
4066 Org-mode defines 8 different headline faces, so this can be at most 8.
4067 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4068   :type 'number
4069   :group 'org-faces)
4071 ;;; Functions and variables from ther packages
4072 ;;  Declared here to avoid compiler warnings
4074 (eval-and-compile
4075   (unless (fboundp 'declare-function)
4076     (defmacro declare-function (fn file &optional arglist fileonly))))
4078 ;; XEmacs only
4079 (defvar outline-mode-menu-heading)
4080 (defvar outline-mode-menu-show)
4081 (defvar outline-mode-menu-hide)
4082 (defvar zmacs-regions) ; XEmacs regions
4084 ;; Emacs only
4085 (defvar mark-active)
4087 ;; Various packages
4088 ;; FIXME: get the argument lists for the UNKNOWN stuff
4089 (declare-function add-to-diary-list "diary-lib"
4090                   (date string specifier &optional marker globcolor literal))
4091 (declare-function table--at-cell-p "table" (position &optional object at-column))
4092 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4093 (declare-function Info-goto-node "info" (nodename &optional fork))
4094 (declare-function bbdb "ext:bbdb-com" (string elidep))
4095 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4096 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4097 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4098 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4099 (declare-function bbdb-record-name "ext:bbdb" (record))
4100 (declare-function bibtex-beginning-of-entry "bibtex" ())
4101 (declare-function bibtex-generate-autokey "bibtex" ())
4102 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4103 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4104 (defvar calc-embedded-close-formula)
4105 (defvar calc-embedded-open-formula)
4106 (declare-function calendar-astro-date-string    "cal-julian" (&optional date))
4107 (declare-function calendar-bahai-date-string    "cal-bahai"  (&optional date))
4108 (declare-function calendar-check-holidays       "holidays"   (date))
4109 (declare-function calendar-chinese-date-string  "cal-china"  (&optional date))
4110 (declare-function calendar-coptic-date-string   "cal-coptic" (&optional date))
4111 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4112 (declare-function calendar-forward-day          "cal-move"   (arg))
4113 (declare-function calendar-french-date-string   "cal-french" (&optional date))
4114 (declare-function calendar-goto-date            "cal-move"   (date))
4115 (declare-function calendar-goto-today           "cal-move"   ())
4116 (declare-function calendar-hebrew-date-string   "cal-hebrew" (&optional date))
4117 (declare-function calendar-islamic-date-string  "cal-islam"  (&optional date))
4118 (declare-function calendar-iso-date-string      "cal-iso"    (&optional date))
4119 (declare-function calendar-julian-date-string   "cal-julian" (&optional date))
4120 (declare-function calendar-mayan-date-string    "cal-mayan"  (&optional date))
4121 (declare-function calendar-persian-date-string  "cal-persia" (&optional date))
4122 (defvar calendar-mode-map)
4123 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4124 (declare-function cdlatex-tab "ext:cdlatex" ())
4125 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4126 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4127 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4128 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4129 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4130 (defvar font-lock-unfontify-region-function)
4131 (declare-function gnus-article-show-summary "gnus-art" ())
4132 (declare-function gnus-summary-last-subject "gnus-sum" ())
4133 (defvar gnus-other-frame-object)
4134 (defvar gnus-group-name)
4135 (defvar gnus-article-current)
4136 (defvar Info-current-file)
4137 (defvar Info-current-node)
4138 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4139 (declare-function mh-find-path "mh-utils" ())
4140 (declare-function mh-get-header-field "mh-utils" (field))
4141 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4142 (declare-function mh-header-display "mh-show" ())
4143 (declare-function mh-index-previous-folder "mh-search" ())
4144 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4145 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4146 (declare-function mh-search-choose "mh-search" (&optional searcher))
4147 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4148 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4149 (declare-function mh-show-header-display "mh-show" t t)
4150 (declare-function mh-show-msg "mh-show" (msg))
4151 (declare-function mh-show-show "mh-show" t t)
4152 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4153 (defvar mh-progs)
4154 (defvar mh-current-folder)
4155 (defvar mh-show-folder-buffer)
4156 (defvar mh-index-folder)
4157 (defvar mh-searcher)
4158 (declare-function org-export-latex-cleaned-string "org-export-latex" (&optional commentsp))
4159 (declare-function parse-time-string "parse-time" (string))
4160 (declare-function remember "remember" (&optional initial))
4161 (declare-function remember-buffer-desc "remember" ())
4162 (defvar remember-save-after-remembering)
4163 (defvar remember-data-file)
4164 (defvar remember-register)
4165 (defvar remember-buffer)
4166 (defvar remember-handler-functions)
4167 (defvar remember-annotation-functions)
4168 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4169 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4170 (declare-function rmail-what-message "rmail" ())
4171 (defvar texmathp-why)
4172 (declare-function vm-beginning-of-message "ext:vm-page" ())
4173 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4174 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4175 (declare-function vm-isearch-narrow "ext:vm-search" ())
4176 (declare-function vm-isearch-update "ext:vm-search" ())
4177 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4178 (declare-function vm-su-message-id "ext:vm-summary" (m))
4179 (declare-function vm-su-subject "ext:vm-summary" (m))
4180 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4181 (defvar vm-message-pointer)
4182 (defvar vm-folder-directory)
4183 (defvar w3m-current-url)
4184 (defvar w3m-current-title)
4185 ;; backward compatibility to old version of wl
4186 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4187 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4188 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4189 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4190 (declare-function wl-summary-line-from "ext:wl-summary" ())
4191 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4192 (declare-function wl-summary-message-number "ext:wl-summary" ())
4193 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4194 (defvar wl-summary-buffer-elmo-folder)
4195 (defvar wl-summary-buffer-folder-name)
4196 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4198 (defvar org-latex-regexps)
4199 (defvar constants-unit-system)
4201 ;;; Variables for pre-computed regular expressions, all buffer local
4203 (defvar org-drawer-regexp nil
4204   "Matches first line of a hidden block.")
4205 (make-variable-buffer-local 'org-drawer-regexp)
4206 (defvar org-todo-regexp nil
4207   "Matches any of the TODO state keywords.")
4208 (make-variable-buffer-local 'org-todo-regexp)
4209 (defvar org-not-done-regexp nil
4210   "Matches any of the TODO state keywords except the last one.")
4211 (make-variable-buffer-local 'org-not-done-regexp)
4212 (defvar org-todo-line-regexp nil
4213   "Matches a headline and puts TODO state into group 2 if present.")
4214 (make-variable-buffer-local 'org-todo-line-regexp)
4215 (defvar org-complex-heading-regexp nil
4216   "Matches a headline and puts everything into groups:
4217 group 1: the stars
4218 group 2: The todo keyword, maybe
4219 group 3: Priority cookie
4220 group 4: True headline
4221 group 5: Tags")
4222 (make-variable-buffer-local 'org-complex-heading-regexp)
4223 (defvar org-todo-line-tags-regexp nil
4224   "Matches a headline and puts TODO state into group 2 if present.
4225 Also put tags into group 4 if tags are present.")
4226 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4227 (defvar org-nl-done-regexp nil
4228   "Matches newline followed by a headline with the DONE keyword.")
4229 (make-variable-buffer-local 'org-nl-done-regexp)
4230 (defvar org-looking-at-done-regexp nil
4231   "Matches the DONE keyword a point.")
4232 (make-variable-buffer-local 'org-looking-at-done-regexp)
4233 (defvar org-ds-keyword-length 12
4234   "Maximum length of the Deadline and SCHEDULED keywords.")
4235 (make-variable-buffer-local 'org-ds-keyword-length)
4236 (defvar org-deadline-regexp nil
4237   "Matches the DEADLINE keyword.")
4238 (make-variable-buffer-local 'org-deadline-regexp)
4239 (defvar org-deadline-time-regexp nil
4240   "Matches the DEADLINE keyword together with a time stamp.")
4241 (make-variable-buffer-local 'org-deadline-time-regexp)
4242 (defvar org-deadline-line-regexp nil
4243   "Matches the DEADLINE keyword and the rest of the line.")
4244 (make-variable-buffer-local 'org-deadline-line-regexp)
4245 (defvar org-scheduled-regexp nil
4246   "Matches the SCHEDULED keyword.")
4247 (make-variable-buffer-local 'org-scheduled-regexp)
4248 (defvar org-scheduled-time-regexp nil
4249   "Matches the SCHEDULED keyword together with a time stamp.")
4250 (make-variable-buffer-local 'org-scheduled-time-regexp)
4251 (defvar org-closed-time-regexp nil
4252   "Matches the CLOSED keyword together with a time stamp.")
4253 (make-variable-buffer-local 'org-closed-time-regexp)
4255 (defvar org-keyword-time-regexp nil
4256   "Matches any of the 4 keywords, together with the time stamp.")
4257 (make-variable-buffer-local 'org-keyword-time-regexp)
4258 (defvar org-keyword-time-not-clock-regexp nil
4259   "Matches any of the 3 keywords, together with the time stamp.")
4260 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4261 (defvar org-maybe-keyword-time-regexp nil
4262   "Matches a timestamp, possibly preceeded by a keyword.")
4263 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4264 (defvar org-planning-or-clock-line-re nil
4265   "Matches a line with planning or clock info.")
4266 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4268 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4269                                    rear-nonsticky t mouse-map t fontified t)
4270   "Properties to remove when a string without properties is wanted.")
4272 (defsubst org-match-string-no-properties (num &optional string)
4273   (if (featurep 'xemacs)
4274       (let ((s (match-string num string)))
4275         (remove-text-properties 0 (length s) org-rm-props s)
4276         s)
4277     (match-string-no-properties num string)))
4279 (defsubst org-no-properties (s)
4280   (if (fboundp 'set-text-properties)
4281       (set-text-properties 0 (length s) nil s)
4282     (remove-text-properties 0 (length s) org-rm-props s))
4283   s)
4285 (defsubst org-get-alist-option (option key)
4286   (cond ((eq key t) t)
4287         ((eq option t) t)
4288         ((assoc key option) (cdr (assoc key option)))
4289         (t (cdr (assq 'default option)))))
4291 (defsubst org-inhibit-invisibility ()
4292   "Modified `buffer-invisibility-spec' for Emacs 21.
4293 Some ops with invisible text do not work correctly on Emacs 21.  For these
4294 we turn off invisibility temporarily.  Use this in a `let' form."
4295   (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4297 (defsubst org-set-local (var value)
4298   "Make VAR local in current buffer and set it to VALUE."
4299   (set (make-variable-buffer-local var) value))
4301 (defsubst org-mode-p ()
4302   "Check if the current buffer is in Org-mode."
4303   (eq major-mode 'org-mode))
4305 (defsubst org-last (list)
4306   "Return the last element of LIST."
4307   (car (last list)))
4309 (defun org-let (list &rest body)
4310   (eval (cons 'let (cons list body))))
4311 (put 'org-let 'lisp-indent-function 1)
4313 (defun org-let2 (list1 list2 &rest body)
4314   (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4315 (put 'org-let2 'lisp-indent-function 2)
4316 (defconst org-startup-options
4317   '(("fold" org-startup-folded t)
4318     ("overview" org-startup-folded t)
4319     ("nofold" org-startup-folded nil)
4320     ("showall" org-startup-folded nil)
4321     ("content" org-startup-folded content)
4322     ("hidestars" org-hide-leading-stars t)
4323     ("showstars" org-hide-leading-stars nil)
4324     ("odd" org-odd-levels-only t)
4325     ("oddeven" org-odd-levels-only nil)
4326     ("align" org-startup-align-all-tables t)
4327     ("noalign" org-startup-align-all-tables nil)
4328     ("customtime" org-display-custom-times t)
4329     ("logging" org-log-done t)
4330     ("logdone" org-log-done t)
4331     ("nologging" org-log-done nil)
4332     ("lognotedone" org-log-done done push)
4333     ("lognotestate" org-log-done state push)
4334     ("lognoteclock-out" org-log-done clock-out push)
4335     ("logrepeat" org-log-repeat t)
4336     ("nologrepeat" org-log-repeat nil)
4337     ("constcgs" constants-unit-system cgs)
4338     ("constSI" constants-unit-system SI))
4339   "Variable associated with STARTUP options for org-mode.
4340 Each element is a list of three items: The startup options as written
4341 in the #+STARTUP line, the corresponding variable, and the value to
4342 set this variable to if the option is found.  An optional forth element PUSH
4343 means to push this value onto the list in the variable.")
4345 (defun org-set-regexps-and-options ()
4346   "Precompute regular expressions for current buffer."
4347   (when (org-mode-p)
4348     (org-set-local 'org-todo-kwd-alist nil)
4349     (org-set-local 'org-todo-key-alist nil)
4350     (org-set-local 'org-todo-key-trigger nil)
4351     (org-set-local 'org-todo-keywords-1 nil)
4352     (org-set-local 'org-done-keywords nil)
4353     (org-set-local 'org-todo-heads nil)
4354     (org-set-local 'org-todo-sets nil)
4355     (org-set-local 'org-todo-log-states nil)
4356     (let ((re (org-make-options-regexp
4357                '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4358                  "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4359                  "CONSTANTS" "PROPERTY" "DRAWERS")))
4360           (splitre "[ \t]+")
4361           kwds kws0 kwsa key value cat arch tags const links hw dws
4362           tail sep kws1 prio props drawers
4363           ex log)
4364       (save-excursion
4365         (save-restriction
4366           (widen)
4367           (goto-char (point-min))
4368           (while (re-search-forward re nil t)
4369             (setq key (match-string 1) value (org-match-string-no-properties 2))
4370             (cond
4371              ((equal key "CATEGORY")
4372               (if (string-match "[ \t]+$" value)
4373                   (setq value (replace-match "" t t value)))
4374               (setq cat value))
4375              ((member key '("SEQ_TODO" "TODO"))
4376               (push (cons 'sequence (org-split-string value splitre)) kwds))
4377              ((equal key "TYP_TODO")
4378               (push (cons 'type (org-split-string value splitre)) kwds))
4379              ((equal key "TAGS")
4380               (setq tags (append tags (org-split-string value splitre))))
4381              ((equal key "COLUMNS")
4382               (org-set-local 'org-columns-default-format value))
4383              ((equal key "LINK")
4384               (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4385                 (push (cons (match-string 1 value)
4386                             (org-trim (match-string 2 value)))
4387                       links)))
4388              ((equal key "PRIORITIES")
4389               (setq prio (org-split-string value " +")))
4390              ((equal key "PROPERTY")
4391               (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4392                 (push (cons (match-string 1 value) (match-string 2 value))
4393                       props)))
4394              ((equal key "DRAWERS")
4395               (setq drawers (org-split-string value splitre)))
4396              ((equal key "CONSTANTS")
4397               (setq const (append const (org-split-string value splitre))))
4398              ((equal key "STARTUP")
4399               (let ((opts (org-split-string value splitre))
4400                     l var val)
4401                 (while (setq l (pop opts))
4402                   (when (setq l (assoc l org-startup-options))
4403                     (setq var (nth 1 l) val (nth 2 l))
4404                     (if (not (nth 3 l))
4405                         (set (make-local-variable var) val)
4406                       (if (not (listp (symbol-value var)))
4407                           (set (make-local-variable var) nil))
4408                       (set (make-local-variable var) (symbol-value var))
4409                       (add-to-list var val))))))
4410              ((equal key "ARCHIVE")
4411               (string-match " *$" value)
4412               (setq arch (replace-match "" t t value))
4413               (remove-text-properties 0 (length arch)
4414                                       '(face t fontified t) arch)))
4415             )))
4416       (when cat
4417         (org-set-local 'org-category (intern cat))
4418         (push (cons "CATEGORY" cat) props))
4419       (when prio
4420         (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4421         (setq prio (mapcar 'string-to-char prio))
4422         (org-set-local 'org-highest-priority (nth 0 prio))
4423         (org-set-local 'org-lowest-priority  (nth 1 prio))
4424         (org-set-local 'org-default-priority (nth 2 prio)))
4425       (and props (org-set-local 'org-local-properties (nreverse props)))
4426       (and drawers (org-set-local 'org-drawers drawers))
4427       (and arch (org-set-local 'org-archive-location arch))
4428       (and links (setq org-link-abbrev-alist-local (nreverse links)))
4429       ;; Process the TODO keywords
4430       (unless kwds
4431         ;; Use the global values as if they had been given locally.
4432         (setq kwds (default-value 'org-todo-keywords))
4433         (if (stringp (car kwds))
4434             (setq kwds (list (cons org-todo-interpretation
4435                                    (default-value 'org-todo-keywords)))))
4436         (setq kwds (reverse kwds)))
4437       (setq kwds (nreverse kwds))
4438       (let (inter kws kw)
4439         (while (setq kws (pop kwds))
4440           (setq inter (pop kws) sep (member "|" kws)
4441                 kws0 (delete "|" (copy-sequence kws))
4442                 kwsa nil
4443                 kws1 (mapcar
4444                       (lambda (x)
4445                         (if (string-match "^\\(.*?\\)\\(?:(\\(..?\\))\\)?$" x)
4446                             (progn
4447                               (setq kw (match-string 1 x)
4448                                     ex (and (match-end 2) (match-string 2 x))
4449                                     log (and ex (string-match "@" ex))
4450                                     key (and ex (substring ex 0 1)))
4451                               (if (equal key "@") (setq key nil))
4452                               (push (cons kw (and key (string-to-char key))) kwsa)
4453                               (and log (push kw org-todo-log-states))
4454                               kw)
4455                           (error "Invalid TODO keyword %s" x)))
4456                       kws0)
4457                 kwsa (if kwsa (append '((:startgroup))
4458                                       (nreverse kwsa)
4459                                       '((:endgroup))))
4460                 hw (car kws1)
4461                 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4462                 tail (list inter hw (car dws) (org-last dws)))
4463           (add-to-list 'org-todo-heads hw 'append)
4464           (push kws1 org-todo-sets)
4465           (setq org-done-keywords (append org-done-keywords dws nil))
4466           (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4467           (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4468           (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4469         (setq org-todo-sets (nreverse org-todo-sets)
4470               org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4471               org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4472               org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4473       ;; Process the constants
4474       (when const
4475         (let (e cst)
4476           (while (setq e (pop const))
4477             (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4478                 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4479           (setq org-table-formula-constants-local cst)))
4481       ;; Process the tags.
4482       (when tags
4483         (let (e tgs)
4484           (while (setq e (pop tags))
4485             (cond
4486              ((equal e "{") (push '(:startgroup) tgs))
4487              ((equal e "}") (push '(:endgroup) tgs))
4488              ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4489               (push (cons (match-string 1 e)
4490                           (string-to-char (match-string 2 e)))
4491                     tgs))
4492              (t (push (list e) tgs))))
4493           (org-set-local 'org-tag-alist nil)
4494           (while (setq e (pop tgs))
4495             (or (and (stringp (car e))
4496                      (assoc (car e) org-tag-alist))
4497                 (push e org-tag-alist))))))
4499     ;; Compute the regular expressions and other local variables
4500     (if (not org-done-keywords)
4501         (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4502     (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4503                                           (length org-scheduled-string)))
4504           org-drawer-regexp
4505           (concat "^[ \t]*:\\("
4506                   (mapconcat 'regexp-quote org-drawers "\\|")
4507                   "\\):[ \t]*$")
4508           org-not-done-keywords
4509           (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4510           org-todo-regexp
4511           (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4512                                       "\\|") "\\)\\>")
4513           org-not-done-regexp
4514           (concat "\\<\\("
4515                   (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4516                   "\\)\\>")
4517           org-todo-line-regexp
4518           (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4519                   (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4520                   "\\)\\>\\)?[ \t]*\\(.*\\)")
4521           org-complex-heading-regexp
4522           (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4523                   (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4524                   "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4525                   "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4526           org-nl-done-regexp
4527           (concat "\n\\*+[ \t]+"
4528                   "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4529                   "\\)" "\\>")
4530           org-todo-line-tags-regexp
4531           (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4532                   (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4533                   (org-re
4534                    "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4535           org-looking-at-done-regexp
4536           (concat "^" "\\(?:"
4537                   (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4538                   "\\>")
4539           org-deadline-regexp (concat "\\<" org-deadline-string)
4540           org-deadline-time-regexp
4541           (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4542           org-deadline-line-regexp
4543           (concat "\\<\\(" org-deadline-string "\\).*")
4544           org-scheduled-regexp
4545           (concat "\\<" org-scheduled-string)
4546           org-scheduled-time-regexp
4547           (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4548           org-closed-time-regexp
4549           (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4550           org-keyword-time-regexp
4551           (concat "\\<\\(" org-scheduled-string
4552                   "\\|" org-deadline-string
4553                   "\\|" org-closed-string
4554                   "\\|" org-clock-string "\\)"
4555                   " *[[<]\\([^]>]+\\)[]>]")
4556           org-keyword-time-not-clock-regexp
4557           (concat "\\<\\(" org-scheduled-string
4558                   "\\|" org-deadline-string
4559                   "\\|" org-closed-string
4560                   "\\)"
4561                   " *[[<]\\([^]>]+\\)[]>]")
4562           org-maybe-keyword-time-regexp
4563           (concat "\\(\\<\\(" org-scheduled-string
4564                   "\\|" org-deadline-string
4565                   "\\|" org-closed-string
4566                   "\\|" org-clock-string "\\)\\)?"
4567                   " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4568           org-planning-or-clock-line-re
4569           (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4570                   "\\|" org-deadline-string
4571                   "\\|" org-closed-string "\\|" org-clock-string
4572                   "\\)\\>\\)")
4573           )
4574     (org-compute-latex-and-specials-regexp)
4575     (org-set-font-lock-defaults)))
4577 (defun org-remove-keyword-keys (list)
4578   (mapcar (lambda (x)
4579             (if (string-match "(..?)$" x)
4580                 (substring x 0 (match-beginning 0))
4581               x))
4582           list))
4584 ;; FIXME: this could be done much better, using second characters etc.
4585 (defun org-assign-fast-keys (alist)
4586   "Assign fast keys to a keyword-key alist.
4587 Respect keys that are already there."
4588   (let (new e k c c1 c2 (char ?a))
4589     (while (setq e (pop alist))
4590       (cond
4591        ((equal e '(:startgroup)) (push e new))
4592        ((equal e '(:endgroup)) (push e new))
4593        (t
4594         (setq k (car e) c2 nil)
4595         (if (cdr e)
4596             (setq c (cdr e))
4597           ;; automatically assign a character.
4598           (setq c1 (string-to-char
4599                     (downcase (substring
4600                                k (if (= (string-to-char k) ?@) 1 0)))))
4601           (if (or (rassoc c1 new) (rassoc c1 alist))
4602               (while (or (rassoc char new) (rassoc char alist))
4603                 (setq char (1+ char)))
4604             (setq c2 c1))
4605           (setq c (or c2 char)))
4606         (push (cons k c) new))))
4607     (nreverse new)))
4609 ;;; Some variables ujsed in various places
4611 (defvar org-window-configuration nil
4612   "Used in various places to store a window configuration.")
4613 (defvar org-finish-function nil
4614   "Function to be called when `C-c C-c' is used.
4615 This is for getting out of special buffers like remember.")
4618 ;; FIXME: Occasionally check by commenting these, to make sure
4619 ;;        no other functions uses these, forgetting to let-bind them.
4620 (defvar entry)
4621 (defvar state)
4622 (defvar last-state)
4623 (defvar date)
4624 (defvar description)
4626 ;; Defined somewhere in this file, but used before definition.
4627 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4628 (defvar org-agenda-buffer-name)
4629 (defvar org-agenda-undo-list)
4630 (defvar org-agenda-pending-undo-list)
4631 (defvar org-agenda-overriding-header)
4632 (defvar orgtbl-mode)
4633 (defvar org-html-entities)
4634 (defvar org-struct-menu)
4635 (defvar org-org-menu)
4636 (defvar org-tbl-menu)
4637 (defvar org-agenda-keymap)
4639 ;;;; Emacs/XEmacs compatibility
4641 ;; Overlay compatibility functions
4642 (defun org-make-overlay (beg end &optional buffer)
4643   (if (featurep 'xemacs)
4644       (make-extent beg end buffer)
4645     (make-overlay beg end buffer)))
4646 (defun org-delete-overlay (ovl)
4647   (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4648 (defun org-detach-overlay (ovl)
4649   (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4650 (defun org-move-overlay (ovl beg end &optional buffer)
4651   (if (featurep 'xemacs)
4652       (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4653     (move-overlay ovl beg end buffer)))
4654 (defun org-overlay-put (ovl prop value)
4655   (if (featurep 'xemacs)
4656       (set-extent-property ovl prop value)
4657     (overlay-put ovl prop value)))
4658 (defun org-overlay-display (ovl text &optional face evap)
4659   "Make overlay OVL display TEXT with face FACE."
4660   (if (featurep 'xemacs)
4661       (let ((gl (make-glyph text)))
4662         (and face (set-glyph-face gl face))
4663         (set-extent-property ovl 'invisible t)
4664         (set-extent-property ovl 'end-glyph gl))
4665     (overlay-put ovl 'display text)
4666     (if face (overlay-put ovl 'face face))
4667     (if evap (overlay-put ovl 'evaporate t))))
4668 (defun org-overlay-before-string (ovl text &optional face evap)
4669   "Make overlay OVL display TEXT with face FACE."
4670   (if (featurep 'xemacs)
4671       (let ((gl (make-glyph text)))
4672         (and face (set-glyph-face gl face))
4673         (set-extent-property ovl 'begin-glyph gl))
4674     (if face (org-add-props text nil 'face face))
4675     (overlay-put ovl 'before-string text)
4676     (if evap (overlay-put ovl 'evaporate t))))
4677 (defun org-overlay-get (ovl prop)
4678   (if (featurep 'xemacs)
4679       (extent-property ovl prop)
4680     (overlay-get ovl prop)))
4681 (defun org-overlays-at (pos)
4682   (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4683 (defun org-overlays-in (&optional start end)
4684   (if (featurep 'xemacs)
4685       (extent-list nil start end)
4686     (overlays-in start end)))
4687 (defun org-overlay-start (o)
4688   (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4689 (defun org-overlay-end (o)
4690   (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4691 (defun org-find-overlays (prop &optional pos delete)
4692   "Find all overlays specifying PROP at POS or point.
4693 If DELETE is non-nil, delete all those overlays."
4694   (let ((overlays (org-overlays-at (or pos (point))))
4695         ov found)
4696     (while (setq ov (pop overlays))
4697       (if (org-overlay-get ov prop)
4698           (if delete (org-delete-overlay ov) (push ov found))))
4699     found))
4701 ;; Region compatibility
4703 (defun org-add-hook (hook function &optional append local)
4704   "Add-hook, compatible with both Emacsen."
4705   (if (and local (featurep 'xemacs))
4706       (add-local-hook hook function append)
4707     (add-hook hook function append local)))
4709 (defvar org-ignore-region nil
4710   "To temporarily disable the active region.")
4712 (defun org-region-active-p ()
4713   "Is `transient-mark-mode' on and the region active?
4714 Works on both Emacs and XEmacs."
4715   (if org-ignore-region
4716       nil
4717     (if (featurep 'xemacs)
4718         (and zmacs-regions (region-active-p))
4719       (if (fboundp 'use-region-p)
4720           (use-region-p)
4721         (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4723 ;; Invisibility compatibility
4725 (defun org-add-to-invisibility-spec (arg)
4726   "Add elements to `buffer-invisibility-spec'.
4727 See documentation for `buffer-invisibility-spec' for the kind of elements
4728 that can be added."
4729   (cond
4730    ((fboundp 'add-to-invisibility-spec)
4731     (add-to-invisibility-spec arg))
4732    ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4733         (setq buffer-invisibility-spec (list arg)))
4734    (t
4735     (setq buffer-invisibility-spec
4736           (cons arg buffer-invisibility-spec)))))
4738 (defun org-remove-from-invisibility-spec (arg)
4739   "Remove elements from `buffer-invisibility-spec'."
4740   (if (fboundp 'remove-from-invisibility-spec)
4741       (remove-from-invisibility-spec arg)
4742     (if (consp buffer-invisibility-spec)
4743         (setq buffer-invisibility-spec
4744               (delete arg buffer-invisibility-spec)))))
4746 (defun org-in-invisibility-spec-p (arg)
4747   "Is ARG a member of `buffer-invisibility-spec'?"
4748   (if (consp buffer-invisibility-spec)
4749       (member arg buffer-invisibility-spec)
4750     nil))
4752 ;;;; Define the Org-mode
4754 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4755     (error "Conflict with outdated version of allout.el.  Load org.el before allout.el, or ugrade to newer allout, for example by switching to Emacs 22."))
4758 ;; We use a before-change function to check if a table might need
4759 ;; an update.
4760 (defvar org-table-may-need-update t
4761   "Indicates that a table might need an update.
4762 This variable is set by `org-before-change-function'.
4763 `org-table-align' sets it back to nil.")
4764 (defvar org-mode-map)
4765 (defvar org-mode-hook nil)
4766 (defvar org-inhibit-startup nil)        ; Dynamically-scoped param.
4767 (defvar org-agenda-keep-modes nil)      ; Dynamically-scoped param.
4768 (defvar org-table-buffer-is-an nil)
4769 (defconst org-outline-regexp "\\*+ ")
4771 ;;;###autoload
4772 (define-derived-mode org-mode outline-mode "Org"
4773   "Outline-based notes management and organizer, alias
4774 \"Carsten's outline-mode for keeping track of everything.\"
4776 Org-mode develops organizational tasks around a NOTES file which
4777 contains information about projects as plain text.  Org-mode is
4778 implemented on top of outline-mode, which is ideal to keep the content
4779 of large files well structured.  It supports ToDo items, deadlines and
4780 time stamps, which magically appear in the diary listing of the Emacs
4781 calendar.  Tables are easily created with a built-in table editor.
4782 Plain text URL-like links connect to websites, emails (VM), Usenet
4783 messages (Gnus), BBDB entries, and any files related to the project.
4784 For printing and sharing of notes, an Org-mode file (or a part of it)
4785 can be exported as a structured ASCII or HTML file.
4787 The following commands are available:
4789 \\{org-mode-map}"
4791   ;; Get rid of Outline menus, they are not needed
4792   ;; Need to do this here because define-derived-mode sets up
4793   ;; the keymap so late.  Still, it is a waste to call this each time
4794   ;; we switch another buffer into org-mode.
4795   (if (featurep 'xemacs)
4796       (when (boundp 'outline-mode-menu-heading)
4797         ;; Assume this is Greg's port, it used easymenu
4798         (easy-menu-remove outline-mode-menu-heading)
4799         (easy-menu-remove outline-mode-menu-show)
4800         (easy-menu-remove outline-mode-menu-hide))
4801     (define-key org-mode-map [menu-bar headings] 'undefined)
4802     (define-key org-mode-map [menu-bar hide] 'undefined)
4803     (define-key org-mode-map [menu-bar show] 'undefined))
4805   (easy-menu-add org-org-menu)
4806   (easy-menu-add org-tbl-menu)
4807   (org-install-agenda-files-menu)
4808   (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4809   (org-add-to-invisibility-spec '(org-cwidth))
4810   (when (featurep 'xemacs)
4811     (org-set-local 'line-move-ignore-invisible t))
4812   (org-set-local 'outline-regexp org-outline-regexp)
4813   (org-set-local 'outline-level 'org-outline-level)
4814   (when (and org-ellipsis
4815              (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4816              (fboundp 'make-glyph-code))
4817     (unless org-display-table
4818       (setq org-display-table (make-display-table)))
4819     (set-display-table-slot
4820      org-display-table 4
4821      (vconcat (mapcar
4822                (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4823                                                    org-ellipsis)))
4824                (if (stringp org-ellipsis) org-ellipsis "..."))))
4825     (setq buffer-display-table org-display-table))
4826   (org-set-regexps-and-options)
4827   ;; Calc embedded
4828   (org-set-local 'calc-embedded-open-mode "# ")
4829   (modify-syntax-entry ?# "<")
4830   (modify-syntax-entry ?@ "w")
4831   (if org-startup-truncated (setq truncate-lines t))
4832   (org-set-local 'font-lock-unfontify-region-function
4833                  'org-unfontify-region)
4834   ;; Activate before-change-function
4835   (org-set-local 'org-table-may-need-update t)
4836   (org-add-hook 'before-change-functions 'org-before-change-function nil
4837                 'local)
4838   ;; Check for running clock before killing a buffer
4839   (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4840   ;; Paragraphs and auto-filling
4841   (org-set-autofill-regexps)
4842   (setq indent-line-function 'org-indent-line-function)
4843   (org-update-radio-target-regexp)
4845   ;; Comment characters
4846 ;  (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4847   (org-set-local 'comment-padding " ")
4849   ;; Imenu
4850   (org-set-local 'imenu-create-index-function
4851                  'org-imenu-get-tree)
4853   ;; Make isearch reveal context
4854   (if (or (featurep 'xemacs)
4855           (not (boundp 'outline-isearch-open-invisible-function)))
4856       ;; Emacs 21 and XEmacs make use of the hook
4857       (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4858     ;; Emacs 22 deals with this through a special variable
4859     (org-set-local 'outline-isearch-open-invisible-function
4860                    (lambda (&rest ignore) (org-show-context 'isearch))))
4862   ;; If empty file that did not turn on org-mode automatically, make it to.
4863   (if (and org-insert-mode-line-in-empty-file
4864            (interactive-p)
4865            (= (point-min) (point-max)))
4866       (insert "#    -*- mode: org -*-\n\n"))
4868   (unless org-inhibit-startup
4869     (when org-startup-align-all-tables
4870       (let ((bmp (buffer-modified-p)))
4871         (org-table-map-tables 'org-table-align)
4872         (set-buffer-modified-p bmp)))
4873     (org-cycle-hide-drawers 'all)
4874     (cond
4875      ((eq org-startup-folded t)
4876       (org-cycle '(4)))
4877      ((eq org-startup-folded 'content)
4878       (let ((this-command 'org-cycle) (last-command 'org-cycle))
4879         (org-cycle '(4)) (org-cycle '(4)))))))
4881 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4883 (defsubst org-call-with-arg (command arg)
4884   "Call COMMAND interactively, but pretend prefix are was ARG."
4885   (let ((current-prefix-arg arg)) (call-interactively command)))
4887 (defsubst org-current-line (&optional pos)
4888   (save-excursion
4889     (and pos (goto-char pos))
4890     ;; works also in narrowed buffer, because we start at 1, not point-min
4891     (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4893 (defun org-current-time ()
4894   "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4895   (if (> org-time-stamp-rounding-minutes 0)
4896       (let ((r org-time-stamp-rounding-minutes)
4897             (time (decode-time)))
4898         (apply 'encode-time
4899                (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4900                        (nthcdr 2 time))))
4901     (current-time)))
4903 (defun org-add-props (string plist &rest props)
4904   "Add text properties to entire string, from beginning to end.
4905 PLIST may be a list of properties, PROPS are individual properties and values
4906 that will be added to PLIST.  Returns the string that was modified."
4907   (add-text-properties
4908    0 (length string) (if props (append plist props) plist) string)
4909   string)
4910 (put 'org-add-props 'lisp-indent-function 2)
4913 ;;;; Font-Lock stuff, including the activators
4915 (defvar org-mouse-map (make-sparse-keymap))
4916 (org-defkey org-mouse-map
4917   (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4918 (org-defkey org-mouse-map
4919   (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4920 (when org-mouse-1-follows-link
4921   (org-defkey org-mouse-map [follow-link] 'mouse-face))
4922 (when org-tab-follows-link
4923   (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4924   (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4925 (when org-return-follows-link
4926   (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4927   (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4929 (require 'font-lock)
4931 (defconst org-non-link-chars "]\t\n\r<>")
4932 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4933                            "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
4934 (defvar org-link-re-with-space nil
4935    "Matches a link with spaces, optional angular brackets around it.")
4936 (defvar org-link-re-with-space2 nil
4937    "Matches a link with spaces, optional angular brackets around it.")
4938 (defvar org-angle-link-re nil
4939    "Matches link with angular brackets, spaces are allowed.")
4940 (defvar org-plain-link-re nil
4941    "Matches plain link, without spaces.")
4942 (defvar org-bracket-link-regexp nil
4943   "Matches a link in double brackets.")
4944 (defvar org-bracket-link-analytic-regexp nil
4945   "Regular expression used to analyze links.
4946 Here is what the match groups contain after a match:
4947 1: http:
4948 2: http
4949 3: path
4950 4: [desc]
4951 5: desc")
4952 (defvar org-any-link-re nil
4953   "Regular expression matching any link.")
4955 (defun org-make-link-regexps ()
4956   "Update the link regular expressions.
4957 This should be called after the variable `org-link-types' has changed."
4958   (setq org-link-re-with-space
4959         (concat
4960          "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4961          "\\([^" org-non-link-chars " ]"
4962          "[^" org-non-link-chars "]*"
4963          "[^" org-non-link-chars " ]\\)>?")
4964         org-link-re-with-space2
4965         (concat
4966          "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4967          "\\([^" org-non-link-chars " ]"
4968          "[^]\t\n\r]*"
4969          "[^" org-non-link-chars " ]\\)>?")
4970         org-angle-link-re
4971         (concat
4972          "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4973          "\\([^" org-non-link-chars " ]"
4974          "[^" org-non-link-chars "]*"
4975          "\\)>")
4976         org-plain-link-re
4977         (concat
4978          "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4979          "\\([^]\t\n\r<>,;() ]+\\)")
4980         org-bracket-link-regexp
4981         "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4982         org-bracket-link-analytic-regexp
4983         (concat
4984          "\\[\\["
4985          "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4986          "\\([^]]+\\)"
4987          "\\]"
4988          "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4989          "\\]")
4990         org-any-link-re
4991         (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4992                 org-angle-link-re "\\)\\|\\("
4993                 org-plain-link-re "\\)")))
4995 (org-make-link-regexps)
4997 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4998   "Regular expression for fast time stamp matching.")
4999 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5000   "Regular expression for fast time stamp matching.")
5001 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5002   "Regular expression matching time strings for analysis.
5003 This one does not require the space after the date.")
5004 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5005   "Regular expression matching time strings for analysis.")
5006 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5007   "Regular expression matching time stamps, with groups.")
5008 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5009   "Regular expression matching time stamps (also [..]), with groups.")
5010 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5011   "Regular expression matching a time stamp range.")
5012 (defconst org-tr-regexp-both
5013   (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5014   "Regular expression matching a time stamp range.")
5015 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5016                                  org-ts-regexp "\\)?")
5017   "Regular expression matching a time stamp or time stamp range.")
5018 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5019                                       org-ts-regexp-both "\\)?")
5020   "Regular expression matching a time stamp or time stamp range.
5021 The time stamps may be either active or inactive.")
5023 (defvar org-emph-face nil)
5025 (defun org-do-emphasis-faces (limit)
5026   "Run through the buffer and add overlays to links."
5027   (let (rtn)
5028     (while (and (not rtn) (re-search-forward org-emph-re limit t))
5029       (if (not (= (char-after (match-beginning 3))
5030                   (char-after (match-beginning 4))))
5031           (progn
5032             (setq rtn t)
5033             (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5034                                              'face
5035                                              (nth 1 (assoc (match-string 3)
5036                                                            org-emphasis-alist)))
5037             (add-text-properties (match-beginning 2) (match-end 2)
5038                                  '(font-lock-multiline t))
5039             (when org-hide-emphasis-markers
5040               (add-text-properties (match-end 4) (match-beginning 5)
5041                                    '(invisible org-link))
5042               (add-text-properties (match-beginning 3) (match-end 3)
5043                                    '(invisible org-link)))))
5044       (backward-char 1))
5045     rtn))
5047 (defun org-emphasize (&optional char)
5048   "Insert or change an emphasis, i.e. a font like bold or italic.
5049 If there is an active region, change that region to a new emphasis.
5050 If there is no region, just insert the marker characters and position
5051 the cursor between them.
5052 CHAR should be either the marker character, or the first character of the
5053 HTML tag associated with that emphasis.  If CHAR is a space, the means
5054 to remove the emphasis of the selected region.
5055 If char is not given (for example in an interactive call) it
5056 will be prompted for."
5057   (interactive)
5058   (let ((eal org-emphasis-alist) e det
5059         (erc org-emphasis-regexp-components)
5060         (prompt "")
5061         (string "") beg end move tag c s)
5062     (if (org-region-active-p)
5063         (setq beg (region-beginning) end (region-end)
5064               string (buffer-substring beg end))
5065       (setq move t))
5067     (while (setq e (pop eal))
5068       (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5069             c (aref tag 0))
5070       (push (cons c (string-to-char (car e))) det)
5071       (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5072                                           (substring tag 1)))))
5073     (unless char
5074       (message "%s" (concat "Emphasis marker or tag:" prompt))
5075       (setq char (read-char-exclusive)))
5076     (setq char (or (cdr (assoc char det)) char))
5077     (if (equal char ?\ )
5078         (setq s "" move nil)
5079       (unless (assoc (char-to-string char) org-emphasis-alist)
5080         (error "No such emphasis marker: \"%c\"" char))
5081       (setq s (char-to-string char)))
5082     (while (and (> (length string) 1)
5083                 (equal (substring string 0 1) (substring string -1))
5084                 (assoc (substring string 0 1) org-emphasis-alist))
5085       (setq string (substring string 1 -1)))
5086     (setq string (concat s string s))
5087     (if beg (delete-region beg end))
5088     (unless (or (bolp)
5089                 (string-match (concat "[" (nth 0 erc) "\n]")
5090                               (char-to-string (char-before (point)))))
5091       (insert " "))
5092     (unless (string-match (concat "[" (nth 1 erc) "\n]")
5093                           (char-to-string (char-after (point))))
5094       (insert " ") (backward-char 1))
5095     (insert string)
5096     (and move (backward-char 1))))
5098 (defconst org-nonsticky-props
5099   '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5102 (defun org-activate-plain-links (limit)
5103   "Run through the buffer and add overlays to links."
5104   (catch 'exit
5105     (let (f)
5106       (while (re-search-forward org-plain-link-re limit t)
5107         (setq f (get-text-property (match-beginning 0) 'face))
5108         (if (or (eq f 'org-tag)
5109                 (and (listp f) (memq 'org-tag f)))
5110             nil
5111           (add-text-properties (match-beginning 0) (match-end 0)
5112                                (list 'mouse-face 'highlight
5113                                      'rear-nonsticky org-nonsticky-props
5114                                      'keymap org-mouse-map
5115                                      ))
5116           (throw 'exit t))))))
5118 (defun org-activate-code (limit)
5119   (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5120       (unless (get-text-property (match-beginning 1) 'face)
5121         (remove-text-properties (match-beginning 0) (match-end 0)
5122                                 '(display t invisible t intangible t))
5123         t)))
5125 (defun org-activate-angle-links (limit)
5126   "Run through the buffer and add overlays to links."
5127   (if (re-search-forward org-angle-link-re limit t)
5128       (progn
5129         (add-text-properties (match-beginning 0) (match-end 0)
5130                              (list 'mouse-face 'highlight
5131                                    'rear-nonsticky org-nonsticky-props
5132                                    'keymap org-mouse-map
5133                                    ))
5134         t)))
5136 (defmacro org-maybe-intangible (props)
5137   "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5138 In emacs 21, invisible text is not avoided by the command loop, so the
5139 intangible property is needed to make sure point skips this text.
5140 In Emacs 22, this is not necessary.  The intangible text property has
5141 led to problems with flyspell.  These problems are fixed in flyspell.el,
5142 but we still avoid setting the property in Emacs 22 and later.
5143 We use a macro so that the test can happen at compilation time."
5144   (if (< emacs-major-version 22)
5145       `(append '(intangible t) ,props)
5146     props))
5148 (defun org-activate-bracket-links (limit)
5149   "Run through the buffer and add overlays to bracketed links."
5150   (if (re-search-forward org-bracket-link-regexp limit t)
5151       (let* ((help (concat "LINK: "
5152                            (org-match-string-no-properties 1)))
5153              ;; FIXME: above we should remove the escapes.
5154              ;; but that requires another match, protecting match data,
5155              ;; a lot of overhead for font-lock.
5156              (ip (org-maybe-intangible
5157                   (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5158                         'keymap org-mouse-map 'mouse-face 'highlight
5159                         'font-lock-multiline t 'help-echo help)))
5160              (vp (list 'rear-nonsticky org-nonsticky-props
5161                        'keymap org-mouse-map 'mouse-face 'highlight
5162                        ' font-lock-multiline t 'help-echo help)))
5163         ;; We need to remove the invisible property here.  Table narrowing
5164         ;; may have made some of this invisible.
5165         (remove-text-properties (match-beginning 0) (match-end 0)
5166                                 '(invisible nil))
5167         (if (match-end 3)
5168             (progn
5169               (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5170               (add-text-properties (match-beginning 3) (match-end 3) vp)
5171               (add-text-properties (match-end 3) (match-end 0) ip))
5172           (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5173           (add-text-properties (match-beginning 1) (match-end 1) vp)
5174           (add-text-properties (match-end 1) (match-end 0) ip))
5175         t)))
5177 (defun org-activate-dates (limit)
5178   "Run through the buffer and add overlays to dates."
5179   (if (re-search-forward org-tsr-regexp-both limit t)
5180       (progn
5181         (add-text-properties (match-beginning 0) (match-end 0)
5182                              (list 'mouse-face 'highlight
5183                                    'rear-nonsticky org-nonsticky-props
5184                                    'keymap org-mouse-map))
5185         (when org-display-custom-times
5186           (if (match-end 3)
5187               (org-display-custom-time (match-beginning 3) (match-end 3)))
5188           (org-display-custom-time (match-beginning 1) (match-end 1)))
5189         t)))
5191 (defvar org-target-link-regexp nil
5192   "Regular expression matching radio targets in plain text.")
5193 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5194   "Regular expression matching a link target.")
5195 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5196   "Regular expression matching a radio target.")
5197 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>>  as a radio target.
5198   "Regular expression matching any target.")
5200 (defun org-activate-target-links (limit)
5201   "Run through the buffer and add overlays to target matches."
5202   (when org-target-link-regexp
5203     (let ((case-fold-search t))
5204       (if (re-search-forward org-target-link-regexp limit t)
5205           (progn
5206             (add-text-properties (match-beginning 0) (match-end 0)
5207                                  (list 'mouse-face 'highlight
5208                                        'rear-nonsticky org-nonsticky-props
5209                                        'keymap org-mouse-map
5210                                        'help-echo "Radio target link"
5211                                        'org-linked-text t))
5212             t)))))
5214 (defun org-update-radio-target-regexp ()
5215   "Find all radio targets in this file and update the regular expression."
5216   (interactive)
5217   (when (memq 'radio org-activate-links)
5218     (setq org-target-link-regexp
5219           (org-make-target-link-regexp (org-all-targets 'radio)))
5220     (org-restart-font-lock)))
5222 (defun org-hide-wide-columns (limit)
5223   (let (s e)
5224     (setq s (text-property-any (point) (or limit (point-max))
5225                                'org-cwidth t))
5226     (when s
5227       (setq e (next-single-property-change s 'org-cwidth))
5228       (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5229       (goto-char e)
5230       t)))
5232 (defvar org-latex-and-specials-regexp nil
5233   "Regular expression for highlighting export special stuff.")
5234 (defvar org-match-substring-regexp)
5235 (defvar org-match-substring-with-braces-regexp)
5236 (defvar org-export-html-special-string-regexps)
5238 (defun org-compute-latex-and-specials-regexp ()
5239   "Compute regular expression for stuff treated specially by exporters."
5240   (if (not org-highlight-latex-fragments-and-specials)
5241       (org-set-local 'org-latex-and-specials-regexp nil)
5242     (let*
5243         ((matchers (plist-get org-format-latex-options :matchers))
5244          (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5245                                    org-latex-regexps)))
5246          (options (org-combine-plists (org-default-export-plist)
5247                                       (org-infile-export-plist)))
5248          (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5249          (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5250          (org-export-with-TeX-macros (plist-get options :TeX-macros))
5251          (org-export-html-expand (plist-get options :expand-quoted-html))
5252          (org-export-with-special-strings (plist-get options :special-strings))
5253          (re-sub
5254           (cond
5255            ((equal org-export-with-sub-superscripts '{})
5256             (list org-match-substring-with-braces-regexp))
5257            (org-export-with-sub-superscripts
5258             (list org-match-substring-regexp))
5259            (t nil)))
5260          (re-latex
5261           (if org-export-with-LaTeX-fragments
5262               (mapcar (lambda (x) (nth 1 x)) latexs)))
5263          (re-macros
5264           (if org-export-with-TeX-macros
5265               (list (concat "\\\\"
5266                             (regexp-opt
5267                              (append (mapcar 'car org-html-entities)
5268                                      (if (boundp 'org-latex-entities)
5269                                          org-latex-entities nil))
5270                              'words))) ; FIXME
5271             ))
5272     ;;                  (list "\\\\\\(?:[a-zA-Z]+\\)")))
5273          (re-special (if org-export-with-special-strings
5274                          (mapcar (lambda (x) (car x))
5275                                  org-export-html-special-string-regexps)))
5276          (re-rest
5277           (delq nil
5278                 (list
5279                  (if org-export-html-expand "@<[^>\n]+>")
5280                  ))))
5281       (org-set-local
5282        'org-latex-and-specials-regexp
5283        (mapconcat 'identity (append re-latex re-sub re-macros re-special
5284                                     re-rest) "\\|")))))
5286 (defface org-latex-and-export-specials
5287   (let ((font (cond ((assq :inherit custom-face-attributes)
5288                      '(:inherit underline))
5289                     (t '(:underline t)))))
5290     `((((class grayscale) (background light))
5291        (:foreground "DimGray" ,@font))
5292       (((class grayscale) (background dark))
5293        (:foreground "LightGray" ,@font))
5294       (((class color) (background light))
5295        (:foreground "SaddleBrown"))
5296       (((class color) (background dark))
5297        (:foreground "burlywood"))
5298       (t (,@font))))
5299   "Face used to highlight math latex and other special exporter stuff."
5300   :group 'org-faces)
5302 (defun org-do-latex-and-special-faces (limit)
5303   "Run through the buffer and add overlays to links."
5304   (when org-latex-and-specials-regexp
5305     (let (rtn d)
5306       (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5307                                                limit t))
5308         (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5309                                                     'face))
5310                        '(org-code org-verbatim underline)))
5311             (progn
5312               (setq rtn t
5313                     d (cond ((member (char-after (1+ (match-beginning 0)))
5314                                      '(?_ ?^)) 1)
5315                             (t 0)))
5316               (font-lock-prepend-text-property
5317                (+ d (match-beginning 0)) (match-end 0)
5318                'face 'org-latex-and-export-specials)
5319               (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5320                                    '(font-lock-multiline t)))))
5321       rtn)))
5323 (defun org-restart-font-lock ()
5324   "Restart font-lock-mode, to force refontification."
5325   (when (and (boundp 'font-lock-mode) font-lock-mode)
5326     (font-lock-mode -1)
5327     (font-lock-mode 1)))
5329 (defun org-all-targets (&optional radio)
5330   "Return a list of all targets in this file.
5331 With optional argument RADIO, only find radio targets."
5332   (let ((re (if radio org-radio-target-regexp org-target-regexp))
5333         rtn)
5334     (save-excursion
5335       (goto-char (point-min))
5336       (while (re-search-forward re nil t)
5337         (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5338       rtn)))
5340 (defun org-make-target-link-regexp (targets)
5341   "Make regular expression matching all strings in TARGETS.
5342 The regular expression finds the targets also if there is a line break
5343 between words."
5344   (and targets
5345        (concat
5346         "\\<\\("
5347         (mapconcat
5348          (lambda (x)
5349            (while (string-match " +" x)
5350              (setq x (replace-match "\\s-+" t t x)))
5351            x)
5352          targets
5353          "\\|")
5354         "\\)\\>")))
5356 (defun org-activate-tags (limit)
5357   (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5358       (progn
5359         (add-text-properties (match-beginning 1) (match-end 1)
5360                              (list 'mouse-face 'highlight
5361                                    'rear-nonsticky org-nonsticky-props
5362                                    'keymap org-mouse-map))
5363         t)))
5365 (defun org-outline-level ()
5366   (save-excursion
5367     (looking-at outline-regexp)
5368     (if (match-beginning 1)
5369         (+ (org-get-string-indentation (match-string 1)) 1000)
5370       (1- (- (match-end 0) (match-beginning 0))))))
5372 (defvar org-font-lock-keywords nil)
5374 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5375   "Regular expression matching a property line.")
5377 (defun org-set-font-lock-defaults ()
5378   (let* ((em org-fontify-emphasized-text)
5379          (lk org-activate-links)
5380          (org-font-lock-extra-keywords
5381           (list
5382            ;; Headlines
5383            '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5384              (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5385            ;; Table lines
5386            '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5387              (1 'org-table t))
5388            ;; Table internals
5389            '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5390            '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5391            '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5392            ;; Drawers
5393            (list org-drawer-regexp '(0 'org-special-keyword t))
5394            (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5395            ;; Properties
5396            (list org-property-re
5397                  '(1 'org-special-keyword t)
5398                  '(3 'org-property-value t))
5399            (if org-format-transports-properties-p
5400                '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5401            ;; Links
5402            (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5403            (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5404            (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5405            (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5406            (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5407            (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5408            '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5409            '(org-hide-wide-columns (0 nil append))
5410            ;; TODO lines
5411            (list (concat "^\\*+[ \t]+" org-todo-regexp)
5412                  '(1 (org-get-todo-face 1) t))
5413            ;; DONE
5414            (if org-fontify-done-headline
5415                (list (concat "^[*]+ +\\<\\("
5416                              (mapconcat 'regexp-quote org-done-keywords "\\|")
5417                              "\\)\\(.*\\)")
5418                      '(2 'org-headline-done t))
5419              nil)
5420            ;; Priorities
5421            (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5422            ;; Special keywords
5423            (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5424            (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5425            (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5426            (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5427            ;; Emphasis
5428            (if em
5429                (if (featurep 'xemacs)
5430                    '(org-do-emphasis-faces (0 nil append))
5431                  '(org-do-emphasis-faces)))
5432            ;; Checkboxes
5433            '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5434              2 'bold prepend)
5435            (if org-provide-checkbox-statistics
5436                '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5437                  (0 (org-get-checkbox-statistics-face) t)))
5438            (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5439                  '(1 'org-archived prepend))
5440            ;; Specials
5441            '(org-do-latex-and-special-faces)
5442            ;; Code
5443            '(org-activate-code (1 'org-code t))
5444            ;; COMMENT
5445            (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5446                          "\\|" org-quote-string "\\)\\>")
5447                  '(1 'org-special-keyword t))
5448            '("^#.*" (0 'font-lock-comment-face t))
5449            )))
5450     (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5451     ;; Now set the full font-lock-keywords
5452     (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5453     (org-set-local 'font-lock-defaults
5454                    '(org-font-lock-keywords t nil nil backward-paragraph))
5455     (kill-local-variable 'font-lock-keywords) nil))
5457 (defvar org-m nil)
5458 (defvar org-l nil)
5459 (defvar org-f nil)
5460 (defun org-get-level-face (n)
5461   "Get the right face for match N in font-lock matching of healdines."
5462   (setq org-l (- (match-end 2) (match-beginning 1) 1))
5463   (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5464   (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5465   (cond
5466    ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5467    ((eq n 2) org-f)
5468    (t (if org-level-color-stars-only nil org-f))))
5470 (defun org-get-todo-face (kwd)
5471   "Get the right face for a TODO keyword KWD.
5472 If KWD is a number, get the corresponding match group."
5473   (if (numberp kwd) (setq kwd (match-string kwd)))
5474   (or (cdr (assoc kwd org-todo-keyword-faces))
5475       (and (member kwd org-done-keywords) 'org-done)
5476       'org-todo))
5478 (defun org-unfontify-region (beg end &optional maybe_loudly)
5479   "Remove fontification and activation overlays from links."
5480   (font-lock-default-unfontify-region beg end)
5481   (let* ((buffer-undo-list t)
5482          (inhibit-read-only t) (inhibit-point-motion-hooks t)
5483          (inhibit-modification-hooks t)
5484          deactivate-mark buffer-file-name buffer-file-truename)
5485     (remove-text-properties beg end
5486                             '(mouse-face t keymap t org-linked-text t
5487                                          invisible t intangible t))))
5489 ;;;; Visibility cycling, including org-goto and indirect buffer
5491 ;;; Cycling
5493 (defvar org-cycle-global-status nil)
5494 (make-variable-buffer-local 'org-cycle-global-status)
5495 (defvar org-cycle-subtree-status nil)
5496 (make-variable-buffer-local 'org-cycle-subtree-status)
5498 ;;;###autoload
5499 (defun org-cycle (&optional arg)
5500   "Visibility cycling for Org-mode.
5502 - When this function is called with a prefix argument, rotate the entire
5503   buffer through 3 states (global cycling)
5504   1. OVERVIEW: Show only top-level headlines.
5505   2. CONTENTS: Show all headlines of all levels, but no body text.
5506   3. SHOW ALL: Show everything.
5508 - When point is at the beginning of a headline, rotate the subtree started
5509   by this line through 3 different states (local cycling)
5510   1. FOLDED:   Only the main headline is shown.
5511   2. CHILDREN: The main headline and the direct children are shown.
5512                From this state, you can move to one of the children
5513                and zoom in further.
5514   3. SUBTREE:  Show the entire subtree, including body text.
5516 - When there is a numeric prefix, go up to a heading with level ARG, do
5517   a `show-subtree' and return to the previous cursor position.  If ARG
5518   is negative, go up that many levels.
5520 - When point is not at the beginning of a headline, execute
5521   `indent-relative', like TAB normally does.  See the option
5522   `org-cycle-emulate-tab' for details.
5524 - Special case: if point is at the beginning of the buffer and there is
5525   no headline in line 1, this function will act as if called with prefix arg.
5526   But only if also the variable `org-cycle-global-at-bob' is t."
5527   (interactive "P")
5528   (let* ((outline-regexp
5529           (if (and (org-mode-p) org-cycle-include-plain-lists)
5530               "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5531             outline-regexp))
5532          (bob-special (and org-cycle-global-at-bob (bobp)
5533                            (not (looking-at outline-regexp))))
5534          (org-cycle-hook
5535           (if bob-special
5536               (delq 'org-optimize-window-after-visibility-change
5537                     (copy-sequence org-cycle-hook))
5538             org-cycle-hook))
5539          (pos (point)))
5541     (if (or bob-special (equal arg '(4)))
5542         ;; special case:  use global cycling
5543         (setq arg t))
5545     (cond
5547      ((org-at-table-p 'any)
5548       ;; Enter the table or move to the next field in the table
5549       (or (org-table-recognize-table.el)
5550           (progn
5551             (if arg (org-table-edit-field t)
5552               (org-table-justify-field-maybe)
5553               (call-interactively 'org-table-next-field)))))
5555      ((eq arg t) ;; Global cycling
5557       (cond
5558        ((and (eq last-command this-command)
5559              (eq org-cycle-global-status 'overview))
5560         ;; We just created the overview - now do table of contents
5561         ;; This can be slow in very large buffers, so indicate action
5562         (message "CONTENTS...")
5563         (org-content)
5564         (message "CONTENTS...done")
5565         (setq org-cycle-global-status 'contents)
5566         (run-hook-with-args 'org-cycle-hook 'contents))
5568        ((and (eq last-command this-command)
5569              (eq org-cycle-global-status 'contents))
5570         ;; We just showed the table of contents - now show everything
5571         (show-all)
5572         (message "SHOW ALL")
5573         (setq org-cycle-global-status 'all)
5574         (run-hook-with-args 'org-cycle-hook 'all))
5576        (t
5577         ;; Default action: go to overview
5578         (org-overview)
5579         (message "OVERVIEW")
5580         (setq org-cycle-global-status 'overview)
5581         (run-hook-with-args 'org-cycle-hook 'overview))))
5583      ((and org-drawers org-drawer-regexp
5584            (save-excursion
5585              (beginning-of-line 1)
5586              (looking-at org-drawer-regexp)))
5587       ;; Toggle block visibility
5588       (org-flag-drawer
5589        (not (get-char-property (match-end 0) 'invisible))))
5591      ((integerp arg)
5592       ;; Show-subtree, ARG levels up from here.
5593       (save-excursion
5594         (org-back-to-heading)
5595         (outline-up-heading (if (< arg 0) (- arg)
5596                               (- (funcall outline-level) arg)))
5597         (org-show-subtree)))
5599      ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5600            (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5601       ;; At a heading: rotate between three different views
5602       (org-back-to-heading)
5603       (let ((goal-column 0) eoh eol eos)
5604         ;; First, some boundaries
5605         (save-excursion
5606           (org-back-to-heading)
5607           (save-excursion
5608             (beginning-of-line 2)
5609             (while (and (not (eobp)) ;; this is like `next-line'
5610                         (get-char-property (1- (point)) 'invisible))
5611               (beginning-of-line 2)) (setq eol (point)))
5612           (outline-end-of-heading)   (setq eoh (point))
5613           (org-end-of-subtree t)
5614           (unless (eobp)
5615             (skip-chars-forward " \t\n")
5616             (beginning-of-line 1) ; in case this is an item
5617             )
5618           (setq eos (1- (point))))
5619         ;; Find out what to do next and set `this-command'
5620         (cond
5621          ((= eos eoh)
5622           ;; Nothing is hidden behind this heading
5623           (message "EMPTY ENTRY")
5624           (setq org-cycle-subtree-status nil)
5625           (save-excursion
5626             (goto-char eos)
5627             (outline-next-heading)
5628             (if (org-invisible-p) (org-flag-heading nil))))
5629          ((or (>= eol eos)
5630               (not (string-match "\\S-" (buffer-substring eol eos))))
5631           ;; Entire subtree is hidden in one line: open it
5632           (org-show-entry)
5633           (show-children)
5634           (message "CHILDREN")
5635           (save-excursion
5636             (goto-char eos)
5637             (outline-next-heading)
5638             (if (org-invisible-p) (org-flag-heading nil)))
5639           (setq org-cycle-subtree-status 'children)
5640           (run-hook-with-args 'org-cycle-hook 'children))
5641          ((and (eq last-command this-command)
5642                (eq org-cycle-subtree-status 'children))
5643           ;; We just showed the children, now show everything.
5644           (org-show-subtree)
5645           (message "SUBTREE")
5646           (setq org-cycle-subtree-status 'subtree)
5647           (run-hook-with-args 'org-cycle-hook 'subtree))
5648          (t
5649           ;; Default action: hide the subtree.
5650           (hide-subtree)
5651           (message "FOLDED")
5652           (setq org-cycle-subtree-status 'folded)
5653           (run-hook-with-args 'org-cycle-hook 'folded)))))
5655      ;; TAB emulation
5656      (buffer-read-only (org-back-to-heading))
5658      ((org-try-cdlatex-tab))
5660      ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5661            (or (not (bolp))
5662                (not (looking-at outline-regexp))))
5663       (call-interactively (global-key-binding "\t")))
5665      ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5666                (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5667                (or (and (eq org-cycle-emulate-tab 'white)
5668                         (= (match-end 0) (point-at-eol)))
5669                    (and (eq org-cycle-emulate-tab 'whitestart)
5670                         (>= (match-end 0) pos))))
5671           t
5672         (eq org-cycle-emulate-tab t))
5673 ;      (if (and (looking-at "[ \n\r\t]")
5674 ;              (string-match "^[ \t]*$" (buffer-substring
5675 ;                                        (point-at-bol) (point))))
5676 ;         (progn
5677 ;           (beginning-of-line 1)
5678 ;           (and (looking-at "[ \t]+") (replace-match ""))))
5679       (call-interactively (global-key-binding "\t")))
5681      (t (save-excursion
5682           (org-back-to-heading)
5683           (org-cycle))))))
5685 ;;;###autoload
5686 (defun org-global-cycle (&optional arg)
5687   "Cycle the global visibility.  For details see `org-cycle'."
5688   (interactive "P")
5689   (let ((org-cycle-include-plain-lists
5690          (if (org-mode-p) org-cycle-include-plain-lists nil)))
5691     (if (integerp arg)
5692         (progn
5693           (show-all)
5694           (hide-sublevels arg)
5695           (setq org-cycle-global-status 'contents))
5696       (org-cycle '(4)))))
5698 (defun org-overview ()
5699   "Switch to overview mode, shoing only top-level headlines.
5700 Really, this shows all headlines with level equal or greater than the level
5701 of the first headline in the buffer.  This is important, because if the
5702 first headline is not level one, then (hide-sublevels 1) gives confusing
5703 results."
5704   (interactive)
5705   (let ((level (save-excursion
5706                  (goto-char (point-min))
5707                  (if (re-search-forward (concat "^" outline-regexp) nil t)
5708                      (progn
5709                        (goto-char (match-beginning 0))
5710                        (funcall outline-level))))))
5711     (and level (hide-sublevels level))))
5713 (defun org-content (&optional arg)
5714   "Show all headlines in the buffer, like a table of contents.
5715 With numerical argument N, show content up to level N."
5716   (interactive "P")
5717   (save-excursion
5718     ;; Visit all headings and show their offspring
5719     (and (integerp arg) (org-overview))
5720     (goto-char (point-max))
5721     (catch 'exit
5722       (while (and (progn (condition-case nil
5723                              (outline-previous-visible-heading 1)
5724                            (error (goto-char (point-min))))
5725                          t)
5726                   (looking-at outline-regexp))
5727         (if (integerp arg)
5728             (show-children (1- arg))
5729           (show-branches))
5730         (if (bobp) (throw 'exit nil))))))
5733 (defun org-optimize-window-after-visibility-change (state)
5734   "Adjust the window after a change in outline visibility.
5735 This function is the default value of the hook `org-cycle-hook'."
5736   (when (get-buffer-window (current-buffer))
5737     (cond
5738 ;     ((eq state 'overview) (org-first-headline-recenter 1))
5739 ;     ((eq state 'overview) (org-beginning-of-line))
5740      ((eq state 'content)  nil)
5741      ((eq state 'all)      nil)
5742      ((eq state 'folded)   nil)
5743      ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5744      ((eq state 'subtree)  (or (org-subtree-end-visible-p) (recenter 1))))))
5746 (defun org-compact-display-after-subtree-move ()
5747   (let (beg end)
5748     (save-excursion
5749       (if (org-up-heading-safe)
5750           (progn
5751             (hide-subtree)
5752             (show-entry)
5753             (show-children)
5754             (org-cycle-show-empty-lines 'children)
5755             (org-cycle-hide-drawers 'children))
5756         (org-overview)))))
5758 (defun org-cycle-show-empty-lines (state)
5759   "Show empty lines above all visible headlines.
5760 The region to be covered depends on STATE when called through
5761 `org-cycle-hook'.  Lisp program can use t for STATE to get the
5762 entire buffer covered.  Note that an empty line is only shown if there
5763 are at least `org-cycle-separator-lines' empty lines before the headeline."
5764   (when (> org-cycle-separator-lines 0)
5765     (save-excursion
5766       (let* ((n org-cycle-separator-lines)
5767              (re (cond
5768                   ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5769                   ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5770                   (t (let ((ns (number-to-string (- n 2))))
5771                        (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5772                                "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5773              beg end)
5774         (cond
5775          ((memq state '(overview contents t))
5776           (setq beg (point-min) end (point-max)))
5777          ((memq state '(children folded))
5778           (setq beg (point) end (progn (org-end-of-subtree t t)
5779                                        (beginning-of-line 2)
5780                                        (point)))))
5781         (when beg
5782           (goto-char beg)
5783           (while (re-search-forward re end t)
5784             (if (not (get-char-property (match-end 1) 'invisible))
5785                 (outline-flag-region
5786                  (match-beginning 1) (match-end 1) nil)))))))
5787   ;; Never hide empty lines at the end of the file.
5788   (save-excursion
5789     (goto-char (point-max))
5790     (outline-previous-heading)
5791     (outline-end-of-heading)
5792     (if (and (looking-at "[ \t\n]+")
5793              (= (match-end 0) (point-max)))
5794         (outline-flag-region (point) (match-end 0) nil))))
5796 (defun org-subtree-end-visible-p ()
5797   "Is the end of the current subtree visible?"
5798   (pos-visible-in-window-p
5799    (save-excursion (org-end-of-subtree t) (point))))
5801 (defun org-first-headline-recenter (&optional N)
5802   "Move cursor to the first headline and recenter the headline.
5803 Optional argument N means, put the headline into the Nth line of the window."
5804   (goto-char (point-min))
5805   (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5806     (beginning-of-line)
5807     (recenter (prefix-numeric-value N))))
5809 ;;; Org-goto
5811 (defvar org-goto-window-configuration nil)
5812 (defvar org-goto-marker nil)
5813 (defvar org-goto-map
5814   (let ((map (make-sparse-keymap)))
5815     (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5816       (while (setq cmd (pop cmds))
5817         (substitute-key-definition cmd cmd map global-map)))
5818     (suppress-keymap map)
5819     (org-defkey map "\C-m"     'org-goto-ret)
5820     (org-defkey map [(left)]   'org-goto-left)
5821     (org-defkey map [(right)]  'org-goto-right)
5822     (org-defkey map [(?q)]     'org-goto-quit)
5823     (org-defkey map [(control ?g)] 'org-goto-quit)
5824     (org-defkey map "\C-i" 'org-cycle)
5825     (org-defkey map [(tab)] 'org-cycle)
5826     (org-defkey map [(down)] 'outline-next-visible-heading)
5827     (org-defkey map [(up)] 'outline-previous-visible-heading)
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 copy of buffer to find location or copy text.
5843 RET=jump to location             [Q]uit and return to previous location
5844 \[Up]/[Down]=next/prev headline   TAB=cycle visibility   [/] org-occur"
5847 (defvar org-goto-start-pos) ; dynamically scoped parameter
5849 (defun org-goto ()
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)
5865   (let* ((org-goto-start-pos (point))
5866          (selected-point
5867           (car (org-get-location (current-buffer) org-goto-help))))
5868     (if selected-point
5869         (progn
5870           (org-mark-ring-push org-goto-start-pos)
5871           (goto-char selected-point)
5872           (if (or (org-invisible-p) (org-invisible-p2))
5873               (org-show-context 'org-goto)))
5874       (message "Quit"))))
5876 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5877 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5879 (defun org-get-location (buf help)
5880   "Let the user select a location in the Org-mode buffer BUF.
5881 This function uses a recursive edit.  It returns the selected position
5882 or nil."
5883   (let (org-goto-selected-point org-goto-exit-command)
5884     (save-excursion
5885       (save-window-excursion
5886         (delete-other-windows)
5887         (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5888         (switch-to-buffer
5889          (condition-case nil
5890              (make-indirect-buffer (current-buffer) "*org-goto*")
5891            (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5892         (with-output-to-temp-buffer "*Help*"
5893           (princ help))
5894         (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5895         (setq buffer-read-only nil)
5896         (let ((org-startup-truncated t)
5897               (org-startup-folded nil)
5898               (org-startup-align-all-tables nil))
5899           (org-mode)
5900           (org-overview))
5901         (setq buffer-read-only t)
5902         (if (and (boundp 'org-goto-start-pos)
5903                  (integer-or-marker-p org-goto-start-pos))
5904             (let ((org-show-hierarchy-above t)
5905                   (org-show-siblings t)
5906                   (org-show-following-heading t))
5907               (goto-char org-goto-start-pos)
5908               (and (org-invisible-p) (org-show-context)))
5909           (goto-char (point-min)))
5910         (org-beginning-of-line)
5911         (message "Select location and press RET")
5912         ;; now we make sure that during selection, ony very few keys work
5913         ;; and that it is impossible to switch to another window.
5914 ;       (let ((gm (current-global-map))
5915 ;             (overriding-local-map org-goto-map))
5916 ;         (unwind-protect
5917 ;             (progn
5918 ;               (use-global-map org-goto-map)
5919 ;               (recursive-edit))
5920 ;           (use-global-map gm)))
5921         (use-local-map org-goto-map)
5922         (recursive-edit)
5923         ))
5924     (kill-buffer "*org-goto*")
5925     (cons org-goto-selected-point org-goto-exit-command)))
5927 (defun org-goto-ret (&optional arg)
5928   "Finish `org-goto' by going to the new location."
5929   (interactive "P")
5930   (setq org-goto-selected-point (point)
5931         org-goto-exit-command 'return)
5932   (throw 'exit nil))
5934 (defun org-goto-left ()
5935   "Finish `org-goto' by going to the new location."
5936   (interactive)
5937   (if (org-on-heading-p)
5938       (progn
5939         (beginning-of-line 1)
5940         (setq org-goto-selected-point (point)
5941               org-goto-exit-command 'left)
5942         (throw 'exit nil))
5943     (error "Not on a heading")))
5945 (defun org-goto-right ()
5946   "Finish `org-goto' by going to the new location."
5947   (interactive)
5948   (if (org-on-heading-p)
5949       (progn
5950         (setq org-goto-selected-point (point)
5951               org-goto-exit-command 'right)
5952         (throw 'exit nil))
5953     (error "Not on a heading")))
5955 (defun org-goto-quit ()
5956   "Finish `org-goto' without cursor motion."
5957   (interactive)
5958   (setq org-goto-selected-point nil)
5959   (setq org-goto-exit-command 'quit)
5960   (throw 'exit nil))
5962 ;;; Indirect buffer display of subtrees
5964 (defvar org-indirect-dedicated-frame nil
5965   "This is the frame being used for indirect tree display.")
5966 (defvar org-last-indirect-buffer nil)
5968 (defun org-tree-to-indirect-buffer (&optional arg)
5969   "Create indirect buffer and narrow it to current subtree.
5970 With numerical prefix ARG, go up to this level and then take that tree.
5971 If ARG is negative, go up that many levels.
5972 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5973 indirect buffer previously made with this command, to avoid proliferation of
5974 indirect buffers.  However, when you call the command with a `C-u' prefix, or
5975 when `org-indirect-buffer-display' is `new-frame', the last buffer
5976 is kept so that you can work with several indirect buffers at the same time.
5977 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5978 requests that a new frame be made for the new buffer, so that the dedicated
5979 frame is not changed."
5980   (interactive "P")
5981   (let ((cbuf (current-buffer))
5982         (cwin (selected-window))
5983         (pos (point))
5984         beg end level heading ibuf)
5985     (save-excursion
5986       (org-back-to-heading t)
5987       (when (numberp arg)
5988         (setq level (org-outline-level))
5989         (if (< arg 0) (setq arg (+ level arg)))
5990         (while (> (setq level (org-outline-level)) arg)
5991           (outline-up-heading 1 t)))
5992       (setq beg (point)
5993             heading (org-get-heading))
5994       (org-end-of-subtree t) (setq end (point)))
5995     (if (and (buffer-live-p org-last-indirect-buffer)
5996              (not (eq org-indirect-buffer-display 'new-frame))
5997              (not arg))
5998         (kill-buffer org-last-indirect-buffer))
5999     (setq ibuf (org-get-indirect-buffer cbuf)
6000           org-last-indirect-buffer ibuf)
6001     (cond
6002      ((or (eq org-indirect-buffer-display 'new-frame)
6003           (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6004       (select-frame (make-frame))
6005       (delete-other-windows)
6006       (switch-to-buffer ibuf)
6007       (org-set-frame-title heading))
6008      ((eq org-indirect-buffer-display 'dedicated-frame)
6009       (raise-frame
6010        (select-frame (or (and org-indirect-dedicated-frame
6011                               (frame-live-p org-indirect-dedicated-frame)
6012                               org-indirect-dedicated-frame)
6013                          (setq org-indirect-dedicated-frame (make-frame)))))
6014       (delete-other-windows)
6015       (switch-to-buffer ibuf)
6016       (org-set-frame-title (concat "Indirect: " heading)))
6017      ((eq org-indirect-buffer-display 'current-window)
6018       (switch-to-buffer ibuf))
6019      ((eq org-indirect-buffer-display 'other-window)
6020       (pop-to-buffer ibuf))
6021      (t (error "Invalid value.")))
6022     (if (featurep 'xemacs)
6023         (save-excursion (org-mode) (turn-on-font-lock)))
6024     (narrow-to-region beg end)
6025     (show-all)
6026     (goto-char pos)
6027     (and (window-live-p cwin) (select-window cwin))))
6029 (defun org-get-indirect-buffer (&optional buffer)
6030   (setq buffer (or buffer (current-buffer)))
6031   (let ((n 1) (base (buffer-name buffer)) bname)
6032     (while (buffer-live-p
6033             (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6034       (setq n (1+ n)))
6035     (condition-case nil
6036         (make-indirect-buffer buffer bname 'clone)
6037       (error (make-indirect-buffer buffer bname)))))
6039 (defun org-set-frame-title (title)
6040   "Set the title of the current frame to the string TITLE."
6041   ;; FIXME: how to name a single frame in XEmacs???
6042   (unless (featurep 'xemacs)
6043     (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6045 ;;;; Structure editing
6047 ;;; Inserting headlines
6049 (defun org-insert-heading (&optional force-heading)
6050   "Insert a new heading or item with same depth at point.
6051 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6052 If point is at the beginning of a headline, insert a sibling before the
6053 current headline.  If point is in the middle of a headline, split the headline
6054 at that position and make the rest of the headline part of the sibling below
6055 the current headline."
6056   (interactive "P")
6057   (if (= (buffer-size) 0)
6058       (insert "\n* ")
6059     (when (or force-heading (not (org-insert-item)))
6060       (let* ((head (save-excursion
6061                      (condition-case nil
6062                          (progn
6063                            (org-back-to-heading)
6064                            (match-string 0))
6065                        (error "*"))))
6066              (blank (cdr (assq 'heading org-blank-before-new-entry)))
6067              pos)
6068         (cond
6069          ((and (org-on-heading-p) (bolp)
6070                (or (bobp)
6071                    (save-excursion (backward-char 1) (not (org-invisible-p)))))
6072           (open-line (if blank 2 1)))
6073          ((and (bolp)
6074                (or (bobp)
6075                    (save-excursion
6076                      (backward-char 1) (not (org-invisible-p)))))
6077           nil)
6078          (t (newline (if blank 2 1))))
6079         (insert head) (just-one-space)
6080         (setq pos (point))
6081         (end-of-line 1)
6082         (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6083         (run-hooks 'org-insert-heading-hook)))))
6085 (defun org-insert-heading-after-current ()
6086   "Insert a new heading with same level as current, after current subtree."
6087   (interactive)
6088   (org-back-to-heading)
6089   (org-insert-heading)
6090   (org-move-subtree-down)
6091   (end-of-line 1))
6093 (defun org-insert-todo-heading (arg)
6094   "Insert a new heading with the same level and TODO state as current heading.
6095 If the heading has no TODO state, or if the state is DONE, use the first
6096 state (TODO by default).  Also with prefix arg, force first state."
6097   (interactive "P")
6098   (when (not (org-insert-item 'checkbox))
6099     (org-insert-heading)
6100     (save-excursion
6101       (org-back-to-heading)
6102       (outline-previous-heading)
6103       (looking-at org-todo-line-regexp))
6104     (if (or arg
6105             (not (match-beginning 2))
6106             (member (match-string 2) org-done-keywords))
6107         (insert (car org-todo-keywords-1) " ")
6108       (insert (match-string 2) " "))))
6110 (defun org-insert-subheading (arg)
6111   "Insert a new subheading and demote it.
6112 Works for outline headings and for plain lists alike."
6113   (interactive "P")
6114   (org-insert-heading arg)
6115   (cond
6116    ((org-on-heading-p) (org-do-demote))
6117    ((org-at-item-p) (org-indent-item 1))))
6119 (defun org-insert-todo-subheading (arg)
6120   "Insert a new subheading with TODO keyword or checkbox and demote it.
6121 Works for outline headings and for plain lists alike."
6122   (interactive "P")
6123   (org-insert-todo-heading arg)
6124   (cond
6125    ((org-on-heading-p) (org-do-demote))
6126    ((org-at-item-p) (org-indent-item 1))))
6128 ;;; Promotion and Demotion
6130 (defun org-promote-subtree ()
6131   "Promote the entire subtree.
6132 See also `org-promote'."
6133   (interactive)
6134   (save-excursion
6135     (org-map-tree 'org-promote))
6136   (org-fix-position-after-promote))
6138 (defun org-demote-subtree ()
6139   "Demote the entire subtree.  See `org-demote'.
6140 See also `org-promote'."
6141   (interactive)
6142   (save-excursion
6143     (org-map-tree 'org-demote))
6144   (org-fix-position-after-promote))
6147 (defun org-do-promote ()
6148   "Promote the current heading higher up the tree.
6149 If the region is active in `transient-mark-mode', promote all headings
6150 in the region."
6151   (interactive)
6152   (save-excursion
6153     (if (org-region-active-p)
6154         (org-map-region 'org-promote (region-beginning) (region-end))
6155       (org-promote)))
6156   (org-fix-position-after-promote))
6158 (defun org-do-demote ()
6159   "Demote the current heading lower down the tree.
6160 If the region is active in `transient-mark-mode', demote all headings
6161 in the region."
6162   (interactive)
6163   (save-excursion
6164     (if (org-region-active-p)
6165         (org-map-region 'org-demote (region-beginning) (region-end))
6166       (org-demote)))
6167   (org-fix-position-after-promote))
6169 (defun org-fix-position-after-promote ()
6170   "Make sure that after pro/demotion cursor position is right."
6171   (let ((pos (point)))
6172     (when (save-excursion
6173             (beginning-of-line 1)
6174             (looking-at org-todo-line-regexp)
6175             (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6176       (cond ((eobp) (insert " "))
6177             ((eolp) (insert " "))
6178             ((equal (char-after) ?\ ) (forward-char 1))))))
6180 (defun org-reduced-level (l)
6181   (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6183 (defun org-get-legal-level (level &optional change)
6184   "Rectify a level change under the influence of `org-odd-levels-only'
6185 LEVEL is a current level, CHANGE is by how much the level should be
6186 modified.  Even if CHANGE is nil, LEVEL may be returned modified because
6187 even level numbers will become the next higher odd number."
6188   (if org-odd-levels-only
6189       (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6190             ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6191             ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6192     (max 1 (+ level change))))
6194 (defun org-promote ()
6195   "Promote the current heading higher up the tree.
6196 If the region is active in `transient-mark-mode', promote all headings
6197 in the region."
6198   (org-back-to-heading t)
6199   (let* ((level (save-match-data (funcall outline-level)))
6200          (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6201          (diff (abs (- level (length up-head) -1))))
6202     (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6203     (replace-match up-head nil t)
6204     ;; Fixup tag positioning
6205     (and org-auto-align-tags (org-set-tags nil t))
6206     (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6208 (defun org-demote ()
6209   "Demote the current heading lower down the tree.
6210 If the region is active in `transient-mark-mode', demote all headings
6211 in the region."
6212   (org-back-to-heading t)
6213   (let* ((level (save-match-data (funcall outline-level)))
6214          (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6215          (diff (abs (- level (length down-head) -1))))
6216     (replace-match down-head nil t)
6217     ;; Fixup tag positioning
6218     (and org-auto-align-tags (org-set-tags nil t))
6219     (if org-adapt-indentation (org-fixup-indentation diff))))
6221 (defun org-map-tree (fun)
6222   "Call FUN for every heading underneath the current one."
6223   (org-back-to-heading)
6224   (let ((level (funcall outline-level)))
6225     (save-excursion
6226       (funcall fun)
6227       (while (and (progn
6228                     (outline-next-heading)
6229                     (> (funcall outline-level) level))
6230                   (not (eobp)))
6231         (funcall fun)))))
6233 (defun org-map-region (fun beg end)
6234   "Call FUN for every heading between BEG and END."
6235   (let ((org-ignore-region t))
6236     (save-excursion
6237       (setq end (copy-marker end))
6238       (goto-char beg)
6239       (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6240                (< (point) end))
6241           (funcall fun))
6242       (while (and (progn
6243                     (outline-next-heading)
6244                     (< (point) end))
6245                   (not (eobp)))
6246         (funcall fun)))))
6248 (defun org-fixup-indentation (diff)
6249   "Change the indentation in the current entry by DIFF
6250 However, if any line in the current entry has no indentation, or if it
6251 would end up with no indentation after the change, nothing at all is done."
6252   (save-excursion
6253     (let ((end (save-excursion (outline-next-heading)
6254                                (point-marker)))
6255           (prohibit (if (> diff 0)
6256                         "^\\S-"
6257                       (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6258           col)
6259       (unless (save-excursion (end-of-line 1)
6260                               (re-search-forward prohibit end t))
6261         (while (and (< (point) end)
6262                     (re-search-forward "^[ \t]+" end t))
6263           (goto-char (match-end 0))
6264           (setq col (current-column))
6265           (if (< diff 0) (replace-match ""))
6266           (indent-to (+ diff col))))
6267       (move-marker end nil))))
6269 (defun org-convert-to-odd-levels ()
6270   "Convert an org-mode file with all levels allowed to one with odd levels.
6271 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6272 level 5 etc."
6273   (interactive)
6274   (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6275     (let ((org-odd-levels-only nil) n)
6276       (save-excursion
6277         (goto-char (point-min))
6278         (while (re-search-forward "^\\*\\*+ " nil t)
6279           (setq n (- (length (match-string 0)) 2))
6280           (while (>= (setq n (1- n)) 0)
6281             (org-demote))
6282           (end-of-line 1))))))
6285 (defun org-convert-to-oddeven-levels ()
6286   "Convert an org-mode file with only odd levels to one with odd and even levels.
6287 This promotes level 3 to level 2, level 5 to level 3 etc.  If the file contains a
6288 section with an even level, conversion would destroy the structure of the file.  An error
6289 is signaled in this case."
6290   (interactive)
6291   (goto-char (point-min))
6292   ;; First check if there are no even levels
6293   (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6294     (org-show-context t)
6295     (error "Not all levels are odd in this file.  Conversion not possible."))
6296   (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6297     (let ((org-odd-levels-only nil) n)
6298       (save-excursion
6299         (goto-char (point-min))
6300         (while (re-search-forward "^\\*\\*+ " nil t)
6301           (setq n (/ (1- (length (match-string 0))) 2))
6302           (while (>= (setq n (1- n)) 0)
6303             (org-promote))
6304           (end-of-line 1))))))
6306 (defun org-tr-level (n)
6307   "Make N odd if required."
6308   (if org-odd-levels-only (1+ (/ n 2)) n))
6310 ;;; Vertical tree motion, cutting and pasting of subtrees
6312 (defun org-move-subtree-up (&optional arg)
6313   "Move the current subtree up past ARG headlines of the same level."
6314   (interactive "p")
6315   (org-move-subtree-down (- (prefix-numeric-value arg))))
6317 (defun org-move-subtree-down (&optional arg)
6318   "Move the current subtree down past ARG headlines of the same level."
6319   (interactive "p")
6320   (setq arg (prefix-numeric-value arg))
6321   (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6322                    'outline-get-last-sibling))
6323         (ins-point (make-marker))
6324         (cnt (abs arg))
6325         beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6326     ;; Select the tree
6327     (org-back-to-heading)
6328     (setq beg0 (point))
6329     (save-excursion
6330       (setq ne-beg (org-back-over-empty-lines))
6331       (setq beg (point)))
6332     (save-match-data
6333       (save-excursion (outline-end-of-heading)
6334                       (setq folded (org-invisible-p)))
6335       (outline-end-of-subtree))
6336     (outline-next-heading)
6337     (setq ne-end (org-back-over-empty-lines))
6338     (setq end (point))
6339     (goto-char beg0)
6340     (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6341       ;; include less whitespace
6342       (save-excursion
6343         (goto-char beg)
6344         (forward-line (- ne-beg ne-end))
6345         (setq beg (point))))
6346     ;; Find insertion point, with error handling
6347     (while (> cnt 0)
6348       (or (and (funcall movfunc) (looking-at outline-regexp))
6349           (progn (goto-char beg0)
6350                  (error "Cannot move past superior level or buffer limit")))
6351       (setq cnt (1- cnt)))
6352     (if (> arg 0)
6353         ;; Moving forward - still need to move over subtree
6354         (progn (org-end-of-subtree t t)
6355                (save-excursion
6356                  (org-back-over-empty-lines)
6357                  (or (bolp) (newline)))))
6358     (setq ne-ins (org-back-over-empty-lines))
6359     (move-marker ins-point (point))
6360     (setq txt (buffer-substring beg end))
6361     (delete-region beg end)
6362     (outline-flag-region (1- beg) beg nil)
6363     (outline-flag-region (1- (point)) (point) nil)
6364     (insert txt)
6365     (or (bolp) (insert "\n"))
6366     (setq ins-end (point))
6367     (goto-char ins-point)
6368     (org-skip-whitespace)
6369     (when (and (< arg 0)
6370                (org-first-sibling-p)
6371                (> ne-ins ne-beg))
6372       ;; Move whitespace back to beginning
6373       (save-excursion
6374         (goto-char ins-end)
6375         (let ((kill-whole-line t))
6376           (kill-line (- ne-ins ne-beg)) (point)))
6377       (insert (make-string (- ne-ins ne-beg) ?\n)))
6378     (move-marker ins-point nil)
6379     (org-compact-display-after-subtree-move)
6380     (unless folded
6381       (org-show-entry)
6382       (show-children)
6383       (org-cycle-hide-drawers 'children))))
6385 (defvar org-subtree-clip ""
6386   "Clipboard for cut and paste of subtrees.
6387 This is actually only a copy of the kill, because we use the normal kill
6388 ring.  We need it to check if the kill was created by `org-copy-subtree'.")
6390 (defvar org-subtree-clip-folded nil
6391   "Was the last copied subtree folded?
6392 This is used to fold the tree back after pasting.")
6394 (defun org-cut-subtree (&optional n)
6395   "Cut the current subtree into the clipboard.
6396 With prefix arg N, cut this many sequential subtrees.
6397 This is a short-hand for marking the subtree and then cutting it."
6398   (interactive "p")
6399   (org-copy-subtree n 'cut))
6401 (defun org-copy-subtree (&optional n cut)
6402   "Cut the current subtree into the clipboard.
6403 With prefix arg N, cut this many sequential subtrees.
6404 This is a short-hand for marking the subtree and then copying it.
6405 If CUT is non-nil, actually cut the subtree."
6406   (interactive "p")
6407   (let (beg end folded (beg0 (point)))
6408     (if (interactive-p)
6409         (org-back-to-heading nil) ; take what looks like a subtree
6410       (org-back-to-heading t)) ; take what is really there
6411     (org-back-over-empty-lines)
6412     (setq beg (point))
6413     (skip-chars-forward " \t\r\n")
6414     (save-match-data
6415       (save-excursion (outline-end-of-heading)
6416                       (setq folded (org-invisible-p)))
6417       (condition-case nil
6418           (outline-forward-same-level (1- n))
6419         (error nil))
6420       (org-end-of-subtree t t))
6421     (org-back-over-empty-lines)
6422     (setq end (point))
6423     (goto-char beg0)
6424     (when (> end beg)
6425       (setq org-subtree-clip-folded folded)
6426       (if cut (kill-region beg end) (copy-region-as-kill beg end))
6427       (setq org-subtree-clip (current-kill 0))
6428       (message "%s: Subtree(s) with %d characters"
6429                (if cut "Cut" "Copied")
6430                (length org-subtree-clip)))))
6432 (defun org-paste-subtree (&optional level tree)
6433   "Paste the clipboard as a subtree, with modification of headline level.
6434 The entire subtree is promoted or demoted in order to match a new headline
6435 level.  By default, the new level is derived from the visible headings
6436 before and after the insertion point, and taken to be the inferior headline
6437 level of the two.  So if the previous visible heading is level 3 and the
6438 next is level 4 (or vice versa), level 4 will be used for insertion.
6439 This makes sure that the subtree remains an independent subtree and does
6440 not swallow low level entries.
6442 You can also force a different level, either by using a numeric prefix
6443 argument, or by inserting the heading marker by hand.  For example, if the
6444 cursor is after \"*****\", then the tree will be shifted to level 5.
6446 If you want to insert the tree as is, just use \\[yank].
6448 If optional TREE is given, use this text instead of the kill ring."
6449   (interactive "P")
6450   (unless (org-kill-is-subtree-p tree)
6451     (error "%s"
6452      (substitute-command-keys
6453       "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6454   (let* ((txt (or tree (and kill-ring (current-kill 0))))
6455          (^re (concat "^\\(" outline-regexp "\\)"))
6456          (re  (concat "\\(" outline-regexp "\\)"))
6457          (^re_ (concat "\\(\\*+\\)[  \t]*"))
6459          (old-level (if (string-match ^re txt)
6460                         (- (match-end 0) (match-beginning 0) 1)
6461                       -1))
6462          (force-level (cond (level (prefix-numeric-value level))
6463                             ((string-match
6464                               ^re_ (buffer-substring (point-at-bol) (point)))
6465                              (- (match-end 1) (match-beginning 1)))
6466                             (t nil)))
6467          (previous-level (save-excursion
6468                            (condition-case nil
6469                                (progn
6470                                  (outline-previous-visible-heading 1)
6471                                  (if (looking-at re)
6472                                      (- (match-end 0) (match-beginning 0) 1)
6473                                    1))
6474                              (error 1))))
6475          (next-level (save-excursion
6476                        (condition-case nil
6477                            (progn
6478                              (or (looking-at outline-regexp)
6479                                  (outline-next-visible-heading 1))
6480                              (if (looking-at re)
6481                                  (- (match-end 0) (match-beginning 0) 1)
6482                                1))
6483                          (error 1))))
6484          (new-level (or force-level (max previous-level next-level)))
6485          (shift (if (or (= old-level -1)
6486                         (= new-level -1)
6487                         (= old-level new-level))
6488                     0
6489                   (- new-level old-level)))
6490          (delta (if (> shift 0) -1 1))
6491          (func (if (> shift 0) 'org-demote 'org-promote))
6492          (org-odd-levels-only nil)
6493          beg end)
6494     ;; Remove the forced level indicator
6495     (if force-level
6496         (delete-region (point-at-bol) (point)))
6497     ;; Paste
6498     (beginning-of-line 1)
6499     (org-back-over-empty-lines)   ;; FIXME: correct fix????
6500     (setq beg (point))
6501     (insert-before-markers txt)   ;; FIXME: correct fix????
6502     (unless (string-match "\n\\'" txt) (insert "\n"))
6503     (setq end (point))
6504     (goto-char beg)
6505     (skip-chars-forward " \t\n\r")
6506     (setq beg (point))
6507     ;; Shift if necessary
6508     (unless (= shift 0)
6509       (save-restriction
6510         (narrow-to-region beg end)
6511         (while (not (= shift 0))
6512           (org-map-region func (point-min) (point-max))
6513           (setq shift (+ delta shift)))
6514         (goto-char (point-min))))
6515     (when (interactive-p)
6516       (message "Clipboard pasted as level %d subtree" new-level))
6517     (if (and kill-ring
6518              (eq org-subtree-clip (current-kill 0))
6519              org-subtree-clip-folded)
6520         ;; The tree was folded before it was killed/copied
6521         (hide-subtree))))
6523 (defun org-kill-is-subtree-p (&optional txt)
6524   "Check if the current kill is an outline subtree, or a set of trees.
6525 Returns nil if kill does not start with a headline, or if the first
6526 headline level is not the largest headline level in the tree.
6527 So this will actually accept several entries of equal levels as well,
6528 which is OK for `org-paste-subtree'.
6529 If optional TXT is given, check this string instead of the current kill."
6530   (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6531          (start-level (and kill
6532                            (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6533                                                  org-outline-regexp "\\)")
6534                                          kill)
6535                            (- (match-end 2) (match-beginning 2) 1)))
6536          (re (concat "^" org-outline-regexp))
6537          (start (1+ (match-beginning 2))))
6538     (if (not start-level)
6539         (progn
6540           nil)  ;; does not even start with a heading
6541       (catch 'exit
6542         (while (setq start (string-match re kill (1+ start)))
6543           (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6544             (throw 'exit nil)))
6545         t))))
6547 (defun org-narrow-to-subtree ()
6548   "Narrow buffer to the current subtree."
6549   (interactive)
6550   (save-excursion
6551     (narrow-to-region
6552      (progn (org-back-to-heading) (point))
6553      (progn (org-end-of-subtree t t) (point)))))
6556 ;;; Outline Sorting
6558 (defun org-sort (with-case)
6559   "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6560 Optional argument WITH-CASE means sort case-sensitively."
6561   (interactive "P")
6562   (if (org-at-table-p)
6563       (org-call-with-arg 'org-table-sort-lines with-case)
6564     (org-call-with-arg 'org-sort-entries-or-items with-case)))
6566 (defvar org-priority-regexp) ; defined later in the file
6568 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6569   "Sort entries on a certain level of an outline tree.
6570 If there is an active region, the entries in the region are sorted.
6571 Else, if the cursor is before the first entry, sort the top-level items.
6572 Else, the children of the entry at point are sorted.
6574 Sorting can be alphabetically, numerically, and by date/time as given by
6575 the first time stamp in the entry.  The command prompts for the sorting
6576 type unless it has been given to the function through the SORTING-TYPE
6577 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6578 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6579 called with point at the beginning of the record.  It must return either
6580 a string or a number that should serve as the sorting key for that record.
6582 Comparing entries ignores case by default.  However, with an optional argument
6583 WITH-CASE, the sorting considers case as well."
6584   (interactive "P")
6585   (let ((case-func (if with-case 'identity 'downcase))
6586         start beg end stars re re2
6587         txt what tmp plain-list-p)
6588     ;; Find beginning and end of region to sort
6589     (cond
6590      ((org-region-active-p)
6591       ;; we will sort the region
6592       (setq end (region-end)
6593             what "region")
6594       (goto-char (region-beginning))
6595       (if (not (org-on-heading-p)) (outline-next-heading))
6596       (setq start (point)))
6597      ((org-at-item-p)
6598       ;; we will sort this plain list
6599       (org-beginning-of-item-list) (setq start (point))
6600       (org-end-of-item-list) (setq end (point))
6601       (goto-char start)
6602       (setq plain-list-p t
6603             what "plain list"))
6604      ((or (org-on-heading-p)
6605           (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6606       ;; we will sort the children of the current headline
6607       (org-back-to-heading)
6608       (setq start (point)
6609             end (progn (org-end-of-subtree t t)
6610                        (org-back-over-empty-lines)
6611                        (point))
6612             what "children")
6613       (goto-char start)
6614       (show-subtree)
6615       (outline-next-heading))
6616      (t
6617       ;; we will sort the top-level entries in this file
6618       (goto-char (point-min))
6619       (or (org-on-heading-p) (outline-next-heading))
6620       (setq start (point) end (point-max) what "top-level")
6621       (goto-char start)
6622       (show-all)))
6624     (setq beg (point))
6625     (if (>= beg end) (error "Nothing to sort"))
6627     (unless plain-list-p
6628       (looking-at "\\(\\*+\\)")
6629       (setq stars (match-string 1)
6630             re (concat "^" (regexp-quote stars) " +")
6631             re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6632             txt (buffer-substring beg end))
6633       (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6634       (if (and (not (equal stars "*")) (string-match re2 txt))
6635           (error "Region to sort contains a level above the first entry")))
6637     (unless sorting-type
6638       (message
6639        (if plain-list-p
6640            "Sort %s: [a]lpha [n]umeric [t]ime [f]unc  A/N/T/F means reversed:"
6641          "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc  A/N/T/P/F means reversed:")
6642        what)
6643       (setq sorting-type (read-char-exclusive))
6645       (and (= (downcase sorting-type) ?f)
6646            (setq getkey-func
6647                  (completing-read "Sort using function: "
6648                                   obarray 'fboundp t nil nil))
6649            (setq getkey-func (intern getkey-func)))
6651       (and (= (downcase sorting-type) ?r)
6652            (setq property
6653                  (completing-read "Property: "
6654                                   (mapcar 'list (org-buffer-property-keys t))
6655                                   nil t))))
6657     (message "Sorting entries...")
6659     (save-restriction
6660       (narrow-to-region start end)
6662       (let ((dcst (downcase sorting-type))
6663             (now (current-time)))
6664         (sort-subr
6665          (/= dcst sorting-type)
6666          ;; This function moves to the beginning character of the "record" to
6667          ;; be sorted.
6668          (if plain-list-p
6669              (lambda nil
6670                (if (org-at-item-p) t (goto-char (point-max))))
6671            (lambda nil
6672              (if (re-search-forward re nil t)
6673                  (goto-char (match-beginning 0))
6674                (goto-char (point-max)))))
6675          ;; This function moves to the last character of the "record" being
6676          ;; sorted.
6677          (if plain-list-p
6678              'org-end-of-item
6679            (lambda nil
6680              (save-match-data
6681                (condition-case nil
6682                    (outline-forward-same-level 1)
6683                  (error
6684                   (goto-char (point-max)))))))
6686          ;; This function returns the value that gets sorted against.
6687          (if plain-list-p
6688              (lambda nil
6689                (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6690                  (cond
6691                   ((= dcst ?n)
6692                    (string-to-number (buffer-substring (match-end 0)
6693                                                        (point-at-eol))))
6694                   ((= dcst ?a)
6695                    (buffer-substring (match-end 0) (point-at-eol)))
6696                   ((= dcst ?t)
6697                    (if (re-search-forward org-ts-regexp
6698                                           (point-at-eol) t)
6699                        (org-time-string-to-time (match-string 0))
6700                      now))
6701                   ((= dcst ?f)
6702                    (if getkey-func
6703                        (progn
6704                          (setq tmp (funcall getkey-func))
6705                          (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6706                          tmp)
6707                      (error "Invalid key function `%s'" getkey-func)))
6708                   (t (error "Invalid sorting type `%c'" sorting-type)))))
6709            (lambda nil
6710              (cond
6711               ((= dcst ?n)
6712                (if (looking-at outline-regexp)
6713                    (string-to-number (buffer-substring (match-end 0)
6714                                                        (point-at-eol)))
6715                  nil))
6716               ((= dcst ?a)
6717                (funcall case-func (buffer-substring (point-at-bol)
6718                                                     (point-at-eol))))
6719               ((= dcst ?t)
6720                (if (re-search-forward org-ts-regexp
6721                                       (save-excursion
6722                                         (forward-line 2)
6723                                         (point)) t)
6724                    (org-time-string-to-time (match-string 0))
6725                  now))
6726               ((= dcst ?p)
6727                (if (re-search-forward org-priority-regexp (point-at-eol) t)
6728                    (string-to-char (match-string 2))
6729                  org-default-priority))
6730               ((= dcst ?r)
6731                (or (org-entry-get nil property) ""))
6732               ((= dcst ?f)
6733                (if getkey-func
6734                    (progn
6735                      (setq tmp (funcall getkey-func))
6736                      (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6737                      tmp)
6738                  (error "Invalid key function `%s'" getkey-func)))
6739               (t (error "Invalid sorting type `%c'" sorting-type)))))
6740          nil
6741          (cond
6742           ((= dcst ?a) 'string<)
6743           ((= dcst ?t) 'time-less-p)
6744           (t nil)))))
6745     (message "Sorting entries...done")))
6747 (defun org-do-sort (table what &optional with-case sorting-type)
6748   "Sort TABLE of WHAT according to SORTING-TYPE.
6749 The user will be prompted for the SORTING-TYPE if the call to this
6750 function does not specify it.  WHAT is only for the prompt, to indicate
6751 what is being sorted.  The sorting key will be extracted from
6752 the car of the elements of the table.
6753 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6754   (unless sorting-type
6755     (message
6756      "Sort %s: [a]lphabetic. [n]umeric. [t]ime.  A/N/T means reversed:"
6757      what)
6758     (setq sorting-type (read-char-exclusive)))
6759   (let ((dcst (downcase sorting-type))
6760         extractfun comparefun)
6761     ;; Define the appropriate functions
6762     (cond
6763      ((= dcst ?n)
6764       (setq extractfun 'string-to-number
6765             comparefun (if (= dcst sorting-type) '< '>)))
6766      ((= dcst ?a)
6767       (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6768                          (lambda(x) (downcase (org-sort-remove-invisible x))))
6769             comparefun (if (= dcst sorting-type)
6770                            'string<
6771                          (lambda (a b) (and (not (string< a b))
6772                                             (not (string= a b)))))))
6773      ((= dcst ?t)
6774       (setq extractfun
6775             (lambda (x)
6776               (if (string-match org-ts-regexp x)
6777                   (time-to-seconds
6778                    (org-time-string-to-time (match-string 0 x)))
6779                 0))
6780             comparefun (if (= dcst sorting-type) '< '>)))
6781      (t (error "Invalid sorting type `%c'" sorting-type)))
6783     (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6784                   table)
6785           (lambda (a b) (funcall comparefun (car a) (car b))))))
6787 ;;;; Plain list items, including checkboxes
6789 ;;; Plain list items
6791 (defun org-at-item-p ()
6792   "Is point in a line starting a hand-formatted item?"
6793   (let ((llt org-plain-list-ordered-item-terminator))
6794     (save-excursion
6795       (goto-char (point-at-bol))
6796       (looking-at
6797        (cond
6798         ((eq llt t)  "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6799         ((= llt ?.)  "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6800         ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6801         (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6803 (defun org-in-item-p ()
6804   "It the cursor inside a plain list item.
6805 Does not have to be the first line."
6806   (save-excursion
6807     (condition-case nil
6808         (progn
6809           (org-beginning-of-item)
6810           (org-at-item-p)
6811           t)
6812       (error nil))))
6814 (defun org-insert-item (&optional checkbox)
6815   "Insert a new item at the current level.
6816 Return t when things worked, nil when we are not in an item."
6817   (when (save-excursion
6818           (condition-case nil
6819               (progn
6820                 (org-beginning-of-item)
6821                 (org-at-item-p)
6822                 (if (org-invisible-p) (error "Invisible item"))
6823                 t)
6824             (error nil)))
6825     (let* ((bul (match-string 0))
6826            (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6827                                 (match-end 0)))
6828            (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6829            pos)
6830       (cond
6831        ((and (org-at-item-p) (<= (point) eow))
6832         ;; before the bullet
6833         (beginning-of-line 1)
6834         (open-line (if blank 2 1)))
6835        ((<= (point) eow)
6836         (beginning-of-line 1))
6837        (t (newline (if blank 2 1))))
6838       (insert bul (if checkbox "[ ]" ""))
6839       (just-one-space)
6840       (setq pos (point))
6841       (end-of-line 1)
6842       (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6843     (org-maybe-renumber-ordered-list)
6844     (and checkbox (org-update-checkbox-count-maybe))
6845     t))
6847 ;;; Checkboxes
6849 (defun org-at-item-checkbox-p ()
6850   "Is point at a line starting a plain-list item with a checklet?"
6851   (and (org-at-item-p)
6852        (save-excursion
6853          (goto-char (match-end 0))
6854          (skip-chars-forward " \t")
6855          (looking-at "\\[[- X]\\]"))))
6857 (defun org-toggle-checkbox (&optional arg)
6858   "Toggle the checkbox in the current line."
6859   (interactive "P")
6860   (catch 'exit
6861     (let (beg end status (firstnew 'unknown))
6862       (cond
6863        ((org-region-active-p)
6864         (setq beg (region-beginning) end (region-end)))
6865        ((org-on-heading-p)
6866         (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6867        ((org-at-item-checkbox-p)
6868         (let ((pos (point)))
6869           (replace-match
6870            (cond (arg "[-]")
6871                  ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6872                  (t "[ ]"))
6873            t t)
6874           (goto-char pos))
6875         (throw 'exit t))
6876        (t (error "Not at a checkbox or heading, and no active region")))
6877       (save-excursion
6878         (goto-char beg)
6879         (while (< (point) end)
6880           (when (org-at-item-checkbox-p)
6881             (setq status (equal (match-string 0) "[X]"))
6882             (when (eq firstnew 'unknown)
6883               (setq firstnew (not status)))
6884             (replace-match
6885              (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6886           (beginning-of-line 2)))))
6887   (org-update-checkbox-count-maybe))
6889 (defun org-update-checkbox-count-maybe ()
6890   "Update checkbox statistics unless turned off by user."
6891   (when org-provide-checkbox-statistics
6892     (org-update-checkbox-count)))
6894 (defun org-update-checkbox-count (&optional all)
6895   "Update the checkbox statistics in the current section.
6896 This will find all statistic cookies like [57%] and [6/12] and update them
6897 with the current numbers.  With optional prefix argument ALL, do this for
6898 the whole buffer."
6899   (interactive "P")
6900   (save-excursion
6901     (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
6902            (beg (condition-case nil
6903                     (progn (outline-back-to-heading) (point))
6904                   (error (point-min))))
6905            (end (move-marker (make-marker)
6906                              (progn (outline-next-heading) (point))))
6907            (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
6908            (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
6909            b1 e1 f1 c-on c-off lim (cstat 0))
6910       (when all
6911         (goto-char (point-min))
6912         (outline-next-heading)
6913         (setq beg (point) end (point-max)))
6914       (goto-char beg)
6915       (while (re-search-forward re end t)
6916         (setq cstat (1+ cstat)
6917               b1 (match-beginning 0)
6918               e1 (match-end 0)
6919               f1 (match-beginning 1)
6920               lim (cond
6921                    ((org-on-heading-p) (outline-next-heading) (point))
6922                    ((org-at-item-p) (org-end-of-item) (point))
6923                    (t nil))
6924               c-on 0 c-off 0)
6925         (goto-char e1)
6926         (when lim
6927           (while (re-search-forward re-box lim t)
6928             (if (member (match-string 2) '("[ ]" "[-]"))
6929                 (setq c-off (1+ c-off))
6930               (setq c-on (1+ c-on))))
6931 ;         (delete-region b1 e1)
6932           (goto-char b1)
6933           (insert (if f1
6934                       (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
6935                     (format "[%d/%d]" c-on (+ c-on c-off))))
6936           (and (looking-at "\\[.*?\\]")
6937                (replace-match ""))))
6938       (when (interactive-p)
6939         (message "Checkbox satistics updated %s (%d places)"
6940                  (if all "in entire file" "in current outline entry") cstat)))))
6942 (defun org-get-checkbox-statistics-face ()
6943   "Select the face for checkbox statistics.
6944 The face will be `org-done' when all relevant boxes are checked.  Otherwise
6945 it will be `org-todo'."
6946   (if (match-end 1)
6947       (if (equal (match-string 1) "100%") 'org-done 'org-todo)
6948     (if (and (> (match-end 2) (match-beginning 2))
6949              (equal (match-string 2) (match-string 3)))
6950         'org-done
6951       'org-todo)))
6953 (defun org-get-indentation (&optional line)
6954   "Get the indentation of the current line, interpreting tabs.
6955 When LINE is given, assume it represents a line and compute its indentation."
6956   (if line
6957       (if (string-match "^ *" (org-remove-tabs line))
6958           (match-end 0))
6959     (save-excursion
6960       (beginning-of-line 1)
6961       (skip-chars-forward " \t")
6962       (current-column))))
6964 (defun org-remove-tabs (s &optional width)
6965   "Replace tabulators in S with spaces.
6966 Assumes that s is a single line, starting in column 0."
6967   (setq width (or width tab-width))
6968   (while (string-match "\t" s)
6969     (setq s (replace-match
6970              (make-string
6971               (- (* width (/ (+ (match-beginning 0) width) width))
6972                  (match-beginning 0)) ?\ )
6973              t t s)))
6974   s)
6976 (defun org-fix-indentation (line ind)
6977   "Fix indentation in LINE.
6978 IND is a cons cell with target and minimum indentation.
6979 If the current indenation in LINE is smaller than the minimum,
6980 leave it alone.  If it is larger than ind, set it to the target."
6981   (let* ((l (org-remove-tabs line))
6982          (i (org-get-indentation l))
6983          (i1 (car ind)) (i2 (cdr ind)))
6984     (if (>= i i2) (setq l (substring line i2)))
6985     (if (> i1 0)
6986         (concat (make-string i1 ?\ ) l)
6987       l)))
6989 (defcustom org-empty-line-terminates-plain-lists nil
6990   "Non-nil means, an empty line ends all plain list levels.
6991 When nil, empty lines are part of the preceeding item."
6992   :group 'org-plain-lists
6993   :type 'boolean)
6995 (defun org-beginning-of-item ()
6996   "Go to the beginning of the current hand-formatted item.
6997 If the cursor is not in an item, throw an error."
6998   (interactive)
6999   (let ((pos (point))
7000         (limit (save-excursion
7001                  (condition-case nil
7002                      (progn
7003                        (org-back-to-heading)
7004                        (beginning-of-line 2) (point))
7005                    (error (point-min)))))
7006         (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7007         ind ind1)
7008     (if (org-at-item-p)
7009         (beginning-of-line 1)
7010       (beginning-of-line 1)
7011       (skip-chars-forward " \t")
7012       (setq ind (current-column))
7013       (if (catch 'exit
7014             (while t
7015               (beginning-of-line 0)
7016               (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7018               (if (looking-at "[ \t]*$")
7019                   (setq ind1 ind-empty)
7020                 (skip-chars-forward " \t")
7021                 (setq ind1 (current-column)))
7022               (if (< ind1 ind)
7023                   (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7024           nil
7025         (goto-char pos)
7026         (error "Not in an item")))))
7028 (defun org-end-of-item ()
7029   "Go to the end of the current hand-formatted item.
7030 If the cursor is not in an item, throw an error."
7031   (interactive)
7032   (let* ((pos (point))
7033          ind1
7034          (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7035          (limit (save-excursion (outline-next-heading) (point)))
7036          (ind (save-excursion
7037                 (org-beginning-of-item)
7038                 (skip-chars-forward " \t")
7039                 (current-column)))
7040          (end (catch 'exit
7041                 (while t
7042                   (beginning-of-line 2)
7043                   (if (eobp) (throw 'exit (point)))
7044                   (if (>= (point) limit) (throw 'exit (point-at-bol)))
7045                   (if (looking-at "[ \t]*$")
7046                       (setq ind1 ind-empty)
7047                     (skip-chars-forward " \t")
7048                     (setq ind1 (current-column)))
7049                   (if (<= ind1 ind)
7050                       (throw 'exit (point-at-bol)))))))
7051     (if end
7052         (goto-char end)
7053       (goto-char pos)
7054       (error "Not in an item"))))
7056 (defun org-next-item ()
7057   "Move to the beginning of the next item in the current plain list.
7058 Error if not at a plain list, or if this is the last item in the list."
7059   (interactive)
7060   (let (ind ind1 (pos (point)))
7061     (org-beginning-of-item)
7062     (setq ind (org-get-indentation))
7063     (org-end-of-item)
7064     (setq ind1 (org-get-indentation))
7065     (unless (and (org-at-item-p) (= ind ind1))
7066       (goto-char pos)
7067       (error "On last item"))))
7069 (defun org-previous-item ()
7070   "Move to the beginning of the previous item in the current plain list.
7071 Error if not at a plain list, or if this is the first item in the list."
7072   (interactive)
7073   (let (beg ind ind1 (pos (point)))
7074     (org-beginning-of-item)
7075     (setq beg (point))
7076     (setq ind (org-get-indentation))
7077     (goto-char beg)
7078     (catch 'exit
7079       (while t
7080         (beginning-of-line 0)
7081         (if (looking-at "[ \t]*$")
7082             nil
7083           (if (<= (setq ind1 (org-get-indentation)) ind)
7084               (throw 'exit t)))))
7085     (condition-case nil
7086         (if (or (not (org-at-item-p))
7087                 (< ind1 (1- ind)))
7088             (error "")
7089           (org-beginning-of-item))
7090       (error (goto-char pos)
7091              (error "On first item")))))
7093 (defun org-first-list-item-p ()
7094   "Is this heading the item in a plain list?"
7095   (unless (org-at-item-p)
7096     (error "Not at a plain list item"))
7097   (org-beginning-of-item)
7098   (= (point) (save-excursion (org-beginning-of-item-list))))
7100 (defun org-move-item-down ()
7101   "Move the plain list item at point down, i.e. swap with following item.
7102 Subitems (items with larger indentation) are considered part of the item,
7103 so this really moves item trees."
7104   (interactive)
7105   (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7106     (org-beginning-of-item)
7107     (setq beg0 (point))
7108     (save-excursion
7109       (setq ne-beg (org-back-over-empty-lines))
7110       (setq beg (point)))
7111     (goto-char beg0)
7112     (setq ind (org-get-indentation))
7113     (org-end-of-item)
7114     (setq end0 (point))
7115     (setq ind1 (org-get-indentation))
7116     (setq ne-end (org-back-over-empty-lines))
7117     (setq end (point))
7118     (goto-char beg0)
7119     (when (and (org-first-list-item-p) (< ne-end ne-beg))
7120       ;; include less whitespace
7121       (save-excursion
7122         (goto-char beg)
7123         (forward-line (- ne-beg ne-end))
7124         (setq beg (point))))
7125     (goto-char end0)
7126     (if (and (org-at-item-p) (= ind ind1))
7127         (progn
7128           (org-end-of-item)
7129           (org-back-over-empty-lines)
7130           (setq txt (buffer-substring beg end))
7131           (save-excursion
7132             (delete-region beg end))
7133           (setq pos (point))
7134           (insert txt)
7135           (goto-char pos) (org-skip-whitespace)
7136           (org-maybe-renumber-ordered-list))
7137       (goto-char pos)
7138       (error "Cannot move this item further down"))))
7140 (defun org-move-item-up (arg)
7141   "Move the plain list item at point up, i.e. swap with previous item.
7142 Subitems (items with larger indentation) are considered part of the item,
7143 so this really moves item trees."
7144   (interactive "p")
7145   (let (beg beg0 end end0 ind ind1 (pos (point)) txt
7146             ne-beg ne-end ne-ins ins-end)
7147     (org-beginning-of-item)
7148     (setq beg0 (point))
7149     (setq ind (org-get-indentation))
7150     (save-excursion
7151       (setq ne-beg (org-back-over-empty-lines))
7152       (setq beg (point)))
7153     (goto-char beg0)
7154     (org-end-of-item)
7155     (setq ne-end (org-back-over-empty-lines))
7156     (setq end (point))
7157     (goto-char beg0)
7158     (catch 'exit
7159       (while t
7160         (beginning-of-line 0)
7161         (if (looking-at "[ \t]*$")
7162             (if org-empty-line-terminates-plain-lists
7163                 (progn
7164                   (goto-char pos)
7165                   (error "Cannot move this item further up"))
7166               nil)
7167           (if (<= (setq ind1 (org-get-indentation)) ind)
7168               (throw 'exit t)))))
7169     (condition-case nil
7170         (org-beginning-of-item)
7171       (error (goto-char beg)
7172              (error "Cannot move this item further up")))
7173     (setq ind1 (org-get-indentation))
7174     (if (and (org-at-item-p) (= ind ind1))
7175         (progn
7176           (setq ne-ins (org-back-over-empty-lines))
7177           (setq txt (buffer-substring beg end))
7178           (save-excursion
7179             (delete-region beg end))
7180           (setq pos (point))
7181           (insert txt)
7182           (setq ins-end (point))
7183           (goto-char pos) (org-skip-whitespace)
7185           (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7186             ;; Move whitespace back to beginning
7187             (save-excursion
7188               (goto-char ins-end)
7189               (let ((kill-whole-line t))
7190                 (kill-line (- ne-ins ne-beg)) (point)))
7191             (insert (make-string (- ne-ins ne-beg) ?\n)))
7192           
7193           (org-maybe-renumber-ordered-list))
7194       (goto-char pos)
7195       (error "Cannot move this item further up"))))
7197 (defun org-maybe-renumber-ordered-list ()
7198   "Renumber the ordered list at point if setup allows it.
7199 This tests the user option `org-auto-renumber-ordered-lists' before
7200 doing the renumbering."
7201   (interactive)
7202   (when (and org-auto-renumber-ordered-lists
7203              (org-at-item-p))
7204     (if (match-beginning 3)
7205         (org-renumber-ordered-list 1)
7206       (org-fix-bullet-type))))
7208 (defun org-maybe-renumber-ordered-list-safe ()
7209   (condition-case nil
7210       (save-excursion
7211         (org-maybe-renumber-ordered-list))
7212     (error nil)))
7214 (defun org-cycle-list-bullet (&optional which)
7215   "Cycle through the different itemize/enumerate bullets.
7216 This cycle the entire list level through the sequence:
7218    `-'  ->  `+'  ->  `*'  ->  `1.'  ->  `1)'
7220 If WHICH is a string, use that as the new bullet.  If WHICH is an integer,
7221 0 meand `-', 1 means `+' etc."
7222   (interactive "P")
7223   (org-preserve-lc
7224    (org-beginning-of-item-list)
7225    (org-at-item-p)
7226    (beginning-of-line 1)
7227    (let ((current (match-string 0))
7228          (prevp (eq which 'previous))
7229          new)
7230      (setq new (cond
7231                 ((and (numberp which)
7232                       (nth (1- which) '("-" "+" "*" "1." "1)"))))
7233                 ((string-match "-" current) (if prevp "1)" "+"))
7234                 ((string-match "\\+" current)
7235                  (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7236                 ((string-match "\\*" current) (if prevp "+" "1."))
7237                 ((string-match "\\." current) (if prevp "*" "1)"))
7238                 ((string-match ")" current) (if prevp "1." "-"))
7239                 (t (error "This should not happen"))))
7240      (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7241      (org-fix-bullet-type)
7242      (org-maybe-renumber-ordered-list))))
7244 (defun org-get-string-indentation (s)
7245   "What indentation has S due to SPACE and TAB at the beginning of the string?"
7246   (let ((n -1) (i 0) (w tab-width) c)
7247     (catch 'exit
7248       (while (< (setq n (1+ n)) (length s))
7249         (setq c (aref s n))
7250         (cond ((= c ?\ ) (setq i (1+ i)))
7251               ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7252               (t (throw 'exit t)))))
7253     i))
7255 (defun org-renumber-ordered-list (arg)
7256   "Renumber an ordered plain list.
7257 Cursor needs to be in the first line of an item, the line that starts
7258 with something like \"1.\" or \"2)\"."
7259   (interactive "p")
7260   (unless (and (org-at-item-p)
7261                (match-beginning 3))
7262     (error "This is not an ordered list"))
7263   (let ((line (org-current-line))
7264         (col (current-column))
7265         (ind (org-get-string-indentation
7266               (buffer-substring (point-at-bol) (match-beginning 3))))
7267         ;; (term (substring (match-string 3) -1))
7268         ind1 (n (1- arg))
7269         fmt)
7270     ;; find where this list begins
7271     (org-beginning-of-item-list)
7272     (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7273     (setq fmt (concat "%d" (match-string 1)))
7274     (beginning-of-line 0)
7275     ;; walk forward and replace these numbers
7276     (catch 'exit
7277       (while t
7278         (catch 'next
7279           (beginning-of-line 2)
7280           (if (eobp) (throw 'exit nil))
7281           (if (looking-at "[ \t]*$") (throw 'next nil))
7282           (skip-chars-forward " \t") (setq ind1 (current-column))
7283           (if (> ind1 ind) (throw 'next t))
7284           (if (< ind1 ind) (throw 'exit t))
7285           (if (not (org-at-item-p)) (throw 'exit nil))
7286           (delete-region (match-beginning 2) (match-end 2))
7287           (goto-char (match-beginning 2))
7288           (insert (format fmt (setq n (1+ n)))))))
7289     (goto-line line)
7290     (move-to-column col)))
7292 (defun org-fix-bullet-type ()
7293   "Make sure all items in this list have the same bullet as the firsst item."
7294   (interactive)
7295   (unless (org-at-item-p) (error "This is not a list"))
7296   (let ((line (org-current-line))
7297         (col (current-column))
7298         (ind (current-indentation))
7299         ind1 bullet)
7300     ;; find where this list begins
7301     (org-beginning-of-item-list)
7302     (beginning-of-line 1)
7303     ;; find out what the bullet type is
7304     (looking-at "[ \t]*\\(\\S-+\\)")
7305     (setq bullet (match-string 1))
7306     ;; walk forward and replace these numbers
7307     (beginning-of-line 0)
7308     (catch 'exit
7309       (while t
7310         (catch 'next
7311           (beginning-of-line 2)
7312           (if (eobp) (throw 'exit nil))
7313           (if (looking-at "[ \t]*$") (throw 'next nil))
7314           (skip-chars-forward " \t") (setq ind1 (current-column))
7315           (if (> ind1 ind) (throw 'next t))
7316           (if (< ind1 ind) (throw 'exit t))
7317           (if (not (org-at-item-p)) (throw 'exit nil))
7318           (skip-chars-forward " \t")
7319           (looking-at "\\S-+")
7320           (replace-match bullet))))
7321     (goto-line line)
7322     (move-to-column col)
7323     (if (string-match "[0-9]" bullet)
7324         (org-renumber-ordered-list 1))))
7326 (defun org-beginning-of-item-list ()
7327   "Go to the beginning of the current item list.
7328 I.e. to the first item in this list."
7329   (interactive)
7330   (org-beginning-of-item)
7331   (let ((pos (point-at-bol))
7332         (ind (org-get-indentation))
7333         ind1)
7334     ;; find where this list begins
7335     (catch 'exit
7336       (while t
7337         (catch 'next
7338           (beginning-of-line 0)
7339           (if (looking-at "[ \t]*$")
7340               (throw (if (bobp) 'exit 'next) t))
7341           (skip-chars-forward " \t") (setq ind1 (current-column))
7342           (if (or (< ind1 ind)
7343                   (and (= ind1 ind)
7344                        (not (org-at-item-p)))
7345                   (bobp))
7346               (throw 'exit t)
7347             (when (org-at-item-p) (setq pos (point-at-bol)))))))
7348     (goto-char pos)))
7351 (defun org-end-of-item-list ()
7352   "Go to the end of the current item list.
7353 I.e. to the text after the last item."
7354   (interactive)
7355   (org-beginning-of-item)
7356   (let ((pos (point-at-bol))
7357         (ind (org-get-indentation))
7358         ind1)
7359     ;; find where this list begins
7360     (catch 'exit
7361       (while t
7362         (catch 'next
7363           (beginning-of-line 2)
7364           (if (looking-at "[ \t]*$")
7365               (throw (if (eobp) 'exit 'next) t))
7366           (skip-chars-forward " \t") (setq ind1 (current-column))
7367           (if (or (< ind1 ind)
7368                   (and (= ind1 ind)
7369                        (not (org-at-item-p)))
7370                   (eobp))
7371               (progn
7372                 (setq pos (point-at-bol))
7373                 (throw 'exit t))))))
7374     (goto-char pos)))
7377 (defvar org-last-indent-begin-marker (make-marker))
7378 (defvar org-last-indent-end-marker (make-marker))
7380 (defun org-outdent-item (arg)
7381   "Outdent a local list item."
7382   (interactive "p")
7383   (org-indent-item (- arg)))
7385 (defun org-indent-item (arg)
7386   "Indent a local list item."
7387   (interactive "p")
7388   (unless (org-at-item-p)
7389     (error "Not on an item"))
7390   (save-excursion
7391     (let (beg end ind ind1 tmp delta ind-down ind-up)
7392       (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7393           (setq beg org-last-indent-begin-marker
7394                 end org-last-indent-end-marker)
7395         (org-beginning-of-item)
7396         (setq beg (move-marker org-last-indent-begin-marker (point)))
7397         (org-end-of-item)
7398         (setq end (move-marker org-last-indent-end-marker (point))))
7399       (goto-char beg)
7400       (setq tmp (org-item-indent-positions)
7401             ind (car tmp)
7402             ind-down (nth 2 tmp)
7403             ind-up (nth 1 tmp)
7404             delta (if (> arg 0)
7405                       (if ind-down (- ind-down ind) 2)
7406                     (if ind-up (- ind-up ind) -2)))
7407       (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7408       (while (< (point) end)
7409         (beginning-of-line 1)
7410         (skip-chars-forward " \t") (setq ind1 (current-column))
7411         (delete-region (point-at-bol) (point))
7412         (or (eolp) (indent-to-column (+ ind1 delta)))
7413         (beginning-of-line 2))))
7414   (org-fix-bullet-type)
7415   (org-maybe-renumber-ordered-list-safe)
7416   (save-excursion
7417     (beginning-of-line 0)
7418     (condition-case nil (org-beginning-of-item) (error nil))
7419     (org-maybe-renumber-ordered-list-safe)))
7421 (defun org-item-indent-positions ()
7422   "Return indentation for plain list items.
7423 This returns a list with three values:  The current indentation, the
7424 parent indentation and the indentation a child should habe.
7425 Assumes cursor in item line."
7426   (let* ((bolpos (point-at-bol))
7427          (ind (org-get-indentation))
7428          ind-down ind-up pos)
7429     (save-excursion
7430       (org-beginning-of-item-list)
7431       (skip-chars-backward "\n\r \t")
7432       (when (org-in-item-p)
7433         (org-beginning-of-item)
7434         (setq ind-up (org-get-indentation))))
7435     (setq pos (point))
7436     (save-excursion
7437       (cond
7438        ((and (condition-case nil (progn (org-previous-item) t)
7439                (error nil))
7440              (or (forward-char 1) t)
7441              (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7442         (setq ind-down (org-get-indentation)))
7443        ((and (goto-char pos)
7444              (org-at-item-p))
7445         (goto-char (match-end 0))
7446         (skip-chars-forward " \t")
7447         (setq ind-down (current-column)))))
7448     (list ind ind-up ind-down)))
7450 ;;; The orgstruct minor mode
7452 ;; Define a minor mode which can be used in other modes in order to
7453 ;; integrate the org-mode structure editing commands.
7455 ;; This is really a hack, because the org-mode structure commands use
7456 ;; keys which normally belong to the major mode.  Here is how it
7457 ;; works: The minor mode defines all the keys necessary to operate the
7458 ;; structure commands, but wraps the commands into a function which
7459 ;; tests if the cursor is currently at a headline or a plain list
7460 ;; item.  If that is the case, the structure command is used,
7461 ;; temporarily setting many Org-mode variables like regular
7462 ;; expressions for filling etc.  However, when any of those keys is
7463 ;; used at a different location, function uses `key-binding' to look
7464 ;; up if the key has an associated command in another currently active
7465 ;; keymap (minor modes, major mode, global), and executes that
7466 ;; command.  There might be problems if any of the keys is otherwise
7467 ;; used as a prefix key.
7469 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7470 ;; likewise the binding for RET can be return or \C-m.  Orgtbl-mode
7471 ;; addresses this by checking explicitly for both bindings.
7473 (defvar orgstruct-mode-map (make-sparse-keymap)
7474   "Keymap for the minor `orgstruct-mode'.")
7476 (defvar org-local-vars nil
7477   "List of local variables, for use by `orgstruct-mode'")
7479 ;;;###autoload
7480 (define-minor-mode orgstruct-mode
7481   "Toggle the minor more `orgstruct-mode'.
7482 This mode is for using Org-mode structure commands in other modes.
7483 The following key behave as if Org-mode was active, if the cursor
7484 is on a headline, or on a plain list item (both in the definition
7485 of Org-mode).
7487 M-up        Move entry/item up
7488 M-down      Move entry/item down
7489 M-left      Promote
7490 M-right     Demote
7491 M-S-up      Move entry/item up
7492 M-S-down    Move entry/item down
7493 M-S-left    Promote subtree
7494 M-S-right   Demote subtree
7495 M-q         Fill paragraph and items like in Org-mode
7496 C-c ^       Sort entries
7497 C-c -       Cycle list bullet
7498 TAB         Cycle item visibility
7499 M-RET       Insert new heading/item
7500 S-M-RET     Insert new TODO heading / Chekbox item
7501 C-c C-c     Set tags / toggle checkbox"
7502   nil " OrgStruct" nil
7503   (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7505 ;;;###autoload
7506 (defun turn-on-orgstruct ()
7507   "Unconditionally turn on `orgstruct-mode'."
7508   (orgstruct-mode 1))
7510 ;;;###autoload
7511 (defun turn-on-orgstruct++ ()
7512   "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7513 In addition to setting orgstruct-mode, this also exports all indentation and
7514 autofilling variables from org-mode into the buffer.  Note that turning
7515 off orgstruct-mode will *not* remove these additonal settings."
7516   (orgstruct-mode 1)
7517   (let (var val)
7518     (mapc
7519      (lambda (x)
7520        (when (string-match
7521               "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7522               (symbol-name (car x)))
7523          (setq var (car x) val (nth 1 x))
7524          (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7525      org-local-vars)))
7527 (defun orgstruct-error ()
7528   "Error when there is no default binding for a structure key."
7529   (interactive)
7530   (error "This key has no function outside structure elements"))
7532 (defun orgstruct-setup ()
7533   "Setup orgstruct keymaps."
7534   (let ((nfunc 0)
7535         (bindings
7536          (list
7537           '([(meta up)]           org-metaup)
7538           '([(meta down)]         org-metadown)
7539           '([(meta left)]         org-metaleft)
7540           '([(meta right)]        org-metaright)
7541           '([(meta shift up)]     org-shiftmetaup)
7542           '([(meta shift down)]   org-shiftmetadown)
7543           '([(meta shift left)]   org-shiftmetaleft)
7544           '([(meta shift right)]  org-shiftmetaright)
7545           '([(shift up)]          org-shiftup)
7546           '([(shift down)]        org-shiftdown)
7547           '("\C-c\C-c"            org-ctrl-c-ctrl-c)
7548           '("\M-q"                fill-paragraph)
7549           '("\C-c^"               org-sort)
7550           '("\C-c-"               org-cycle-list-bullet)))
7551         elt key fun cmd)
7552     (while (setq elt (pop bindings))
7553       (setq nfunc (1+ nfunc))
7554       (setq key (org-key (car elt))
7555             fun (nth 1 elt)
7556             cmd (orgstruct-make-binding fun nfunc key))
7557       (org-defkey orgstruct-mode-map key cmd))
7559     ;; Special treatment needed for TAB and RET
7560     (org-defkey orgstruct-mode-map [(tab)]
7561                 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7562     (org-defkey orgstruct-mode-map "\C-i"
7563                 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7565     (org-defkey orgstruct-mode-map "\M-\C-m"
7566                 (orgstruct-make-binding 'org-insert-heading 105
7567                                      "\M-\C-m" [(meta return)]))
7568     (org-defkey orgstruct-mode-map [(meta return)]
7569                 (orgstruct-make-binding 'org-insert-heading 106
7570                                      [(meta return)] "\M-\C-m"))
7572     (org-defkey orgstruct-mode-map [(shift meta return)]
7573                 (orgstruct-make-binding 'org-insert-todo-heading 107
7574                                      [(meta return)] "\M-\C-m"))
7576     (unless org-local-vars
7577       (setq org-local-vars (org-get-local-variables)))
7579     t))
7581 (defun orgstruct-make-binding (fun n &rest keys)
7582   "Create a function for binding in the structure minor mode.
7583 FUN is the command to call inside a table.  N is used to create a unique
7584 command name.  KEYS are keys that should be checked in for a command
7585 to execute outside of tables."
7586   (eval
7587    (list 'defun
7588          (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7589          '(arg)
7590          (concat "In Structure, run `" (symbol-name fun) "'.\n"
7591                  "Outside of structure, run the binding of `"
7592                  (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7593                  "'.")
7594          '(interactive "p")
7595          (list 'if
7596                '(org-context-p 'headline 'item)
7597                (list 'org-run-like-in-org-mode (list 'quote fun))
7598                (list 'let '(orgstruct-mode)
7599                      (list 'call-interactively
7600                            (append '(or)
7601                                    (mapcar (lambda (k)
7602                                              (list 'key-binding k))
7603                                            keys)
7604                                    '('orgstruct-error))))))))
7606 (defun org-context-p (&rest contexts)
7607   "Check if local context is and of CONTEXTS.
7608 Possible values in the list of contexts are `table', `headline', and `item'."
7609   (let ((pos (point)))
7610     (goto-char (point-at-bol))
7611     (prog1 (or (and (memq 'table contexts)
7612                     (looking-at "[ \t]*|"))
7613                (and (memq 'headline contexts)
7614                     (looking-at "\\*+"))
7615                (and (memq 'item contexts)
7616                     (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7617       (goto-char pos))))
7619 (defun org-get-local-variables ()
7620   "Return a list of all local variables in an org-mode buffer."
7621   (let (varlist)
7622     (with-current-buffer (get-buffer-create "*Org tmp*")
7623       (erase-buffer)
7624       (org-mode)
7625       (setq varlist (buffer-local-variables)))
7626     (kill-buffer "*Org tmp*")
7627     (delq nil
7628           (mapcar
7629            (lambda (x)
7630              (setq x
7631                    (if (symbolp x)
7632                        (list x)
7633                      (list (car x) (list 'quote (cdr x)))))
7634              (if (string-match
7635                   "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7636                   (symbol-name (car x)))
7637                  x nil))
7638            varlist))))
7640 ;;;###autoload
7641 (defun org-run-like-in-org-mode (cmd)
7642   (unless org-local-vars
7643     (setq org-local-vars (org-get-local-variables)))
7644   (eval (list 'let org-local-vars
7645               (list 'call-interactively (list 'quote cmd)))))
7647 ;;;; Archiving
7649 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7651 (defun org-archive-subtree (&optional find-done)
7652   "Move the current subtree to the archive.
7653 The archive can be a certain top-level heading in the current file, or in
7654 a different file.  The tree will be moved to that location, the subtree
7655 heading be marked DONE, and the current time will be added.
7657 When called with prefix argument FIND-DONE, find whole trees without any
7658 open TODO items and archive them (after getting confirmation from the user).
7659 If the cursor is not at a headline when this comand is called, try all level
7660 1 trees.  If the cursor is on a headline, only try the direct children of
7661 this heading."
7662   (interactive "P")
7663   (if find-done
7664       (org-archive-all-done)
7665     ;; Save all relevant TODO keyword-relatex variables
7667     (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7668           (tr-org-todo-keywords-1 org-todo-keywords-1)
7669           (tr-org-todo-kwd-alist org-todo-kwd-alist)
7670           (tr-org-done-keywords org-done-keywords)
7671           (tr-org-todo-regexp org-todo-regexp)
7672           (tr-org-todo-line-regexp org-todo-line-regexp)
7673           (tr-org-odd-levels-only org-odd-levels-only)
7674           (this-buffer (current-buffer))
7675           (org-archive-location org-archive-location)
7676           (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7677           ;; start of variables that will be used for saving context
7678           ;; The compiler complains about them - keep them anyway!
7679           (file (abbreviate-file-name (buffer-file-name)))
7680           (time (format-time-string
7681                  (substring (cdr org-time-stamp-formats) 1 -1)
7682                  (current-time)))
7683           afile heading buffer level newfile-p
7684           category todo priority
7685           ;; start of variables that will be used for savind context
7686           ltags itags prop)
7688       ;; Try to find a local archive location
7689       (save-excursion
7690         (save-restriction
7691           (widen)
7692           (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7693           (if (and prop (string-match "\\S-" prop))
7694               (setq org-archive-location prop)
7695             (if (or (re-search-backward re nil t)
7696                     (re-search-forward re nil t))
7697                 (setq org-archive-location (match-string 1))))))
7699       (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7700           (progn
7701             (setq afile (format (match-string 1 org-archive-location)
7702                                (file-name-nondirectory buffer-file-name))
7703                   heading (match-string 2 org-archive-location)))
7704         (error "Invalid `org-archive-location'"))
7705       (if (> (length afile) 0)
7706           (setq newfile-p (not (file-exists-p afile))
7707                 buffer (find-file-noselect afile))
7708         (setq buffer (current-buffer)))
7709       (unless buffer
7710         (error "Cannot access file \"%s\"" afile))
7711       (if (and (> (length heading) 0)
7712                (string-match "^\\*+" heading))
7713           (setq level (match-end 0))
7714         (setq heading nil level 0))
7715       (save-excursion
7716         (org-back-to-heading t)
7717         ;; Get context information that will be lost by moving the tree
7718         (org-refresh-category-properties)
7719         (setq category (org-get-category)
7720               todo (and (looking-at org-todo-line-regexp)
7721                         (match-string 2))
7722               priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7723               ltags (org-get-tags)
7724               itags (org-delete-all ltags (org-get-tags-at)))
7725         (setq ltags (mapconcat 'identity ltags " ")
7726               itags (mapconcat 'identity itags " "))
7727         ;; We first only copy, in case something goes wrong
7728         ;; we need to protect this-command, to avoid kill-region sets it,
7729         ;; which would lead to duplication of subtrees
7730         (let (this-command) (org-copy-subtree))
7731         (set-buffer buffer)
7732         ;; Enforce org-mode for the archive buffer
7733         (if (not (org-mode-p))
7734             ;; Force the mode for future visits.
7735             (let ((org-insert-mode-line-in-empty-file t)
7736                   (org-inhibit-startup t))
7737               (call-interactively 'org-mode)))
7738         (when newfile-p
7739           (goto-char (point-max))
7740           (insert (format "\nArchived entries from file %s\n\n"
7741                           (buffer-file-name this-buffer))))
7742         ;; Force the TODO keywords of the original buffer
7743         (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7744               (org-todo-keywords-1 tr-org-todo-keywords-1)
7745               (org-todo-kwd-alist tr-org-todo-kwd-alist)
7746               (org-done-keywords tr-org-done-keywords)
7747               (org-todo-regexp tr-org-todo-regexp)
7748               (org-todo-line-regexp tr-org-todo-line-regexp)
7749               (org-odd-levels-only
7750                (if (local-variable-p 'org-odd-levels-only (current-buffer))
7751                    org-odd-levels-only
7752                  tr-org-odd-levels-only)))
7753           (goto-char (point-min))
7754           (if heading
7755               (progn
7756                 (if (re-search-forward
7757                      (concat "^" (regexp-quote heading)
7758                              (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7759                      nil t)
7760                     (goto-char (match-end 0))
7761                   ;; Heading not found, just insert it at the end
7762                   (goto-char (point-max))
7763                   (or (bolp) (insert "\n"))
7764                   (insert "\n" heading "\n")
7765                   (end-of-line 0))
7766                 ;; Make the subtree visible
7767                 (show-subtree)
7768                 (org-end-of-subtree t)
7769                 (skip-chars-backward " \t\r\n")
7770                 (and (looking-at "[ \t\r\n]*")
7771                      (replace-match "\n\n")))
7772             ;; No specific heading, just go to end of file.
7773             (goto-char (point-max)) (insert "\n"))
7774           ;; Paste
7775           (org-paste-subtree (org-get-legal-level level 1))
7777           ;; Mark the entry as done
7778           (when (and org-archive-mark-done
7779                      (looking-at org-todo-line-regexp)
7780                      (or (not (match-end 2))
7781                          (not (member (match-string 2) org-done-keywords))))
7782             (let (org-log-done)
7783               (org-todo
7784                (car (or (member org-archive-mark-done org-done-keywords)
7785                         org-done-keywords)))))
7787           ;; Add the context info
7788           (when org-archive-save-context-info
7789             (let ((l org-archive-save-context-info) e n v)
7790               (while (setq e (pop l))
7791                 (when (and (setq v (symbol-value e))
7792                            (stringp v) (string-match "\\S-" v))
7793                   (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7794                   (org-entry-put (point) n v)))))
7796           ;; Save the buffer, if it is not the same buffer.
7797           (if (not (eq this-buffer buffer)) (save-buffer))))
7798       ;; Here we are back in the original buffer.  Everything seems to have
7799       ;; worked.  So now cut the tree and finish up.
7800       (let (this-command) (org-cut-subtree))
7801       (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7802       (message "Subtree archived %s"
7803                (if (eq this-buffer buffer)
7804                    (concat "under heading: " heading)
7805                  (concat "in file: " (abbreviate-file-name afile)))))))
7807 (defun org-refresh-category-properties ()
7808   "Refresh category text properties in teh buffer."
7809   (let ((def-cat (cond
7810                   ((null org-category)
7811                    (if buffer-file-name
7812                        (file-name-sans-extension
7813                         (file-name-nondirectory buffer-file-name))
7814                      "???"))
7815                   ((symbolp org-category) (symbol-name org-category))
7816                   (t org-category)))
7817         beg end cat pos optionp)
7818     (org-unmodified
7819      (save-excursion
7820        (save-restriction
7821          (widen)
7822          (goto-char (point-min))
7823          (put-text-property (point) (point-max) 'org-category def-cat)
7824          (while (re-search-forward
7825                  "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7826            (setq pos (match-end 0)
7827                  optionp (equal (char-after (match-beginning 0)) ?#)
7828                  cat (org-trim (match-string 2)))
7829            (if optionp
7830                (setq beg (point-at-bol) end (point-max))
7831              (org-back-to-heading t)
7832              (setq beg (point) end (org-end-of-subtree t t)))
7833            (put-text-property beg end 'org-category cat)
7834            (goto-char pos)))))))
7836 (defun org-archive-all-done (&optional tag)
7837   "Archive sublevels of the current tree without open TODO items.
7838 If the cursor is not on a headline, try all level 1 trees.  If
7839 it is on a headline, try all direct children.
7840 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7841   (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7842         (rea (concat ".*:" org-archive-tag ":"))
7843         (begm (make-marker))
7844         (endm (make-marker))
7845         (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7846                     "Move subtree to archive (no open TODO items)? "))
7847         beg end (cntarch 0))
7848     (if (org-on-heading-p)
7849         (progn
7850           (setq re1 (concat "^" (regexp-quote
7851                                  (make-string
7852                                   (1+ (- (match-end 0) (match-beginning 0)))
7853                                   ?*))
7854                             " "))
7855           (move-marker begm (point))
7856           (move-marker endm (org-end-of-subtree t)))
7857       (setq re1 "^* ")
7858       (move-marker begm (point-min))
7859       (move-marker endm (point-max)))
7860     (save-excursion
7861       (goto-char begm)
7862       (while (re-search-forward re1 endm t)
7863         (setq beg (match-beginning 0)
7864               end (save-excursion (org-end-of-subtree t) (point)))
7865         (goto-char beg)
7866         (if (re-search-forward re end t)
7867             (goto-char end)
7868           (goto-char beg)
7869           (if (and (or (not tag) (not (looking-at rea)))
7870                    (y-or-n-p question))
7871               (progn
7872                 (if tag
7873                     (org-toggle-tag org-archive-tag 'on)
7874                   (org-archive-subtree))
7875                 (setq cntarch (1+ cntarch)))
7876             (goto-char end)))))
7877     (message "%d trees archived" cntarch)))
7879 (defun org-cycle-hide-drawers (state)
7880   "Re-hide all drawers after a visibility state change."
7881   (when (and (org-mode-p)
7882              (not (memq state '(overview folded))))
7883     (save-excursion
7884       (let* ((globalp (memq state '(contents all)))
7885              (beg (if globalp (point-min) (point)))
7886              (end (if globalp (point-max) (org-end-of-subtree t))))
7887         (goto-char beg)
7888         (while (re-search-forward org-drawer-regexp end t)
7889           (org-flag-drawer t))))))
7891 (defun org-flag-drawer (flag)
7892   (save-excursion
7893     (beginning-of-line 1)
7894     (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7895       (let ((b (match-end 0)))
7896         (if (re-search-forward
7897              "^[ \t]*:END:"
7898              (save-excursion (outline-next-heading) (point)) t)
7899             (outline-flag-region b (point-at-eol) flag)
7900           (error ":END: line missing"))))))
7902 (defun org-cycle-hide-archived-subtrees (state)
7903   "Re-hide all archived subtrees after a visibility state change."
7904   (when (and (not org-cycle-open-archived-trees)
7905              (not (memq state '(overview folded))))
7906     (save-excursion
7907       (let* ((globalp (memq state '(contents all)))
7908              (beg (if globalp (point-min) (point)))
7909              (end (if globalp (point-max) (org-end-of-subtree t))))
7910         (org-hide-archived-subtrees beg end)
7911         (goto-char beg)
7912         (if (looking-at (concat ".*:" org-archive-tag ":"))
7913             (message "%s" (substitute-command-keys
7914                            "Subtree is archived and stays closed.  Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
7916 (defun org-force-cycle-archived ()
7917   "Cycle subtree even if it is archived."
7918   (interactive)
7919   (setq this-command 'org-cycle)
7920   (let ((org-cycle-open-archived-trees t))
7921     (call-interactively 'org-cycle)))
7923 (defun org-hide-archived-subtrees (beg end)
7924   "Re-hide all archived subtrees after a visibility state change."
7925   (save-excursion
7926     (let* ((re (concat ":" org-archive-tag ":")))
7927       (goto-char beg)
7928       (while (re-search-forward re end t)
7929         (and (org-on-heading-p) (hide-subtree))
7930         (org-end-of-subtree t)))))
7932 (defun org-toggle-tag (tag &optional onoff)
7933   "Toggle the tag TAG for the current line.
7934 If ONOFF is `on' or `off', don't toggle but set to this state."
7935   (unless (org-on-heading-p t) (error "Not on headling"))
7936   (let (res current)
7937     (save-excursion
7938       (beginning-of-line)
7939       (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
7940                              (point-at-eol) t)
7941           (progn
7942             (setq current (match-string 1))
7943             (replace-match ""))
7944         (setq current ""))
7945       (setq current (nreverse (org-split-string current ":")))
7946       (cond
7947        ((eq onoff 'on)
7948         (setq res t)
7949         (or (member tag current) (push tag current)))
7950        ((eq onoff 'off)
7951         (or (not (member tag current)) (setq current (delete tag current))))
7952        (t (if (member tag current)
7953               (setq current (delete tag current))
7954             (setq res t)
7955             (push tag current))))
7956       (end-of-line 1)
7957       (if current
7958           (progn
7959             (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
7960             (org-set-tags nil t))
7961         (delete-horizontal-space))
7962       (run-hooks 'org-after-tags-change-hook))
7963     res))
7965 (defun org-toggle-archive-tag (&optional arg)
7966   "Toggle the archive tag for the current headline.
7967 With prefix ARG, check all children of current headline and offer tagging
7968 the children that do not contain any open TODO items."
7969   (interactive "P")
7970   (if arg
7971       (org-archive-all-done 'tag)
7972     (let (set)
7973       (save-excursion
7974         (org-back-to-heading t)
7975         (setq set (org-toggle-tag org-archive-tag))
7976         (when set (hide-subtree)))
7977       (and set (beginning-of-line 1))
7978       (message "Subtree %s" (if set "archived" "unarchived")))))
7981 ;;;; Tables
7983 ;;; The table editor
7985 ;; Watch out:  Here we are talking about two different kind of tables.
7986 ;; Most of the code is for the tables created with the Org-mode table editor.
7987 ;; Sometimes, we talk about tables created and edited with the table.el
7988 ;; Emacs package.  We call the former org-type tables, and the latter
7989 ;; table.el-type tables.
7991 (defun org-before-change-function (beg end)
7992   "Every change indicates that a table might need an update."
7993   (setq org-table-may-need-update t))
7995 (defconst org-table-line-regexp "^[ \t]*|"
7996   "Detects an org-type table line.")
7997 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7998   "Detects an org-type table line.")
7999 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8000   "Detects a table line marked for automatic recalculation.")
8001 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8002   "Detects a table line marked for automatic recalculation.")
8003 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8004   "Detects a table line marked for automatic recalculation.")
8005 (defconst org-table-hline-regexp "^[ \t]*|-"
8006   "Detects an org-type table hline.")
8007 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8008   "Detects a table-type table hline.")
8009 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8010   "Detects an org-type or table-type table.")
8011 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8012   "Searching from within a table (any type) this finds the first line
8013 outside the table.")
8014 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8015   "Searching from within a table (any type) this finds the first line
8016 outside the table.")
8018 (defvar org-table-last-highlighted-reference nil)
8019 (defvar org-table-formula-history nil)
8021 (defvar org-table-column-names nil
8022   "Alist with column names, derived from the `!' line.")
8023 (defvar org-table-column-name-regexp nil
8024   "Regular expression matching the current column names.")
8025 (defvar org-table-local-parameters nil
8026   "Alist with parameter names, derived from the `$' line.")
8027 (defvar org-table-named-field-locations nil
8028   "Alist with locations of named fields.")
8030 (defvar org-table-current-line-types nil
8031   "Table row types, non-nil only for the duration of a comand.")
8032 (defvar org-table-current-begin-line nil
8033   "Table begin line, non-nil only for the duration of a comand.")
8034 (defvar org-table-current-begin-pos nil
8035   "Table begin position, non-nil only for the duration of a comand.")
8036 (defvar org-table-dlines nil
8037   "Vector of data line line numbers in the current table.")
8038 (defvar org-table-hlines nil
8039   "Vector of hline line numbers in the current table.")
8041 (defconst org-table-range-regexp
8042    "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8043    ;;   1                        2                    3          4                        5
8044   "Regular expression for matching ranges in formulas.")
8046 (defconst org-table-range-regexp2
8047   (concat
8048    "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8049    "\\.\\."
8050    "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8051   "Match a range for reference display.")
8053 (defconst org-table-translate-regexp
8054   (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8055   "Match a reference that needs translation, for reference display.")
8057 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8059 (defun org-table-create-with-table.el ()
8060   "Use the table.el package to insert a new table.
8061 If there is already a table at point, convert between Org-mode tables
8062 and table.el tables."
8063   (interactive)
8064   (require 'table)
8065   (cond
8066    ((org-at-table.el-p)
8067     (if (y-or-n-p "Convert table to Org-mode table? ")
8068         (org-table-convert)))
8069    ((org-at-table-p)
8070     (if (y-or-n-p "Convert table to table.el table? ")
8071         (org-table-convert)))
8072    (t (call-interactively 'table-insert))))
8074 (defun org-table-create-or-convert-from-region (arg)
8075   "Convert region to table, or create an empty table.
8076 If there is an active region, convert it to a table, using the function
8077 `org-table-convert-region'.  See the documentation of that function
8078 to learn how the prefix argument is interpreted to determine the field
8079 separator.
8080 If there is no such region, create an empty table with `org-table-create'."
8081   (interactive "P")
8082   (if (org-region-active-p)
8083       (org-table-convert-region (region-beginning) (region-end) arg)
8084     (org-table-create arg)))
8086 (defun org-table-create (&optional size)
8087   "Query for a size and insert a table skeleton.
8088 SIZE is a string Columns x Rows like for example \"3x2\"."
8089   (interactive "P")
8090   (unless size
8091     (setq size (read-string
8092                 (concat "Table size Columns x Rows [e.g. "
8093                         org-table-default-size "]: ")
8094                 "" nil org-table-default-size)))
8096   (let* ((pos (point))
8097          (indent (make-string (current-column) ?\ ))
8098          (split (org-split-string size " *x *"))
8099          (rows (string-to-number (nth 1 split)))
8100          (columns (string-to-number (car split)))
8101          (line (concat (apply 'concat indent "|" (make-list columns "  |"))
8102                        "\n")))
8103     (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8104                                   (point-at-bol) (point)))
8105         (beginning-of-line 1)
8106       (newline))
8107     ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8108     (dotimes (i rows) (insert line))
8109     (goto-char pos)
8110     (if (> rows 1)
8111         ;; Insert a hline after the first row.
8112         (progn
8113           (end-of-line 1)
8114           (insert "\n|-")
8115           (goto-char pos)))
8116     (org-table-align)))
8118 (defun org-table-convert-region (beg0 end0 &optional separator)
8119   "Convert region to a table.
8120 The region goes from BEG0 to END0, but these borders will be moved
8121 slightly, to make sure a beginning of line in the first line is included.
8123 SEPARATOR specifies the field separator in the lines.  It can have the
8124 following values:
8126 '(4)     Use the comma as a field separator
8127 '(16)    Use a TAB as field separator
8128 integer  When a number, use that many spaces as field separator
8129 nil      When nil, the command tries to be smart and figure out the
8130          separator in the following way:
8131          - when each line contains a TAB, assume TAB-separated material
8132          - when each line contains a comme, assume CSV material
8133          - else, assume one or more SPACE charcters as separator."
8134   (interactive "rP")
8135   (let* ((beg (min beg0 end0))
8136          (end (max beg0 end0))
8137          re)
8138     (goto-char beg)
8139     (beginning-of-line 1)
8140     (setq beg (move-marker (make-marker) (point)))
8141     (goto-char end)
8142     (if (bolp) (backward-char 1) (end-of-line 1))
8143     (setq end (move-marker (make-marker) (point)))
8144     ;; Get the right field separator
8145     (unless separator
8146       (goto-char beg)
8147       (setq separator
8148             (cond
8149              ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8150              ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8151              (t 1))))
8152     (setq re (cond
8153               ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8154               ((equal separator '(16)) "^\\|\t")
8155               ((integerp separator)
8156                (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8157               (t (error "This should not happen"))))
8158     (goto-char beg)
8159     (while (re-search-forward re end t)
8160       (replace-match "| " t t))
8161     (goto-char beg)
8162     (insert " ")
8163     (org-table-align)))
8165 (defun org-table-import (file arg)
8166   "Import FILE as a table.
8167 The file is assumed to be tab-separated.  Such files can be produced by most
8168 spreadsheet and database applications.  If no tabs (at least one per line)
8169 are found, lines will be split on whitespace into fields."
8170   (interactive "f\nP")
8171   (or (bolp) (newline))
8172   (let ((beg (point))
8173         (pm (point-max)))
8174     (insert-file-contents file)
8175     (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8177 (defun org-table-export ()
8178   "Export table as a tab-separated file.
8179 Such a file can be imported into a spreadsheet program like Excel."
8180   (interactive)
8181   (let* ((beg (org-table-begin))
8182          (end (org-table-end))
8183          (table (buffer-substring beg end))
8184          (file (read-file-name "Export table to: "))
8185          buf)
8186     (unless (or (not (file-exists-p file))
8187                 (y-or-n-p (format "Overwrite file %s? " file)))
8188       (error "Abort"))
8189     (with-current-buffer (find-file-noselect file)
8190       (setq buf (current-buffer))
8191       (erase-buffer)
8192       (fundamental-mode)
8193       (insert table)
8194       (goto-char (point-min))
8195       (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8196         (replace-match "" t t)
8197         (end-of-line 1))
8198       (goto-char (point-min))
8199       (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8200         (replace-match "" t t)
8201         (goto-char (min (1+ (point)) (point-max))))
8202       (goto-char (point-min))
8203       (while (re-search-forward "^-[-+]*$" nil t)
8204         (replace-match "")
8205         (if (looking-at "\n")
8206             (delete-char 1)))
8207       (goto-char (point-min))
8208       (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8209         (replace-match "\t" t t))
8210       (save-buffer))
8211     (kill-buffer buf)))
8213 (defvar org-table-aligned-begin-marker (make-marker)
8214   "Marker at the beginning of the table last aligned.
8215 Used to check if cursor still is in that table, to minimize realignment.")
8216 (defvar org-table-aligned-end-marker (make-marker)
8217   "Marker at the end of the table last aligned.
8218 Used to check if cursor still is in that table, to minimize realignment.")
8219 (defvar org-table-last-alignment nil
8220   "List of flags for flushright alignment, from the last re-alignment.
8221 This is being used to correctly align a single field after TAB or RET.")
8222 (defvar org-table-last-column-widths nil
8223   "List of max width of fields in each column.
8224 This is being used to correctly align a single field after TAB or RET.")
8225 (defvar org-table-overlay-coordinates nil
8226   "Overlay coordinates after each align of a table.")
8227 (make-variable-buffer-local 'org-table-overlay-coordinates)
8229 (defvar org-last-recalc-line nil)
8230 (defconst org-narrow-column-arrow "=>"
8231   "Used as display property in narrowed table columns.")
8233 (defun org-table-align ()
8234   "Align the table at point by aligning all vertical bars."
8235   (interactive)
8236   (let* (
8237          ;; Limits of table
8238          (beg (org-table-begin))
8239          (end (org-table-end))
8240          ;; Current cursor position
8241          (linepos (org-current-line))
8242          (colpos (org-table-current-column))
8243          (winstart (window-start))
8244          (winstartline (org-current-line (min winstart (1- (point-max)))))
8245          lines (new "") lengths l typenums ty fields maxfields i
8246          column
8247          (indent "") cnt frac
8248          rfmt hfmt
8249          (spaces '(1 . 1))
8250          (sp1 (car spaces))
8251          (sp2 (cdr spaces))
8252          (rfmt1 (concat
8253                  (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8254          (hfmt1 (concat
8255                  (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8256          emptystrings links dates emph narrow fmax f1 len c e)
8257     (untabify beg end)
8258     (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8259     ;; Check if we have links or dates
8260     (goto-char beg)
8261     (setq links (re-search-forward org-bracket-link-regexp end t))
8262     (goto-char beg)
8263     (setq emph (and org-hide-emphasis-markers
8264                     (re-search-forward org-emph-re end t)))
8265     (goto-char beg)
8266     (setq dates (and org-display-custom-times
8267                      (re-search-forward org-ts-regexp-both end t)))
8268     ;; Make sure the link properties are right
8269     (when links (goto-char beg) (while (org-activate-bracket-links end)))
8270     ;; Make sure the date properties are right
8271     (when dates (goto-char beg) (while (org-activate-dates end)))
8272     (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8274     ;; Check if we are narrowing any columns
8275     (goto-char beg)
8276     (setq narrow (and org-format-transports-properties-p
8277                       (re-search-forward "<[0-9]+>" end t)))
8278     ;; Get the rows
8279     (setq lines (org-split-string
8280                  (buffer-substring beg end) "\n"))
8281     ;; Store the indentation of the first line
8282     (if (string-match "^ *" (car lines))
8283         (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8284     ;; Mark the hlines by setting the corresponding element to nil
8285     ;; At the same time, we remove trailing space.
8286     (setq lines (mapcar (lambda (l)
8287                           (if (string-match "^ *|-" l)
8288                               nil
8289                             (if (string-match "[ \t]+$" l)
8290                                 (substring l 0 (match-beginning 0))
8291                               l)))
8292                         lines))
8293     ;; Get the data fields by splitting the lines.
8294     (setq fields (mapcar
8295                   (lambda (l)
8296                       (org-split-string l " *| *"))
8297                   (delq nil (copy-sequence lines))))
8298     ;; How many fields in the longest line?
8299     (condition-case nil
8300         (setq maxfields (apply 'max (mapcar 'length fields)))
8301       (error
8302        (kill-region beg end)
8303        (org-table-create org-table-default-size)
8304        (error "Empty table - created default table")))
8305     ;; A list of empty strings to fill any short rows on output
8306     (setq emptystrings (make-list maxfields ""))
8307     ;; Check for special formatting.
8308     (setq i -1)
8309     (while (< (setq i (1+ i)) maxfields)   ;; Loop over all columns
8310       (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8311       ;; Check if there is an explicit width specified
8312       (when narrow
8313         (setq c column fmax nil)
8314         (while c
8315           (setq e (pop c))
8316           (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8317               (setq fmax (string-to-number (match-string 1 e)) c nil)))
8318         ;; Find fields that are wider than fmax, and shorten them
8319         (when fmax
8320           (loop for xx in column do
8321                 (when (and (stringp xx)
8322                            (> (org-string-width xx) fmax))
8323                   (org-add-props xx nil
8324                     'help-echo
8325                     (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8326                   (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8327                   (unless (> f1 1)
8328                     (error "Cannot narrow field starting with wide link \"%s\""
8329                            (match-string 0 xx)))
8330                   (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8331                   (add-text-properties (- f1 2) f1
8332                                        (list 'display org-narrow-column-arrow)
8333                                        xx)))))
8334       ;; Get the maximum width for each column
8335       (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8336       ;; Get the fraction of numbers, to decide about alignment of the column
8337       (setq cnt 0 frac 0.0)
8338       (loop for x in column do
8339             (if (equal x "")
8340                 nil
8341               (setq frac ( / (+ (* frac cnt)
8342                                 (if (string-match org-table-number-regexp x) 1 0))
8343                              (setq cnt (1+ cnt))))))
8344       (push (>= frac org-table-number-fraction) typenums))
8345     (setq lengths (nreverse lengths) typenums (nreverse typenums))
8347     ;; Store the alignment of this table, for later editing of single fields
8348     (setq org-table-last-alignment typenums
8349           org-table-last-column-widths lengths)
8351     ;; With invisible characters, `format' does not get the field width right
8352     ;; So we need to make these fields wide by hand.
8353     (when (or links emph)
8354       (loop for i from 0 upto (1- maxfields) do
8355             (setq len (nth i lengths))
8356             (loop for j from 0 upto (1- (length fields)) do
8357                   (setq c (nthcdr i (car (nthcdr j fields))))
8358                   (if (and (stringp (car c))
8359                            (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8360 ;                          (string-match org-bracket-link-regexp (car c))
8361                            (< (org-string-width (car c)) len))
8362                       (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8364     ;; Compute the formats needed for output of the table
8365     (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8366     (while (setq l (pop lengths))
8367       (setq ty (if (pop typenums) "" "-")) ; number types flushright
8368       (setq rfmt (concat rfmt (format rfmt1 ty l))
8369             hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8370     (setq rfmt (concat rfmt "\n")
8371           hfmt (concat (substring hfmt 0 -1) "|\n"))
8373     (setq new (mapconcat
8374                (lambda (l)
8375                  (if l (apply 'format rfmt
8376                               (append (pop fields) emptystrings))
8377                    hfmt))
8378                lines ""))
8379     ;; Replace the old one
8380     (delete-region beg end)
8381     (move-marker end nil)
8382     (move-marker org-table-aligned-begin-marker (point))
8383     (insert new)
8384     (move-marker org-table-aligned-end-marker (point))
8385     (when (and orgtbl-mode (not (org-mode-p)))
8386       (goto-char org-table-aligned-begin-marker)
8387       (while (org-hide-wide-columns org-table-aligned-end-marker)))
8388     ;; Try to move to the old location
8389     (goto-line winstartline)
8390     (setq winstart (point-at-bol))
8391     (goto-line linepos)
8392     (set-window-start (selected-window) winstart 'noforce)
8393     (org-table-goto-column colpos)
8394     (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8395     (setq org-table-may-need-update nil)
8396     ))
8398 (defun org-string-width (s)
8399   "Compute width of string, ignoring invisible characters.
8400 This ignores character with invisibility property `org-link', and also
8401 characters with property `org-cwidth', because these will become invisible
8402 upon the next fontification round."
8403   (let (b l)
8404     (when (or (eq t buffer-invisibility-spec)
8405               (assq 'org-link buffer-invisibility-spec))
8406       (while (setq b (text-property-any 0 (length s)
8407                                         'invisible 'org-link s))
8408         (setq s (concat (substring s 0 b)
8409                         (substring s (or (next-single-property-change
8410                                           b 'invisible s) (length s)))))))
8411     (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8412       (setq s (concat (substring s 0 b)
8413                       (substring s (or (next-single-property-change
8414                                         b 'org-cwidth s) (length s))))))
8415     (setq l (string-width s) b -1)
8416     (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8417       (setq l (- l (get-text-property b 'org-dwidth-n s))))
8418     l))
8420 (defun org-table-begin (&optional table-type)
8421   "Find the beginning of the table and return its position.
8422 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8423   (save-excursion
8424     (if (not (re-search-backward
8425               (if table-type org-table-any-border-regexp
8426                 org-table-border-regexp)
8427               nil t))
8428         (progn (goto-char (point-min)) (point))
8429       (goto-char (match-beginning 0))
8430       (beginning-of-line 2)
8431       (point))))
8433 (defun org-table-end (&optional table-type)
8434   "Find the end of the table and return its position.
8435 With argument TABLE-TYPE, go to the end of a table.el-type table."
8436   (save-excursion
8437     (if (not (re-search-forward
8438               (if table-type org-table-any-border-regexp
8439                 org-table-border-regexp)
8440               nil t))
8441         (goto-char (point-max))
8442       (goto-char (match-beginning 0)))
8443     (point-marker)))
8445 (defun org-table-justify-field-maybe (&optional new)
8446   "Justify the current field, text to left, number to right.
8447 Optional argument NEW may specify text to replace the current field content."
8448   (cond
8449    ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8450    ((org-at-table-hline-p))
8451    ((and (not new)
8452          (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8453                          (current-buffer)))
8454              (< (point) org-table-aligned-begin-marker)
8455              (>= (point) org-table-aligned-end-marker)))
8456     ;; This is not the same table, force a full re-align
8457     (setq org-table-may-need-update t))
8458    (t ;; realign the current field, based on previous full realign
8459     (let* ((pos (point)) s
8460            (col (org-table-current-column))
8461            (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8462            l f n o e)
8463       (when (> col 0)
8464         (skip-chars-backward "^|\n")
8465         (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8466             (progn
8467               (setq s (match-string 1)
8468                     o (match-string 0)
8469                     l (max 1 (- (match-end 0) (match-beginning 0) 3))
8470                     e (not (= (match-beginning 2) (match-end 2))))
8471               (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8472                               l (if e "|" (setq org-table-may-need-update t) ""))
8473                     n (format f s))
8474               (if new
8475                   (if (<= (length new) l)      ;; FIXME: length -> str-width?
8476                       (setq n (format f new))
8477                     (setq n (concat new "|") org-table-may-need-update t)))
8478               (or (equal n o)
8479                   (let (org-table-may-need-update)
8480                     (replace-match n t t))))
8481           (setq org-table-may-need-update t))
8482         (goto-char pos))))))
8484 (defun org-table-next-field ()
8485   "Go to the next field in the current table, creating new lines as needed.
8486 Before doing so, re-align the table if necessary."
8487   (interactive)
8488   (org-table-maybe-eval-formula)
8489   (org-table-maybe-recalculate-line)
8490   (if (and org-table-automatic-realign
8491            org-table-may-need-update)
8492       (org-table-align))
8493   (let ((end (org-table-end)))
8494     (if (org-at-table-hline-p)
8495         (end-of-line 1))
8496     (condition-case nil
8497         (progn
8498           (re-search-forward "|" end)
8499           (if (looking-at "[ \t]*$")
8500               (re-search-forward "|" end))
8501           (if (and (looking-at "-")
8502                    org-table-tab-jumps-over-hlines
8503                    (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8504               (goto-char (match-beginning 1)))
8505           (if (looking-at "-")
8506               (progn
8507                 (beginning-of-line 0)
8508                 (org-table-insert-row 'below))
8509             (if (looking-at " ") (forward-char 1))))
8510       (error
8511        (org-table-insert-row 'below)))))
8513 (defun org-table-previous-field ()
8514   "Go to the previous field in the table.
8515 Before doing so, re-align the table if necessary."
8516   (interactive)
8517   (org-table-justify-field-maybe)
8518   (org-table-maybe-recalculate-line)
8519   (if (and org-table-automatic-realign
8520            org-table-may-need-update)
8521       (org-table-align))
8522   (if (org-at-table-hline-p)
8523       (end-of-line 1))
8524   (re-search-backward "|" (org-table-begin))
8525   (re-search-backward "|" (org-table-begin))
8526   (while (looking-at "|\\(-\\|[ \t]*$\\)")
8527     (re-search-backward "|" (org-table-begin)))
8528   (if (looking-at "| ?")
8529       (goto-char (match-end 0))))
8531 (defun org-table-next-row ()
8532   "Go to the next row (same column) in the current table.
8533 Before doing so, re-align the table if necessary."
8534   (interactive)
8535   (org-table-maybe-eval-formula)
8536   (org-table-maybe-recalculate-line)
8537   (if (or (looking-at "[ \t]*$")
8538           (save-excursion (skip-chars-backward " \t") (bolp)))
8539       (newline)
8540     (if (and org-table-automatic-realign
8541              org-table-may-need-update)
8542         (org-table-align))
8543     (let ((col (org-table-current-column)))
8544       (beginning-of-line 2)
8545       (if (or (not (org-at-table-p))
8546               (org-at-table-hline-p))
8547           (progn
8548             (beginning-of-line 0)
8549             (org-table-insert-row 'below)))
8550       (org-table-goto-column col)
8551       (skip-chars-backward "^|\n\r")
8552       (if (looking-at " ") (forward-char 1)))))
8554 (defun org-table-copy-down (n)
8555   "Copy a field down in the current column.
8556 If the field at the cursor is empty, copy into it the content of the nearest
8557 non-empty field above.  With argument N, use the Nth non-empty field.
8558 If the current field is not empty, it is copied down to the next row, and
8559 the cursor is moved with it.  Therefore, repeating this command causes the
8560 column to be filled row-by-row.
8561 If the variable `org-table-copy-increment' is non-nil and the field is an
8562 integer or a timestamp, it will be incremented while copying.  In the case of
8563 a timestamp, if the cursor is on the year, change the year.  If it is on the
8564 month or the day, change that.  Point will stay on the current date field
8565 in order to easily repeat the interval."
8566   (interactive "p")
8567   (let* ((colpos (org-table-current-column))
8568          (col (current-column))
8569          (field (org-table-get-field))
8570          (non-empty (string-match "[^ \t]" field))
8571          (beg (org-table-begin))
8572          txt)
8573     (org-table-check-inside-data-field)
8574     (if non-empty
8575         (progn
8576           (setq txt (org-trim field))
8577           (org-table-next-row)
8578           (org-table-blank-field))
8579       (save-excursion
8580         (setq txt
8581               (catch 'exit
8582                 (while (progn (beginning-of-line 1)
8583                               (re-search-backward org-table-dataline-regexp
8584                                                   beg t))
8585                   (org-table-goto-column colpos t)
8586                   (if (and (looking-at
8587                             "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8588                            (= (setq n (1- n)) 0))
8589                       (throw 'exit (match-string 1))))))))
8590     (if txt
8591         (progn
8592           (if (and org-table-copy-increment
8593                    (string-match "^[0-9]+$" txt))
8594               (setq txt (format "%d" (+ (string-to-number txt) 1))))
8595           (insert txt)
8596           (move-to-column col)
8597           (if (and org-table-copy-increment (org-at-timestamp-p t))
8598               (org-timestamp-up 1)
8599             (org-table-maybe-recalculate-line))
8600           (org-table-align)
8601           (move-to-column col))
8602       (error "No non-empty field found"))))
8604 (defun org-table-check-inside-data-field ()
8605   "Is point inside a table data field?
8606 I.e. not on a hline or before the first or after the last column?
8607 This actually throws an error, so it aborts the current command."
8608   (if (or (not (org-at-table-p))
8609           (= (org-table-current-column) 0)
8610           (org-at-table-hline-p)
8611           (looking-at "[ \t]*$"))
8612       (error "Not in table data field")))
8614 (defvar org-table-clip nil
8615   "Clipboard for table regions.")
8617 (defun org-table-blank-field ()
8618   "Blank the current table field or active region."
8619   (interactive)
8620   (org-table-check-inside-data-field)
8621   (if (and (interactive-p) (org-region-active-p))
8622       (let (org-table-clip)
8623         (org-table-cut-region (region-beginning) (region-end)))
8624     (skip-chars-backward "^|")
8625     (backward-char 1)
8626     (if (looking-at "|[^|\n]+")
8627         (let* ((pos (match-beginning 0))
8628                (match (match-string 0))
8629                (len (org-string-width match)))
8630           (replace-match (concat "|" (make-string (1- len) ?\ )))
8631           (goto-char (+ 2 pos))
8632           (substring match 1)))))
8634 (defun org-table-get-field (&optional n replace)
8635   "Return the value of the field in column N of current row.
8636 N defaults to current field.
8637 If REPLACE is a string, replace field with this value.  The return value
8638 is always the old value."
8639   (and n (org-table-goto-column n))
8640   (skip-chars-backward "^|\n")
8641   (backward-char 1)
8642   (if (looking-at "|[^|\r\n]*")
8643       (let* ((pos (match-beginning 0))
8644              (val (buffer-substring (1+ pos) (match-end 0))))
8645         (if replace
8646             (replace-match (concat "|" replace) t t))
8647         (goto-char (min (point-at-eol) (+ 2 pos)))
8648         val)
8649     (forward-char 1) ""))
8651 (defun org-table-field-info (arg)
8652   "Show info about the current field, and highlight any reference at point."
8653   (interactive "P")
8654   (org-table-get-specials)
8655   (save-excursion
8656     (let* ((pos (point))
8657            (col (org-table-current-column))
8658            (cname (car (rassoc (int-to-string col) org-table-column-names)))
8659            (name (car (rassoc (list (org-current-line) col)
8660                               org-table-named-field-locations)))
8661            (eql (org-table-get-stored-formulas))
8662            (dline (org-table-current-dline))
8663            (ref (format "@%d$%d" dline col))
8664            (ref1 (org-table-convert-refs-to-an ref))
8665            (fequation (or (assoc name eql) (assoc ref eql)))
8666            (cequation (assoc (int-to-string col) eql))
8667            (eqn (or fequation cequation)))
8668       (goto-char pos)
8669       (condition-case nil
8670           (org-table-show-reference 'local)
8671         (error nil))
8672       (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8673                dline col
8674                (if cname (concat " or $" cname) "")
8675                dline col ref1
8676                (if name (concat " or $" name) "")
8677                ;; FIXME: formula info not correct if special table line
8678                (if eqn
8679                    (concat ", formula: "
8680                            (org-table-formula-to-user
8681                             (concat
8682                              (if (string-match "^[$@]"(car eqn)) "" "$")
8683                              (car eqn) "=" (cdr eqn))))
8684                  "")))))
8686 (defun org-table-current-column ()
8687   "Find out which column we are in.
8688 When called interactively, column is also displayed in echo area."
8689   (interactive)
8690   (if (interactive-p) (org-table-check-inside-data-field))
8691   (save-excursion
8692     (let ((cnt 0) (pos (point)))
8693       (beginning-of-line 1)
8694       (while (search-forward "|" pos t)
8695         (setq cnt (1+ cnt)))
8696       (if (interactive-p) (message "This is table column %d" cnt))
8697       cnt)))
8699 (defun org-table-current-dline ()
8700   "Find out what table data line we are in.
8701 Only datalins count for this."
8702   (interactive)
8703   (if (interactive-p) (org-table-check-inside-data-field))
8704   (save-excursion
8705     (let ((cnt 0) (pos (point)))
8706       (goto-char (org-table-begin))
8707       (while (<= (point) pos)
8708         (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8709         (beginning-of-line 2))
8710       (if (interactive-p) (message "This is table line %d" cnt))
8711       cnt)))
8713 (defun org-table-goto-column (n &optional on-delim force)
8714   "Move the cursor to the Nth column in the current table line.
8715 With optional argument ON-DELIM, stop with point before the left delimiter
8716 of the field.
8717 If there are less than N fields, just go to after the last delimiter.
8718 However, when FORCE is non-nil, create new columns if necessary."
8719   (interactive "p")
8720   (let ((pos (point-at-eol)))
8721     (beginning-of-line 1)
8722     (when (> n 0)
8723       (while (and (> (setq n (1- n)) -1)
8724                   (or (search-forward "|" pos t)
8725                       (and force
8726                            (progn (end-of-line 1)
8727                                   (skip-chars-backward "^|")
8728                                   (insert " | "))))))
8729 ;                                  (backward-char 2) t)))))
8730       (when (and force (not (looking-at ".*|")))
8731         (save-excursion (end-of-line 1) (insert " | ")))
8732       (if on-delim
8733           (backward-char 1)
8734         (if (looking-at " ") (forward-char 1))))))
8736 (defun org-at-table-p (&optional table-type)
8737   "Return t if the cursor is inside an org-type table.
8738 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8739   (if org-enable-table-editor
8740       (save-excursion
8741         (beginning-of-line 1)
8742         (looking-at (if table-type org-table-any-line-regexp
8743                       org-table-line-regexp)))
8744     nil))
8746 (defun org-at-table.el-p ()
8747   "Return t if and only if we are at a table.el table."
8748   (and (org-at-table-p 'any)
8749        (save-excursion
8750          (goto-char (org-table-begin 'any))
8751          (looking-at org-table1-hline-regexp))))
8753 (defun org-table-recognize-table.el ()
8754   "If there is a table.el table nearby, recognize it and move into it."
8755   (if org-table-tab-recognizes-table.el
8756       (if (org-at-table.el-p)
8757           (progn
8758             (beginning-of-line 1)
8759             (if (looking-at org-table-dataline-regexp)
8760                 nil
8761               (if (looking-at org-table1-hline-regexp)
8762                   (progn
8763                     (beginning-of-line 2)
8764                     (if (looking-at org-table-any-border-regexp)
8765                         (beginning-of-line -1)))))
8766             (if (re-search-forward "|" (org-table-end t) t)
8767                 (progn
8768                   (require 'table)
8769                   (if (table--at-cell-p (point))
8770                       t
8771                     (message "recognizing table.el table...")
8772                     (table-recognize-table)
8773                     (message "recognizing table.el table...done")))
8774               (error "This should not happen..."))
8775             t)
8776         nil)
8777     nil))
8779 (defun org-at-table-hline-p ()
8780   "Return t if the cursor is inside a hline in a table."
8781   (if org-enable-table-editor
8782       (save-excursion
8783         (beginning-of-line 1)
8784         (looking-at org-table-hline-regexp))
8785     nil))
8787 (defun org-table-insert-column ()
8788   "Insert a new column into the table."
8789   (interactive)
8790   (if (not (org-at-table-p))
8791       (error "Not at a table"))
8792   (org-table-find-dataline)
8793   (let* ((col (max 1 (org-table-current-column)))
8794          (beg (org-table-begin))
8795          (end (org-table-end))
8796          ;; Current cursor position
8797          (linepos (org-current-line))
8798          (colpos col))
8799     (goto-char beg)
8800     (while (< (point) end)
8801       (if (org-at-table-hline-p)
8802           nil
8803         (org-table-goto-column col t)
8804         (insert "|   "))
8805       (beginning-of-line 2))
8806     (move-marker end nil)
8807     (goto-line linepos)
8808     (org-table-goto-column colpos)
8809     (org-table-align)
8810     (org-table-fix-formulas "$" nil (1- col) 1)))
8812 (defun org-table-find-dataline ()
8813   "Find a dataline in the current table, which is needed for column commands."
8814   (if (and (org-at-table-p)
8815            (not (org-at-table-hline-p)))
8816       t
8817     (let ((col (current-column))
8818           (end (org-table-end)))
8819       (move-to-column col)
8820       (while (and (< (point) end)
8821                   (or (not (= (current-column) col))
8822                       (org-at-table-hline-p)))
8823         (beginning-of-line 2)
8824         (move-to-column col))
8825       (if (and (org-at-table-p)
8826                (not (org-at-table-hline-p)))
8827           t
8828         (error
8829          "Please position cursor in a data line for column operations")))))
8831 (defun org-table-delete-column ()
8832   "Delete a column from the table."
8833   (interactive)
8834   (if (not (org-at-table-p))
8835       (error "Not at a table"))
8836   (org-table-find-dataline)
8837   (org-table-check-inside-data-field)
8838   (let* ((col (org-table-current-column))
8839          (beg (org-table-begin))
8840          (end (org-table-end))
8841          ;; Current cursor position
8842          (linepos (org-current-line))
8843          (colpos col))
8844     (goto-char beg)
8845     (while (< (point) end)
8846       (if (org-at-table-hline-p)
8847           nil
8848         (org-table-goto-column col t)
8849         (and (looking-at "|[^|\n]+|")
8850              (replace-match "|")))
8851       (beginning-of-line 2))
8852     (move-marker end nil)
8853     (goto-line linepos)
8854     (org-table-goto-column colpos)
8855     (org-table-align)
8856     (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
8857                             col -1 col)))
8859 (defun org-table-move-column-right ()
8860   "Move column to the right."
8861   (interactive)
8862   (org-table-move-column nil))
8863 (defun org-table-move-column-left ()
8864   "Move column to the left."
8865   (interactive)
8866   (org-table-move-column 'left))
8868 (defun org-table-move-column (&optional left)
8869   "Move the current column to the right.  With arg LEFT, move to the left."
8870   (interactive "P")
8871   (if (not (org-at-table-p))
8872       (error "Not at a table"))
8873   (org-table-find-dataline)
8874   (org-table-check-inside-data-field)
8875   (let* ((col (org-table-current-column))
8876          (col1 (if left (1- col) col))
8877          (beg (org-table-begin))
8878          (end (org-table-end))
8879          ;; Current cursor position
8880          (linepos (org-current-line))
8881          (colpos (if left (1- col) (1+ col))))
8882     (if (and left (= col 1))
8883         (error "Cannot move column further left"))
8884     (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8885         (error "Cannot move column further right"))
8886     (goto-char beg)
8887     (while (< (point) end)
8888       (if (org-at-table-hline-p)
8889           nil
8890         (org-table-goto-column col1 t)
8891         (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8892              (replace-match "|\\2|\\1|")))
8893       (beginning-of-line 2))
8894     (move-marker end nil)
8895     (goto-line linepos)
8896     (org-table-goto-column colpos)
8897     (org-table-align)
8898     (org-table-fix-formulas
8899      "$" (list (cons (number-to-string col) (number-to-string colpos))
8900                (cons (number-to-string colpos) (number-to-string col))))))
8902 (defun org-table-move-row-down ()
8903   "Move table row down."
8904   (interactive)
8905   (org-table-move-row nil))
8906 (defun org-table-move-row-up ()
8907   "Move table row up."
8908   (interactive)
8909   (org-table-move-row 'up))
8911 (defun org-table-move-row (&optional up)
8912   "Move the current table line down.  With arg UP, move it up."
8913   (interactive "P")
8914   (let* ((col (current-column))
8915          (pos (point))
8916          (hline1p (save-excursion (beginning-of-line 1)
8917                                   (looking-at org-table-hline-regexp)))
8918          (dline1 (org-table-current-dline))
8919          (dline2 (+ dline1 (if up -1 1)))
8920          (tonew (if up 0 2))
8921          txt hline2p)
8922     (beginning-of-line tonew)
8923     (unless (org-at-table-p)
8924       (goto-char pos)
8925       (error "Cannot move row further"))
8926     (setq hline2p (looking-at org-table-hline-regexp))
8927     (goto-char pos)
8928     (beginning-of-line 1)
8929     (setq pos (point))
8930     (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8931     (delete-region (point) (1+ (point-at-eol)))
8932     (beginning-of-line tonew)
8933     (insert txt)
8934     (beginning-of-line 0)
8935     (move-to-column col)
8936     (unless (or hline1p hline2p)
8937       (org-table-fix-formulas
8938        "@" (list (cons (number-to-string dline1) (number-to-string dline2))
8939                  (cons (number-to-string dline2) (number-to-string dline1)))))))
8941 (defun org-table-insert-row (&optional arg)
8942   "Insert a new row above the current line into the table.
8943 With prefix ARG, insert below the current line."
8944   (interactive "P")
8945   (if (not (org-at-table-p))
8946       (error "Not at a table"))
8947   (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
8948          (new (org-table-clean-line line)))
8949     ;; Fix the first field if necessary
8950     (if (string-match "^[ \t]*| *[#$] *|" line)
8951         (setq new (replace-match (match-string 0 line) t t new)))
8952     (beginning-of-line (if arg 2 1))
8953     (let (org-table-may-need-update) (insert-before-markers new "\n"))
8954     (beginning-of-line 0)
8955     (re-search-forward "| ?" (point-at-eol) t)
8956     (and (or org-table-may-need-update org-table-overlay-coordinates)
8957          (org-table-align))
8958     (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
8960 (defun org-table-insert-hline (&optional above)
8961   "Insert a horizontal-line below the current line into the table.
8962 With prefix ABOVE, insert above the current line."
8963   (interactive "P")
8964   (if (not (org-at-table-p))
8965       (error "Not at a table"))
8966   (let ((line (org-table-clean-line
8967                (buffer-substring (point-at-bol) (point-at-eol))))
8968         (col (current-column)))
8969     (while (string-match "|\\( +\\)|" line)
8970       (setq line (replace-match
8971                   (concat "+" (make-string (- (match-end 1) (match-beginning 1))
8972                                            ?-) "|") t t line)))
8973     (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
8974     (beginning-of-line (if above 1 2))
8975     (insert line "\n")
8976     (beginning-of-line (if above 1 -1))
8977     (move-to-column col)
8978     (and org-table-overlay-coordinates (org-table-align))))
8980 (defun org-table-hline-and-move (&optional same-column)
8981   "Insert a hline and move to the row below that line."
8982   (interactive "P")
8983   (let ((col (org-table-current-column)))
8984     (org-table-maybe-eval-formula)
8985     (org-table-maybe-recalculate-line)
8986     (org-table-insert-hline)
8987     (end-of-line 2)
8988     (if (looking-at "\n[ \t]*|-")
8989         (progn (insert "\n|") (org-table-align))
8990       (org-table-next-field))
8991     (if same-column (org-table-goto-column col))))
8993 (defun org-table-clean-line (s)
8994   "Convert a table line S into a string with only \"|\" and space.
8995 In particular, this does handle wide and invisible characters."
8996   (if (string-match "^[ \t]*|-" s)
8997       ;; It's a hline, just map the characters
8998       (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
8999     (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9000       (setq s (replace-match
9001                (concat "|" (make-string (org-string-width (match-string 1 s))
9002                                         ?\ ) "|")
9003                t t s)))
9004     s))
9006 (defun org-table-kill-row ()
9007   "Delete the current row or horizontal line from the table."
9008   (interactive)
9009   (if (not (org-at-table-p))
9010       (error "Not at a table"))
9011   (let ((col (current-column))
9012         (dline (org-table-current-dline)))
9013     (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9014     (if (not (org-at-table-p)) (beginning-of-line 0))
9015     (move-to-column col)
9016     (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9017                             dline -1 dline)))
9019 (defun org-table-sort-lines (with-case &optional sorting-type)
9020   "Sort table lines according to the column at point.
9022 The position of point indicates the column to be used for
9023 sorting, and the range of lines is the range between the nearest
9024 horizontal separator lines, or the entire table of no such lines
9025 exist.  If point is before the first column, you will be prompted
9026 for the sorting column.  If there is an active region, the mark
9027 specifies the first line and the sorting column, while point
9028 should be in the last line to be included into the sorting.
9030 The command then prompts for the sorting type which can be
9031 alphabetically, numerically, or by time (as given in a time stamp
9032 in the field).  Sorting in reverse order is also possible.
9034 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9036 If SORTING-TYPE is specified when this function is called from a Lisp
9037 program, no prompting will take place.  SORTING-TYPE must be a character,
9038 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9039 should be done in reverse order."
9040   (interactive "P")
9041   (let* ((thisline (org-current-line))
9042          (thiscol (org-table-current-column))
9043          beg end bcol ecol tend tbeg column lns pos)
9044     (when (equal thiscol 0)
9045       (if (interactive-p)
9046           (setq thiscol
9047                 (string-to-number
9048                  (read-string "Use column N for sorting: ")))
9049         (setq thiscol 1))
9050       (org-table-goto-column thiscol))
9051     (org-table-check-inside-data-field)
9052     (if (org-region-active-p)
9053         (progn
9054           (setq beg (region-beginning) end (region-end))
9055           (goto-char beg)
9056           (setq column (org-table-current-column)
9057                 beg (point-at-bol))
9058           (goto-char end)
9059           (setq end (point-at-bol 2)))
9060       (setq column (org-table-current-column)
9061             pos (point)
9062             tbeg (org-table-begin)
9063             tend (org-table-end))
9064       (if (re-search-backward org-table-hline-regexp tbeg t)
9065           (setq beg (point-at-bol 2))
9066         (goto-char tbeg)
9067         (setq beg (point-at-bol 1)))
9068       (goto-char pos)
9069       (if (re-search-forward org-table-hline-regexp tend t)
9070           (setq end (point-at-bol 1))
9071         (goto-char tend)
9072         (setq end (point-at-bol))))
9073     (setq beg (move-marker (make-marker) beg)
9074           end (move-marker (make-marker) end))
9075     (untabify beg end)
9076     (goto-char beg)
9077     (org-table-goto-column column)
9078     (skip-chars-backward "^|")
9079     (setq bcol (current-column))
9080     (org-table-goto-column (1+ column))
9081     (skip-chars-backward "^|")
9082     (setq ecol (1- (current-column)))
9083     (org-table-goto-column column)
9084     (setq lns (mapcar (lambda(x) (cons
9085                                   (org-sort-remove-invisible
9086                                    (nth (1- column)
9087                                         (org-split-string x "[ \t]*|[ \t]*")))
9088                                   x))
9089                       (org-split-string (buffer-substring beg end) "\n")))
9090     (setq lns (org-do-sort lns "Table" with-case sorting-type))
9091     (delete-region beg end)
9092     (move-marker beg nil)
9093     (move-marker end nil)
9094     (insert (mapconcat 'cdr lns "\n") "\n")
9095     (goto-line thisline)
9096     (org-table-goto-column thiscol)
9097     (message "%d lines sorted, based on column %d" (length lns) column)))
9099 ;; FIXME: maybe we will not need this?  Table sorting is broken....
9100 (defun org-sort-remove-invisible (s)
9101   (remove-text-properties 0 (length s) org-rm-props s)
9102   (while (string-match org-bracket-link-regexp s)
9103     (setq s (replace-match (if (match-end 2)
9104                                (match-string 3 s)
9105                              (match-string 1 s)) t t s)))
9106   s)
9108 (defun org-table-cut-region (beg end)
9109   "Copy region in table to the clipboard and blank all relevant fields."
9110   (interactive "r")
9111   (org-table-copy-region beg end 'cut))
9113 (defun org-table-copy-region (beg end &optional cut)
9114   "Copy rectangular region in table to clipboard.
9115 A special clipboard is used which can only be accessed
9116 with `org-table-paste-rectangle'."
9117   (interactive "rP")
9118   (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9119          region cols
9120          (rpl (if cut "  " nil)))
9121     (goto-char beg)
9122     (org-table-check-inside-data-field)
9123     (setq l01 (org-current-line)
9124           c01 (org-table-current-column))
9125     (goto-char end)
9126     (org-table-check-inside-data-field)
9127     (setq l02 (org-current-line)
9128           c02 (org-table-current-column))
9129     (setq l1 (min l01 l02) l2 (max l01 l02)
9130           c1 (min c01 c02) c2 (max c01 c02))
9131     (catch 'exit
9132       (while t
9133         (catch 'nextline
9134           (if (> l1 l2) (throw 'exit t))
9135           (goto-line l1)
9136           (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9137           (setq cols nil ic1 c1 ic2 c2)
9138           (while (< ic1 (1+ ic2))
9139             (push (org-table-get-field ic1 rpl) cols)
9140             (setq ic1 (1+ ic1)))
9141           (push (nreverse cols) region)
9142           (setq l1 (1+ l1)))))
9143     (setq org-table-clip (nreverse region))
9144     (if cut (org-table-align))
9145     org-table-clip))
9147 (defun org-table-paste-rectangle ()
9148   "Paste a rectangular region into a table.
9149 The upper right corner ends up in the current field.  All involved fields
9150 will be overwritten.  If the rectangle does not fit into the present table,
9151 the table is enlarged as needed.  The process ignores horizontal separator
9152 lines."
9153   (interactive)
9154   (unless (and org-table-clip (listp org-table-clip))
9155     (error "First cut/copy a region to paste!"))
9156   (org-table-check-inside-data-field)
9157   (let* ((clip org-table-clip)
9158          (line (org-current-line))
9159          (col (org-table-current-column))
9160          (org-enable-table-editor t)
9161          (org-table-automatic-realign nil)
9162          c cols field)
9163     (while (setq cols (pop clip))
9164       (while (org-at-table-hline-p) (beginning-of-line 2))
9165       (if (not (org-at-table-p))
9166           (progn (end-of-line 0) (org-table-next-field)))
9167       (setq c col)
9168       (while (setq field (pop cols))
9169         (org-table-goto-column c nil 'force)
9170         (org-table-get-field nil field)
9171         (setq c (1+ c)))
9172       (beginning-of-line 2))
9173     (goto-line line)
9174     (org-table-goto-column col)
9175     (org-table-align)))
9177 (defun org-table-convert ()
9178   "Convert from `org-mode' table to table.el and back.
9179 Obviously, this only works within limits.  When an Org-mode table is
9180 converted to table.el, all horizontal separator lines get lost, because
9181 table.el uses these as cell boundaries and has no notion of horizontal lines.
9182 A table.el table can be converted to an Org-mode table only if it does not
9183 do row or column spanning.  Multiline cells will become multiple cells.
9184 Beware, Org-mode does not test if the table can be successfully converted - it
9185 blindly applies a recipe that works for simple tables."
9186   (interactive)
9187   (require 'table)
9188   (if (org-at-table.el-p)
9189       ;; convert to Org-mode table
9190       (let ((beg (move-marker (make-marker) (org-table-begin t)))
9191             (end (move-marker (make-marker) (org-table-end t))))
9192         (table-unrecognize-region beg end)
9193         (goto-char beg)
9194         (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9195           (replace-match ""))
9196         (goto-char beg))
9197     (if (org-at-table-p)
9198         ;; convert to table.el table
9199         (let ((beg (move-marker (make-marker) (org-table-begin)))
9200               (end (move-marker (make-marker) (org-table-end))))
9201           ;; first, get rid of all horizontal lines
9202           (goto-char beg)
9203           (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9204             (replace-match ""))
9205           ;; insert a hline before first
9206           (goto-char beg)
9207           (org-table-insert-hline 'above)
9208           (beginning-of-line -1)
9209           ;; insert a hline after each line
9210           (while (progn (beginning-of-line 3) (< (point) end))
9211             (org-table-insert-hline))
9212           (goto-char beg)
9213           (setq end (move-marker end (org-table-end)))
9214           ;; replace "+" at beginning and ending of hlines
9215           (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9216             (replace-match "\\1+-"))
9217           (goto-char beg)
9218           (while (re-search-forward "-|[ \t]*$" end t)
9219             (replace-match "-+"))
9220           (goto-char beg)))))
9222 (defun org-table-wrap-region (arg)
9223   "Wrap several fields in a column like a paragraph.
9224 This is useful if you'd like to spread the contents of a field over several
9225 lines, in order to keep the table compact.
9227 If there is an active region, and both point and mark are in the same column,
9228 the text in the column is wrapped to minimum width for the given number of
9229 lines.  Generally, this makes the table more compact.  A prefix ARG may be
9230 used to change the number of desired lines.  For example, `C-2 \\[org-table-wrap]'
9231 formats the selected text to two lines.  If the region was longer than two
9232 lines, the remaining lines remain empty.  A negative prefix argument reduces
9233 the current number of lines by that amount.  The wrapped text is pasted back
9234 into the table.  If you formatted it to more lines than it was before, fields
9235 further down in the table get overwritten - so you might need to make space in
9236 the table first.
9238 If there is no region, the current field is split at the cursor position and
9239 the text fragment to the right of the cursor is prepended to the field one
9240 line down.
9242 If there is no region, but you specify a prefix ARG, the current field gets
9243 blank, and the content is appended to the field above."
9244   (interactive "P")
9245   (org-table-check-inside-data-field)
9246   (if (org-region-active-p)
9247       ;; There is a region:  fill as a paragraph
9248       (let* ((beg (region-beginning))
9249              (cline (save-excursion (goto-char beg) (org-current-line)))
9250              (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9251              nlines)
9252         (org-table-cut-region (region-beginning) (region-end))
9253         (if (> (length (car org-table-clip)) 1)
9254             (error "Region must be limited to single column"))
9255         (setq nlines (if arg
9256                          (if (< arg 1)
9257                              (+ (length org-table-clip) arg)
9258                            arg)
9259                        (length org-table-clip)))
9260         (setq org-table-clip
9261               (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9262                                       nil nlines)))
9263         (goto-line cline)
9264         (org-table-goto-column ccol)
9265         (org-table-paste-rectangle))
9266     ;; No region, split the current field at point
9267     (if arg
9268         ;; combine with field above
9269         (let ((s (org-table-blank-field))
9270               (col (org-table-current-column)))
9271           (beginning-of-line 0)
9272           (while (org-at-table-hline-p) (beginning-of-line 0))
9273           (org-table-goto-column col)
9274           (skip-chars-forward "^|")
9275           (skip-chars-backward " ")
9276           (insert " " (org-trim s))
9277           (org-table-align))
9278       ;;  split field
9279       (when (looking-at "\\([^|]+\\)+|")
9280         (let ((s (match-string 1)))
9281           (replace-match " |")
9282           (goto-char (match-beginning 0))
9283           (org-table-next-row)
9284           (insert (org-trim s) " ")
9285           (org-table-align))))))
9287 (defvar org-field-marker nil)
9289 (defun org-table-edit-field (arg)
9290   "Edit table field in a different window.
9291 This is mainly useful for fields that contain hidden parts.
9292 When called with a \\[universal-argument] prefix, just make the full field visible so that
9293 it can be edited in place."
9294   (interactive "P")
9295   (if arg
9296       (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9297             (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9298         (remove-text-properties b e '(org-cwidth t invisible t
9299                                                  display t intangible t))
9300         (if (and (boundp 'font-lock-mode) font-lock-mode)
9301             (font-lock-fontify-block)))
9302     (let ((pos (move-marker (make-marker) (point)))
9303           (field (org-table-get-field))
9304           (cw (current-window-configuration))
9305           p)
9306       (org-switch-to-buffer-other-window "*Org tmp*")
9307       (erase-buffer)
9308       (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9309       (let ((org-inhibit-startup t)) (org-mode))
9310       (goto-char (setq p (point-max)))
9311       (insert (org-trim field))
9312       (remove-text-properties p (point-max)
9313                               '(invisible t org-cwidth t display t
9314                                           intangible t))
9315       (goto-char p)
9316       (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9317       (org-set-local 'org-window-configuration cw)
9318       (org-set-local 'org-field-marker pos)
9319       (message "Edit and finish with C-c C-c"))))
9321 (defun org-table-finish-edit-field ()
9322   "Finish editing a table data field.
9323 Remove all newline characters, insert the result into the table, realign
9324 the table and kill the editing buffer."
9325   (let ((pos org-field-marker)
9326         (cw org-window-configuration)
9327         (cb (current-buffer))
9328         text)
9329     (goto-char (point-min))
9330     (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9331     (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9332       (replace-match " "))
9333     (setq text (org-trim (buffer-string)))
9334     (set-window-configuration cw)
9335     (kill-buffer cb)
9336     (select-window (get-buffer-window (marker-buffer pos)))
9337     (goto-char pos)
9338     (move-marker pos nil)
9339     (org-table-check-inside-data-field)
9340     (org-table-get-field nil text)
9341     (org-table-align)
9342     (message "New field value inserted")))
9344 (defun org-trim (s)
9345   "Remove whitespace at beginning and end of string."
9346   (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9347   (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9348   s)
9350 (defun org-wrap (string &optional width lines)
9351   "Wrap string to either a number of lines, or a width in characters.
9352 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9353 that costs.  If there is a word longer than WIDTH, the text is actually
9354 wrapped to the length of that word.
9355 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9356 many lines, whatever width that takes.
9357 The return value is a list of lines, without newlines at the end."
9358   (let* ((words (org-split-string string "[ \t\n]+"))
9359          (maxword (apply 'max (mapcar 'org-string-width words)))
9360          w ll)
9361     (cond (width
9362            (org-do-wrap words (max maxword width)))
9363           (lines
9364            (setq w maxword)
9365            (setq ll (org-do-wrap words maxword))
9366            (if (<= (length ll) lines)
9367                ll
9368              (setq ll words)
9369              (while (> (length ll) lines)
9370                (setq w (1+ w))
9371                (setq ll (org-do-wrap words w)))
9372              ll))
9373           (t (error "Cannot wrap this")))))
9376 (defun org-do-wrap (words width)
9377   "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9378   (let (lines line)
9379     (while words
9380       (setq line (pop words))
9381       (while (and words (< (+ (length line) (length (car words))) width))
9382         (setq line (concat line " " (pop words))))
9383       (setq lines (push line lines)))
9384     (nreverse lines)))
9386 (defun org-split-string (string &optional separators)
9387   "Splits STRING into substrings at SEPARATORS.
9388 No empty strings are returned if there are matches at the beginning
9389 and end of string."
9390   (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9391         (start 0)
9392         notfirst
9393         (list nil))
9394     (while (and (string-match rexp string
9395                               (if (and notfirst
9396                                        (= start (match-beginning 0))
9397                                        (< start (length string)))
9398                                   (1+ start) start))
9399                 (< (match-beginning 0) (length string)))
9400       (setq notfirst t)
9401       (or (eq (match-beginning 0) 0)
9402           (and (eq (match-beginning 0) (match-end 0))
9403                (eq (match-beginning 0) start))
9404           (setq list
9405                 (cons (substring string start (match-beginning 0))
9406                       list)))
9407       (setq start (match-end 0)))
9408     (or (eq start (length string))
9409         (setq list
9410               (cons (substring string start)
9411                     list)))
9412     (nreverse list)))
9414 (defun org-table-map-tables (function)
9415   "Apply FUNCTION to the start of all tables in the buffer."
9416   (save-excursion
9417     (save-restriction
9418       (widen)
9419       (goto-char (point-min))
9420       (while (re-search-forward org-table-any-line-regexp nil t)
9421         (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9422         (beginning-of-line 1)
9423         (if (looking-at org-table-line-regexp)
9424             (save-excursion (funcall function)))
9425         (re-search-forward org-table-any-border-regexp nil 1))))
9426   (message "Mapping tables: done"))
9428 (defvar org-timecnt) ; dynamically scoped parameter
9430 (defun org-table-sum (&optional beg end nlast)
9431   "Sum numbers in region of current table column.
9432 The result will be displayed in the echo area, and will be available
9433 as kill to be inserted with \\[yank].
9435 If there is an active region, it is interpreted as a rectangle and all
9436 numbers in that rectangle will be summed.  If there is no active
9437 region and point is located in a table column, sum all numbers in that
9438 column.
9440 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9441 numbers are assumed to be times as well (in decimal hours) and the
9442 numbers are added as such.
9444 If NLAST is a number, only the NLAST fields will actually be summed."
9445   (interactive)
9446   (save-excursion
9447     (let (col (org-timecnt 0) diff h m s org-table-clip)
9448       (cond
9449        ((and beg end))   ; beg and end given explicitly
9450        ((org-region-active-p)
9451         (setq beg (region-beginning) end (region-end)))
9452        (t
9453         (setq col (org-table-current-column))
9454         (goto-char (org-table-begin))
9455         (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9456           (error "No table data"))
9457         (org-table-goto-column col)
9458         (setq beg (point))
9459         (goto-char (org-table-end))
9460         (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9461           (error "No table data"))
9462         (org-table-goto-column col)
9463         (setq end (point))))
9464       (let* ((items (apply 'append (org-table-copy-region beg end)))
9465              (items1 (cond ((not nlast) items)
9466                            ((>= nlast (length items)) items)
9467                            (t (setq items (reverse items))
9468                               (setcdr (nthcdr (1- nlast) items) nil)
9469                               (nreverse items))))
9470              (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9471                                         items1)))
9472              (res (apply '+ numbers))
9473              (sres (if (= org-timecnt 0)
9474                        (format "%g" res)
9475                      (setq diff (* 3600 res)
9476                            h (floor (/ diff 3600)) diff (mod diff 3600)
9477                            m (floor (/ diff 60)) diff (mod diff 60)
9478                            s diff)
9479                      (format "%d:%02d:%02d" h m s))))
9480         (kill-new sres)
9481         (if (interactive-p)
9482             (message "%s"
9483                      (substitute-command-keys
9484                       (format "Sum of %d items: %-20s     (\\[yank] will insert result into buffer)"
9485                               (length numbers) sres))))
9486         sres))))
9488 (defun org-table-get-number-for-summing (s)
9489   (let (n)
9490     (if (string-match "^ *|? *" s)
9491         (setq s (replace-match "" nil nil s)))
9492     (if (string-match " *|? *$" s)
9493         (setq s (replace-match "" nil nil s)))
9494     (setq n (string-to-number s))
9495     (cond
9496      ((and (string-match "0" s)
9497            (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9498      ((string-match "\\`[ \t]+\\'" s)         nil)
9499      ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9500       (let ((h (string-to-number (or (match-string 1 s) "0")))
9501             (m (string-to-number (or (match-string 2 s) "0")))
9502             (s (string-to-number (or (match-string 4 s) "0"))))
9503         (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9504         (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9505      ((equal n 0)                             nil)
9506      (t n))))
9508 (defun org-table-current-field-formula (&optional key noerror)
9509   "Return the formula active for the current field.
9510 Assumes that specials are in place.
9511 If KEY is given, return the key to this formula.
9512 Otherwise return the formula preceeded with \"=\" or \":=\"."
9513   (let* ((name (car (rassoc (list (org-current-line)
9514                                   (org-table-current-column))
9515                             org-table-named-field-locations)))
9516          (col (org-table-current-column))
9517          (scol (int-to-string col))
9518          (ref (format "@%d$%d" (org-table-current-dline) col))
9519          (stored-list (org-table-get-stored-formulas noerror))
9520          (ass (or (assoc name stored-list)
9521                   (assoc ref stored-list)
9522                   (assoc scol stored-list))))
9523     (if key
9524         (car ass)
9525       (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9526                       (cdr ass))))))
9528 (defun org-table-get-formula (&optional equation named)
9529   "Read a formula from the minibuffer, offer stored formula as default.
9530 When NAMED is non-nil, look for a named equation."
9531   (let* ((stored-list (org-table-get-stored-formulas))
9532          (name (car (rassoc (list (org-current-line)
9533                                   (org-table-current-column))
9534                             org-table-named-field-locations)))
9535          (ref (format "@%d$%d" (org-table-current-dline)
9536                       (org-table-current-column)))
9537          (refass (assoc ref stored-list))
9538          (scol (if named
9539                    (if name name ref)
9540                  (int-to-string (org-table-current-column))))
9541          (dummy (and (or name refass) (not named)
9542                      (not (y-or-n-p "Replace field formula with column formula? " ))
9543                      (error "Abort")))
9544          (name (or name ref))
9545          (org-table-may-need-update nil)
9546          (stored (cdr (assoc scol stored-list)))
9547          (eq (cond
9548               ((and stored equation (string-match "^ *=? *$" equation))
9549                stored)
9550               ((stringp equation)
9551                equation)
9552               (t (org-table-formula-from-user
9553                   (read-string
9554                    (org-table-formula-to-user
9555                     (format "%s formula %s%s="
9556                             (if named "Field" "Column")
9557                             (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9558                             scol))
9559                    (if stored (org-table-formula-to-user stored) "")
9560                    'org-table-formula-history
9561                    )))))
9562          mustsave)
9563     (when (not (string-match "\\S-" eq))
9564       ;; remove formula
9565       (setq stored-list (delq (assoc scol stored-list) stored-list))
9566       (org-table-store-formulas stored-list)
9567       (error "Formula removed"))
9568     (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9569     (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9570     (if (and name (not named))
9571         ;; We set the column equation, delete the named one.
9572         (setq stored-list (delq (assoc name stored-list) stored-list)
9573               mustsave t))
9574     (if stored
9575         (setcdr (assoc scol stored-list) eq)
9576       (setq stored-list (cons (cons scol eq) stored-list)))
9577     (if (or mustsave (not (equal stored eq)))
9578         (org-table-store-formulas stored-list))
9579     eq))
9581 (defun org-table-store-formulas (alist)
9582   "Store the list of formulas below the current table."
9583   (setq alist (sort alist 'org-table-formula-less-p))
9584   (save-excursion
9585     (goto-char (org-table-end))
9586     (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9587         (progn
9588           ;; don't overwrite TBLFM, we might use text properties to store stuff
9589           (goto-char (match-beginning 2))
9590           (delete-region (match-beginning 2) (match-end 0)))
9591       (insert "#+TBLFM:"))
9592     (insert " "
9593             (mapconcat (lambda (x)
9594                          (concat
9595                           (if (equal (string-to-char (car x)) ?@) "" "$")
9596                           (car x) "=" (cdr x)))
9597                        alist "::")
9598             "\n")))
9600 (defsubst org-table-formula-make-cmp-string (a)
9601   (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9602     (concat
9603      (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9604      (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9605      (if (match-end 5) (concat "@@" (match-string 5 a))))))
9607 (defun org-table-formula-less-p (a b)
9608   "Compare two formulas for sorting."
9609   (let ((as (org-table-formula-make-cmp-string (car a)))
9610         (bs (org-table-formula-make-cmp-string (car b))))
9611     (and as bs (string< as bs))))
9613 (defun org-table-get-stored-formulas (&optional noerror)
9614   "Return an alist with the stored formulas directly after current table."
9615   (interactive)
9616   (let (scol eq eq-alist strings string seen)
9617     (save-excursion
9618       (goto-char (org-table-end))
9619       (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9620         (setq strings (org-split-string (match-string 2) " *:: *"))
9621         (while (setq string (pop strings))
9622           (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9623             (setq scol (if (match-end 2)
9624                            (match-string 2 string)
9625                          (match-string 1 string))
9626                   eq (match-string 3 string)
9627                   eq-alist (cons (cons scol eq) eq-alist))
9628             (if (member scol seen)
9629                 (if noerror
9630                     (progn
9631                       (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9632                       (ding)
9633                       (sit-for 2))
9634                   (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9635               (push scol seen))))))
9636     (nreverse eq-alist)))
9638 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9639   "Modify the equations after the table structure has been edited.
9640 KEY is \"@\" or \"$\".  REPLACE is an alist of numbers to replace.
9641 For all numbers larger than LIMIT, shift them by DELTA."
9642   (save-excursion
9643     (goto-char (org-table-end))
9644     (when (looking-at "#\\+TBLFM:")
9645       (let ((re (concat key "\\([0-9]+\\)"))
9646             (re2
9647              (when remove
9648                (if (equal key "$")
9649                    (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9650                  (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9651             s n a)
9652         (when remove
9653           (while (re-search-forward re2 (point-at-eol) t)
9654             (replace-match "")))
9655         (while (re-search-forward re (point-at-eol) t)
9656           (setq s (match-string 1) n (string-to-number s))
9657           (cond
9658            ((setq a (assoc s replace))
9659             (replace-match (concat key (cdr a)) t t))
9660            ((and limit (> n limit))
9661             (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9663 (defun org-table-get-specials ()
9664   "Get the column names and local parameters for this table."
9665   (save-excursion
9666     (let ((beg (org-table-begin)) (end (org-table-end))
9667           names name fields fields1 field cnt
9668           c v l line col types dlines hlines)
9669       (setq org-table-column-names nil
9670             org-table-local-parameters nil
9671             org-table-named-field-locations nil
9672             org-table-current-begin-line nil
9673             org-table-current-begin-pos nil
9674             org-table-current-line-types nil)
9675       (goto-char beg)
9676       (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9677         (setq names (org-split-string (match-string 1) " *| *")
9678               cnt 1)
9679         (while (setq name (pop names))
9680           (setq cnt (1+ cnt))
9681           (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9682               (push (cons name (int-to-string cnt)) org-table-column-names))))
9683       (setq org-table-column-names (nreverse org-table-column-names))
9684       (setq org-table-column-name-regexp
9685             (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9686       (goto-char beg)
9687       (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9688         (setq fields (org-split-string (match-string 1) " *| *"))
9689         (while (setq field (pop fields))
9690           (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9691               (push (cons (match-string 1 field) (match-string 2 field))
9692                     org-table-local-parameters))))
9693       (goto-char beg)
9694       (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9695         (setq c (match-string 1)
9696               fields (org-split-string (match-string 2) " *| *"))
9697         (save-excursion
9698           (beginning-of-line (if (equal c "_") 2 0))
9699           (setq line (org-current-line) col 1)
9700           (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9701                (setq fields1 (org-split-string (match-string 1) " *| *"))))
9702         (while (and fields1 (setq field (pop fields)))
9703           (setq v (pop fields1) col (1+ col))
9704           (when (and (stringp field) (stringp v)
9705                      (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9706               (push (cons field v) org-table-local-parameters)
9707               (push (list field line col) org-table-named-field-locations))))
9708       ;; Analyse the line types
9709       (goto-char beg)
9710       (setq org-table-current-begin-line (org-current-line)
9711             org-table-current-begin-pos (point)
9712             l org-table-current-begin-line)
9713       (while (looking-at "[ \t]*|\\(-\\)?")
9714         (push (if (match-end 1) 'hline 'dline) types)
9715         (if (match-end 1) (push l hlines) (push l dlines))
9716         (beginning-of-line 2)
9717         (setq l (1+ l)))
9718       (setq org-table-current-line-types (apply 'vector (nreverse types))
9719             org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9720             org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9722 (defun org-table-maybe-eval-formula ()
9723   "Check if the current field starts with \"=\" or \":=\".
9724 If yes, store the formula and apply it."
9725   ;; We already know we are in a table.  Get field will only return a formula
9726   ;; when appropriate.  It might return a separator line, but no problem.
9727   (when org-table-formula-evaluate-inline
9728     (let* ((field (org-trim (or (org-table-get-field) "")))
9729            named eq)
9730       (when (string-match "^:?=\\(.*\\)" field)
9731         (setq named (equal (string-to-char field) ?:)
9732               eq (match-string 1 field))
9733         (if (or (fboundp 'calc-eval)
9734                 (equal (substring eq 0 (min 2 (length eq))) "'("))
9735             (org-table-eval-formula (if named '(4) nil)
9736                                     (org-table-formula-from-user eq))
9737           (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9739 (defvar org-recalc-commands nil
9740   "List of commands triggering the recalculation of a line.
9741 Will be filled automatically during use.")
9743 (defvar org-recalc-marks
9744   '((" " . "Unmarked: no special line, no automatic recalculation")
9745     ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9746     ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9747     ("!" . "Column name definition line. Reference in formula as $name.")
9748     ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9749     ("_" . "Names for values in row below this one.")
9750     ("^" . "Names for values in row above this one.")))
9752 (defun org-table-rotate-recalc-marks (&optional newchar)
9753   "Rotate the recalculation mark in the first column.
9754 If in any row, the first field is not consistent with a mark,
9755 insert a new column for the markers.
9756 When there is an active region, change all the lines in the region,
9757 after prompting for the marking character.
9758 After each change, a message will be displayed indicating the meaning
9759 of the new mark."
9760   (interactive)
9761   (unless (org-at-table-p) (error "Not at a table"))
9762   (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9763          (beg (org-table-begin))
9764          (end (org-table-end))
9765          (l (org-current-line))
9766          (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9767          (l2 (if (org-region-active-p) (org-current-line (region-end))))
9768          (have-col
9769           (save-excursion
9770             (goto-char beg)
9771             (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9772          (col (org-table-current-column))
9773          (forcenew (car (assoc newchar org-recalc-marks)))
9774          epos new)
9775     (when l1
9776       (message "Change region to what mark?  Type # * ! $ or SPC: ")
9777       (setq newchar (char-to-string (read-char-exclusive))
9778             forcenew (car (assoc newchar org-recalc-marks))))
9779     (if (and newchar (not forcenew))
9780         (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9781                newchar))
9782     (if l1 (goto-line l1))
9783     (save-excursion
9784       (beginning-of-line 1)
9785       (unless (looking-at org-table-dataline-regexp)
9786         (error "Not at a table data line")))
9787     (unless have-col
9788       (org-table-goto-column 1)
9789       (org-table-insert-column)
9790       (org-table-goto-column (1+ col)))
9791     (setq epos (point-at-eol))
9792     (save-excursion
9793       (beginning-of-line 1)
9794       (org-table-get-field
9795        1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9796              (concat " "
9797                      (setq new (or forcenew
9798                                    (cadr (member (match-string 1) marks))))
9799                      " ")
9800            " # ")))
9801     (if (and l1 l2)
9802         (progn
9803           (goto-line l1)
9804           (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9805             (and (looking-at org-table-dataline-regexp)
9806                  (org-table-get-field 1 (concat " " new " "))))
9807           (goto-line l1)))
9808     (if (not (= epos (point-at-eol))) (org-table-align))
9809     (goto-line l)
9810     (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
9812 (defun org-table-maybe-recalculate-line ()
9813   "Recompute the current line if marked for it, and if we haven't just done it."
9814   (interactive)
9815   (and org-table-allow-automatic-line-recalculation
9816        (not (and (memq last-command org-recalc-commands)
9817                  (equal org-last-recalc-line (org-current-line))))
9818        (save-excursion (beginning-of-line 1)
9819                        (looking-at org-table-auto-recalculate-regexp))
9820        (org-table-recalculate) t))
9822 (defvar org-table-formula-debug nil
9823   "Non-nil means, debug table formulas.
9824 When nil, simply write \"#ERROR\" in corrupted fields.")
9825 (make-variable-buffer-local 'org-table-formula-debug)
9827 (defvar modes)
9828 (defsubst org-set-calc-mode (var &optional value)
9829   (if (stringp var)
9830       (setq var (assoc var '(("D" calc-angle-mode deg)
9831                              ("R" calc-angle-mode rad)
9832                              ("F" calc-prefer-frac t)
9833                              ("S" calc-symbolic-mode t)))
9834             value (nth 2 var) var (nth 1 var)))
9835   (if (memq var modes)
9836       (setcar (cdr (memq var modes)) value)
9837     (cons var (cons value modes)))
9838   modes)
9840 (defun org-table-eval-formula (&optional arg equation
9841                                          suppress-align suppress-const
9842                                          suppress-store suppress-analysis)
9843   "Replace the table field value at the cursor by the result of a calculation.
9845 This function makes use of Dave Gillespie's Calc package, in my view the
9846 most exciting program ever written for GNU Emacs.  So you need to have Calc
9847 installed in order to use this function.
9849 In a table, this command replaces the value in the current field with the
9850 result of a formula.  It also installs the formula as the \"current\" column
9851 formula, by storing it in a special line below the table.  When called
9852 with a `C-u' prefix, the current field must ba a named field, and the
9853 formula is installed as valid in only this specific field.
9855 When called with two `C-u' prefixes, insert the active equation
9856 for the field back into the current field, so that it can be
9857 edited there.  This is useful in order to use \\[org-table-show-reference]
9858 to check the referenced fields.
9860 When called, the command first prompts for a formula, which is read in
9861 the minibuffer.  Previously entered formulas are available through the
9862 history list, and the last used formula is offered as a default.
9863 These stored formulas are adapted correctly when moving, inserting, or
9864 deleting columns with the corresponding commands.
9866 The formula can be any algebraic expression understood by the Calc package.
9867 For details, see the Org-mode manual.
9869 This function can also be called from Lisp programs and offers
9870 additional arguments: EQUATION can be the formula to apply.  If this
9871 argument is given, the user will not be prompted.  SUPPRESS-ALIGN is
9872 used to speed-up recursive calls by by-passing unnecessary aligns.
9873 SUPPRESS-CONST suppresses the interpretation of constants in the
9874 formula, assuming that this has been done already outside the function.
9875 SUPPRESS-STORE means the formula should not be stored, either because
9876 it is already stored, or because it is a modified equation that should
9877 not overwrite the stored one."
9878   (interactive "P")
9879   (org-table-check-inside-data-field)
9880   (or suppress-analysis (org-table-get-specials))
9881   (if (equal arg '(16))
9882       (let ((eq (org-table-current-field-formula)))
9883         (or eq (error "No equation active for current field"))
9884         (org-table-get-field nil eq)
9885         (org-table-align)
9886         (setq org-table-may-need-update t))
9887     (let* (fields
9888            (ndown (if (integerp arg) arg 1))
9889            (org-table-automatic-realign nil)
9890            (case-fold-search nil)
9891            (down (> ndown 1))
9892            (formula (if (and equation suppress-store)
9893                         equation
9894                       (org-table-get-formula equation (equal arg '(4)))))
9895            (n0 (org-table-current-column))
9896            (modes (copy-sequence org-calc-default-modes))
9897            (numbers nil) ; was a variable, now fixed default
9898            (keep-empty nil)
9899            n form form0 bw fmt x ev orig c lispp literal)
9900       ;; Parse the format string.  Since we have a lot of modes, this is
9901       ;; a lot of work.  However, I think calc still uses most of the time.
9902       (if (string-match ";" formula)
9903           (let ((tmp (org-split-string formula ";")))
9904             (setq formula (car tmp)
9905                   fmt (concat (cdr (assoc "%" org-table-local-parameters))
9906                               (nth 1 tmp)))
9907             (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
9908               (setq c (string-to-char (match-string 1 fmt))
9909                     n (string-to-number (match-string 2 fmt)))
9910               (if (= c ?p)
9911                   (setq modes (org-set-calc-mode 'calc-internal-prec n))
9912                 (setq modes (org-set-calc-mode
9913                              'calc-float-format
9914                              (list (cdr (assoc c '((?n . float) (?f . fix)
9915                                                    (?s . sci) (?e . eng))))
9916                                    n))))
9917               (setq fmt (replace-match "" t t fmt)))
9918             (if (string-match "[NT]" fmt)
9919                 (setq numbers (equal (match-string 0 fmt) "N")
9920                       fmt (replace-match "" t t fmt)))
9921             (if (string-match "L" fmt)
9922                 (setq literal t
9923                       fmt (replace-match "" t t fmt)))
9924             (if (string-match "E" fmt)
9925                 (setq keep-empty t
9926                       fmt (replace-match "" t t fmt)))
9927             (while (string-match "[DRFS]" fmt)
9928               (setq modes (org-set-calc-mode (match-string 0 fmt)))
9929               (setq fmt (replace-match "" t t fmt)))
9930             (unless (string-match "\\S-" fmt)
9931               (setq fmt nil))))
9932       (if (and (not suppress-const) org-table-formula-use-constants)
9933           (setq formula (org-table-formula-substitute-names formula)))
9934       (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9935       (while (> ndown 0)
9936         (setq fields (org-split-string
9937                       (org-no-properties
9938                        (buffer-substring (point-at-bol) (point-at-eol)))
9939                       " *| *"))
9940         (if (eq numbers t)
9941             (setq fields (mapcar
9942                           (lambda (x) (number-to-string (string-to-number x)))
9943                           fields)))
9944         (setq ndown (1- ndown))
9945         (setq form (copy-sequence formula)
9946               lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
9947         (if (and lispp literal) (setq lispp 'literal))
9948         ;; Check for old vertical references
9949         (setq form (org-rewrite-old-row-references form))
9950         ;; Insert complex ranges
9951         (while (string-match org-table-range-regexp form)
9952           (setq form
9953                 (replace-match
9954                  (save-match-data
9955                    (org-table-make-reference
9956                     (org-table-get-range (match-string 0 form) nil n0)
9957                     keep-empty numbers lispp))
9958                  t t form)))
9959         ;; Insert simple ranges
9960         (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)"  form)
9961           (setq form
9962                 (replace-match
9963                  (save-match-data
9964                    (org-table-make-reference
9965                     (org-sublist
9966                      fields (string-to-number (match-string 1 form))
9967                      (string-to-number (match-string 2 form)))
9968                     keep-empty numbers lispp))
9969                  t t form)))
9970         (setq form0 form)
9971         ;; Insert the references to fields in same row
9972         (while (string-match "\\$\\([0-9]+\\)" form)
9973           (setq n (string-to-number (match-string 1 form))
9974                 x (nth (1- (if (= n 0) n0 n)) fields))
9975           (unless x (error "Invalid field specifier \"%s\""
9976                            (match-string 0 form)))
9977           (setq form (replace-match
9978                       (save-match-data
9979                         (org-table-make-reference x nil numbers lispp))
9980                       t t form)))
9982         (if lispp
9983             (setq ev (condition-case nil
9984                          (eval (eval (read form)))
9985                        (error "#ERROR"))
9986                   ev (if (numberp ev) (number-to-string ev) ev))
9987           (or (fboundp 'calc-eval)
9988               (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
9989           (setq ev (calc-eval (cons form modes)
9990                               (if numbers 'num))))
9992         (when org-table-formula-debug
9993           (with-output-to-temp-buffer "*Substitution History*"
9994             (princ (format "Substitution history of formula
9995 Orig:   %s
9996 $xyz->  %s
9997 @r$c->  %s
9998 $1->    %s\n" orig formula form0 form))
9999             (if (listp ev)
10000                 (princ (format "       %s^\nError:  %s"
10001                                (make-string (car ev) ?\-) (nth 1 ev)))
10002               (princ (format "Result: %s\nFormat: %s\nFinal:  %s"
10003                              ev (or fmt "NONE")
10004                              (if fmt (format fmt (string-to-number ev)) ev)))))
10005           (setq bw (get-buffer-window "*Substitution History*"))
10006           (shrink-window-if-larger-than-buffer bw)
10007           (unless (and (interactive-p) (not ndown))
10008             (unless (let (inhibit-redisplay)
10009                       (y-or-n-p "Debugging Formula. Continue to next? "))
10010               (org-table-align)
10011               (error "Abort"))
10012             (delete-window bw)
10013             (message "")))
10014         (if (listp ev) (setq fmt nil ev "#ERROR"))
10015         (org-table-justify-field-maybe
10016          (if fmt (format fmt (string-to-number ev)) ev))
10017         (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10018             (call-interactively 'org-return)
10019           (setq ndown 0)))
10020       (and down (org-table-maybe-recalculate-line))
10021       (or suppress-align (and org-table-may-need-update
10022                               (org-table-align))))))
10024 (defun org-table-put-field-property (prop value)
10025   (save-excursion
10026     (put-text-property (progn (skip-chars-backward "^|") (point))
10027                        (progn (skip-chars-forward "^|") (point))
10028                        prop value)))
10030 (defun org-table-get-range (desc &optional tbeg col highlight)
10031   "Get a calc vector from a column, accorting to descriptor DESC.
10032 Optional arguments TBEG and COL can give the beginning of the table and
10033 the current column, to avoid unnecessary parsing.
10034 HIGHLIGHT means, just highlight the range."
10035   (if (not (equal (string-to-char desc) ?@))
10036       (setq desc (concat "@" desc)))
10037   (save-excursion
10038     (or tbeg (setq tbeg (org-table-begin)))
10039     (or col (setq col (org-table-current-column)))
10040     (let ((thisline (org-current-line))
10041           beg end c1 c2 r1 r2 rangep tmp)
10042       (unless (string-match org-table-range-regexp desc)
10043         (error "Invalid table range specifier `%s'" desc))
10044       (setq rangep (match-end 3)
10045             r1 (and (match-end 1) (match-string 1 desc))
10046             r2 (and (match-end 4) (match-string 4 desc))
10047             c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10048             c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10050       (and c1 (setq c1 (+ (string-to-number c1)
10051                           (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10052       (and c2 (setq c2 (+ (string-to-number c2)
10053                           (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10054       (if (equal r1 "") (setq r1 nil))
10055       (if (equal r2 "") (setq r2 nil))
10056       (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10057       (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10058 ;      (setq r2 (or r2 r1) c2 (or c2 c1))
10059       (if (not r1) (setq r1 thisline))
10060       (if (not r2) (setq r2 thisline))
10061       (if (not c1) (setq c1 col))
10062       (if (not c2) (setq c2 col))
10063       (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10064           ;; just one field
10065           (progn
10066             (goto-line r1)
10067             (while (not (looking-at org-table-dataline-regexp))
10068               (beginning-of-line 2))
10069             (prog1 (org-trim (org-table-get-field c1))
10070               (if highlight (org-table-highlight-rectangle (point) (point)))))
10071         ;; A range, return a vector
10072         ;; First sort the numbers to get a regular ractangle
10073         (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10074         (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10075         (goto-line r1)
10076         (while (not (looking-at org-table-dataline-regexp))
10077           (beginning-of-line 2))
10078         (org-table-goto-column c1)
10079         (setq beg (point))
10080         (goto-line r2)
10081         (while (not (looking-at org-table-dataline-regexp))
10082           (beginning-of-line 0))
10083         (org-table-goto-column c2)
10084         (setq end (point))
10085         (if highlight
10086             (org-table-highlight-rectangle
10087              beg (progn (skip-chars-forward "^|\n") (point))))
10088         ;; return string representation of calc vector
10089         (mapcar 'org-trim
10090                 (apply 'append (org-table-copy-region beg end)))))))
10092 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10093   "Analyze descriptor DESC and retrieve the corresponding line number.
10094 The cursor is currently in line CLINE, the table begins in line BLINE,
10095 and TABLE is a vector with line types."
10096   (if (string-match "^[0-9]+$" desc)
10097       (aref org-table-dlines (string-to-number desc))
10098     (setq cline (or cline (org-current-line))
10099           bline (or bline org-table-current-begin-line)
10100           table (or table org-table-current-line-types))
10101     (if (or
10102          (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10103          ;;                     1  2          3           4  5          6
10104          (and (not (match-end 3)) (not (match-end 6)))
10105          (and (match-end 3) (match-end 6) (not (match-end 5))))
10106         (error "invalid row descriptor `%s'" desc))
10107     (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10108            (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10109            (odir (and (match-end 5) (match-string 5 desc)))
10110            (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10111            (i (- cline bline))
10112            (rel (and (match-end 6)
10113                      (or (and (match-end 1) (not (match-end 3)))
10114                          (match-end 5)))))
10115       (if (and hn (not hdir))
10116           (progn
10117             (setq i 0 hdir "+")
10118             (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10119       (if (and (not hn) on (not odir))
10120           (error "should never happen");;(aref org-table-dlines on)
10121         (if (and hn (> hn 0))
10122             (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10123         (if on
10124             (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10125         (+ bline i)))))
10127 (defun org-find-row-type (table i type backwards relative n)
10128   (let ((l (length table)))
10129     (while (> n 0)
10130       (while (and (setq i (+ i (if backwards -1 1)))
10131                   (>= i 0) (< i l)
10132                   (not (eq (aref table i) type))
10133                   (if (and relative (eq (aref table i) 'hline))
10134                       (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10135                     t)))
10136       (setq n (1- n)))
10137     (if (or (< i 0) (>= i l))
10138         (error "Row descriptior leads outside table")
10139       i)))
10141 (defun org-rewrite-old-row-references (s)
10142   (if (string-match "&[-+0-9I]" s)
10143       (error "Formula contains old &row reference, please rewrite using @-syntax")
10144     s))
10146 (defun org-table-make-reference (elements keep-empty numbers lispp)
10147   "Convert list ELEMENTS to something appropriate to insert into formula.
10148 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10149 NUMBERS indicates that everything should be converted to numbers.
10150 LISPP means to return something appropriate for a Lisp list."
10151   (if (stringp elements) ; just a single val
10152       (if lispp
10153           (if (eq lispp 'literal)
10154               elements
10155             (prin1-to-string (if numbers (string-to-number elements) elements)))
10156         (if (equal elements "") (setq elements "0"))
10157         (if numbers (number-to-string (string-to-number elements)) elements))
10158     (unless keep-empty
10159       (setq elements
10160             (delq nil
10161                   (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10162                           elements))))
10163     (setq elements (or elements '("0")))
10164     (if lispp
10165         (mapconcat
10166          (lambda (x)
10167            (if (eq lispp 'literal)
10168                x
10169              (prin1-to-string (if numbers (string-to-number x) x))))
10170          elements " ")
10171       (concat "[" (mapconcat
10172                    (lambda (x)
10173                      (if numbers (number-to-string (string-to-number x)) x))
10174                    elements
10175                    ",") "]"))))
10177 (defun org-table-recalculate (&optional all noalign)
10178   "Recalculate the current table line by applying all stored formulas.
10179 With prefix arg ALL, do this for all lines in the table."
10180   (interactive "P")
10181   (or (memq this-command org-recalc-commands)
10182       (setq org-recalc-commands (cons this-command org-recalc-commands)))
10183   (unless (org-at-table-p) (error "Not at a table"))
10184   (if (equal all '(16))
10185       (org-table-iterate)
10186     (org-table-get-specials)
10187     (let* ((eqlist (sort (org-table-get-stored-formulas)
10188                          (lambda (a b) (string< (car a) (car b)))))
10189            (inhibit-redisplay (not debug-on-error))
10190            (line-re org-table-dataline-regexp)
10191            (thisline (org-current-line))
10192            (thiscol (org-table-current-column))
10193            beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10194       ;; Insert constants in all formulas
10195       (setq eqlist
10196             (mapcar (lambda (x)
10197                       (setcdr x (org-table-formula-substitute-names (cdr x)))
10198                       x)
10199                     eqlist))
10200       ;; Split the equation list
10201       (while (setq eq (pop eqlist))
10202         (if (<= (string-to-char (car eq)) ?9)
10203             (push eq eqlnum)
10204           (push eq eqlname)))
10205       (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10206       (if all
10207           (progn
10208             (setq end (move-marker (make-marker) (1+ (org-table-end))))
10209             (goto-char (setq beg (org-table-begin)))
10210             (if (re-search-forward org-table-calculate-mark-regexp end t)
10211                 ;; This is a table with marked lines, compute selected lines
10212                 (setq line-re org-table-recalculate-regexp)
10213               ;; Move forward to the first non-header line
10214               (if (and (re-search-forward org-table-dataline-regexp end t)
10215                        (re-search-forward org-table-hline-regexp end t)
10216                        (re-search-forward org-table-dataline-regexp end t))
10217                   (setq beg (match-beginning 0))
10218                 nil))) ;; just leave beg where it is
10219         (setq beg (point-at-bol)
10220               end (move-marker (make-marker) (1+ (point-at-eol)))))
10221       (goto-char beg)
10222       (and all (message "Re-applying formulas to full table..."))
10224       ;; First find the named fields, and mark them untouchanble
10225       (remove-text-properties beg end '(org-untouchable t))
10226       (while (setq eq (pop eqlname))
10227         (setq name (car eq)
10228               a (assoc name org-table-named-field-locations))
10229         (and (not a)
10230              (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10231              (setq a (list name
10232                            (aref org-table-dlines
10233                                  (string-to-number (match-string 1 name)))
10234                            (string-to-number (match-string 2 name)))))
10235         (when (and a (or all (equal (nth 1 a) thisline)))
10236           (message "Re-applying formula to field: %s" name)
10237           (goto-line (nth 1 a))
10238           (org-table-goto-column (nth 2 a))
10239           (push (append a (list (cdr eq))) eqlname1)
10240           (org-table-put-field-property :org-untouchable t)))
10242       ;; Now evauluate the column formulas, but skip fields covered by
10243       ;; field formulas
10244       (goto-char beg)
10245       (while (re-search-forward line-re end t)
10246         (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10247           ;; Unprotected line, recalculate
10248           (and all (message "Re-applying formulas to full table...(line %d)"
10249                             (setq cnt (1+ cnt))))
10250           (setq org-last-recalc-line (org-current-line))
10251           (setq eql eqlnum)
10252           (while (setq entry (pop eql))
10253             (goto-line org-last-recalc-line)
10254             (org-table-goto-column (string-to-number (car entry)) nil 'force)
10255             (unless (get-text-property (point) :org-untouchable)
10256               (org-table-eval-formula nil (cdr entry)
10257                                       'noalign 'nocst 'nostore 'noanalysis)))))
10259       ;; Now evaluate the field formulas
10260       (while (setq eq (pop eqlname1))
10261         (message "Re-applying formula to field: %s" (car eq))
10262         (goto-line (nth 1 eq))
10263         (org-table-goto-column (nth 2 eq))
10264         (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10265                                 'nostore 'noanalysis))
10267       (goto-line thisline)
10268       (org-table-goto-column thiscol)
10269       (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10270       (or noalign (and org-table-may-need-update (org-table-align))
10271           (and all (message "Re-applying formulas to %d lines...done" cnt)))
10273       ;; back to initial position
10274       (message "Re-applying formulas...done")
10275       (goto-line thisline)
10276       (org-table-goto-column thiscol)
10277       (or noalign (and org-table-may-need-update (org-table-align))
10278           (and all (message "Re-applying formulas...done"))))))
10280 (defun org-table-iterate (&optional arg)
10281   "Recalculate the table until it does not change anymore."
10282   (interactive "P")
10283   (let ((imax (if arg (prefix-numeric-value arg) 10))
10284         (i 0)
10285         (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10286         thistbl)
10287     (catch 'exit
10288       (while (< i imax)
10289         (setq i (1+ i))
10290         (org-table-recalculate 'all)
10291         (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10292         (if (not (string= lasttbl thistbl))
10293             (setq lasttbl thistbl)
10294           (if (> i 1)
10295               (message "Convergence after %d iterations" i)
10296             (message "Table was already stable"))
10297           (throw 'exit t)))
10298       (error "No convergence after %d iterations" i))))
10300 (defun org-table-formula-substitute-names (f)
10301   "Replace $const with values in string F."
10302   (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10303     ;; First, check for column names
10304     (while (setq start (string-match org-table-column-name-regexp f start))
10305       (setq start (1+ start))
10306       (setq a (assoc (match-string 1 f) org-table-column-names))
10307       (setq f (replace-match (concat "$" (cdr a)) t t f)))
10308     ;; Parameters and constants
10309     (setq start 0)
10310     (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10311       (setq start (1+ start))
10312       (if (setq a (save-match-data
10313                     (org-table-get-constant (match-string 1 f))))
10314           (setq f (replace-match
10315                    (concat (if pp "(") a (if pp ")")) t t f))))
10316     (if org-table-formula-debug
10317         (put-text-property 0 (length f) :orig-formula f1 f))
10318     f))
10320 (defun org-table-get-constant (const)
10321   "Find the value for a parameter or constant in a formula.
10322 Parameters get priority."
10323   (or (cdr (assoc const org-table-local-parameters))
10324       (cdr (assoc const org-table-formula-constants-local))
10325       (cdr (assoc const org-table-formula-constants))
10326       (and (fboundp 'constants-get) (constants-get const))
10327       (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10328            (org-entry-get nil (substring const 5) 'inherit))
10329       "#UNDEFINED_NAME"))
10331 (defvar org-table-fedit-map
10332   (let ((map (make-sparse-keymap)))
10333     (org-defkey map "\C-x\C-s"      'org-table-fedit-finish)
10334     (org-defkey map "\C-c\C-s"      'org-table-fedit-finish)
10335     (org-defkey map "\C-c\C-c"      'org-table-fedit-finish)
10336     (org-defkey map "\C-c\C-q"      'org-table-fedit-abort)
10337     (org-defkey map "\C-c?"         'org-table-show-reference)
10338     (org-defkey map [(meta shift up)]    'org-table-fedit-line-up)
10339     (org-defkey map [(meta shift down)]  'org-table-fedit-line-down)
10340     (org-defkey map [(shift up)]    'org-table-fedit-ref-up)
10341     (org-defkey map [(shift down)]  'org-table-fedit-ref-down)
10342     (org-defkey map [(shift left)]  'org-table-fedit-ref-left)
10343     (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10344     (org-defkey map [(meta up)]     'org-table-fedit-scroll-down)
10345     (org-defkey map [(meta down)]   'org-table-fedit-scroll)
10346     (org-defkey map [(meta tab)]    'lisp-complete-symbol)
10347     (org-defkey map "\M-\C-i"       'lisp-complete-symbol)
10348     (org-defkey map [(tab)]         'org-table-fedit-lisp-indent)
10349     (org-defkey map "\C-i"          'org-table-fedit-lisp-indent)
10350     (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10351     (org-defkey map "\C-c}"    'org-table-fedit-toggle-coordinates)
10352     map))
10354 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10355   '("Edit-Formulas"
10356     ["Finish and Install" org-table-fedit-finish t]
10357     ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10358     ["Abort" org-table-fedit-abort t]
10359     "--"
10360     ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10361     ["Complete Lisp Symbol" lisp-complete-symbol t]
10362     "--"
10363     "Shift Reference at Point"
10364     ["Up" org-table-fedit-ref-up t]
10365     ["Down" org-table-fedit-ref-down t]
10366     ["Left" org-table-fedit-ref-left t]
10367     ["Right" org-table-fedit-ref-right t]
10368     "-"
10369     "Change Test Row for Column Formulas"
10370     ["Up" org-table-fedit-line-up t]
10371     ["Down" org-table-fedit-line-down t]
10372     "--"
10373     ["Scroll Table Window" org-table-fedit-scroll t]
10374     ["Scroll Table Window down" org-table-fedit-scroll-down t]
10375     ["Show Table Grid" org-table-fedit-toggle-coordinates
10376      :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10377                                org-table-overlay-coordinates)]
10378     "--"
10379     ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10380      :style toggle :selected org-table-buffer-is-an]))
10382 (defvar org-pos)
10384 (defun org-table-edit-formulas ()
10385   "Edit the formulas of the current table in a separate buffer."
10386   (interactive)
10387   (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10388     (beginning-of-line 0))
10389   (unless (org-at-table-p) (error "Not at a table"))
10390   (org-table-get-specials)
10391   (let ((key (org-table-current-field-formula 'key 'noerror))
10392         (eql (sort (org-table-get-stored-formulas 'noerror)
10393                    'org-table-formula-less-p))
10394         (pos (move-marker (make-marker) (point)))
10395         (startline 1)
10396         (wc (current-window-configuration))
10397         (titles '((column . "# Column Formulas\n")
10398                   (field . "# Field Formulas\n")
10399                   (named . "# Named Field Formulas\n")))
10400         entry s type title)
10401     (org-switch-to-buffer-other-window "*Edit Formulas*")
10402     (erase-buffer)
10403     ;; Keep global-font-lock-mode from turning on font-lock-mode
10404     (let ((font-lock-global-modes '(not fundamental-mode)))
10405       (fundamental-mode))
10406     (org-set-local 'font-lock-global-modes (list 'not major-mode))
10407     (org-set-local 'org-pos pos)
10408     (org-set-local 'org-window-configuration wc)
10409     (use-local-map org-table-fedit-map)
10410     (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10411     (easy-menu-add org-table-fedit-menu)
10412     (setq startline (org-current-line))
10413     (while (setq entry (pop eql))
10414       (setq type (cond
10415                   ((equal (string-to-char (car entry)) ?@) 'field)
10416                   ((string-match "^[0-9]" (car entry)) 'column)
10417                   (t 'named)))
10418       (when (setq title (assq type titles))
10419         (or (bobp) (insert "\n"))
10420         (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10421         (setq titles (delq title titles)))
10422       (if (equal key (car entry)) (setq startline (org-current-line)))
10423       (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10424                       (car entry) " = " (cdr entry) "\n"))
10425       (remove-text-properties 0 (length s) '(face nil) s)
10426       (insert s))
10427     (if (eq org-table-use-standard-references t)
10428         (org-table-fedit-toggle-ref-type))
10429     (goto-line startline)
10430     (message "Edit formulas and finish with `C-c C-c'.  See menu for more commands.")))
10432 (defun org-table-fedit-post-command ()
10433   (when (not (memq this-command '(lisp-complete-symbol)))
10434     (let ((win (selected-window)))
10435       (save-excursion
10436         (condition-case nil
10437             (org-table-show-reference)
10438           (error nil))
10439         (select-window win)))))
10441 (defun org-table-formula-to-user (s)
10442   "Convert a formula from internal to user representation."
10443   (if (eq org-table-use-standard-references t)
10444       (org-table-convert-refs-to-an s)
10445     s))
10447 (defun org-table-formula-from-user (s)
10448   "Convert a formula from user to internal representation."
10449   (if org-table-use-standard-references
10450       (org-table-convert-refs-to-rc s)
10451     s))
10453 (defun org-table-convert-refs-to-rc (s)
10454   "Convert spreadsheet references from AB7 to @7$28.
10455 Works for single references, but also for entire formulas and even the
10456 full TBLFM line."
10457   (let ((start 0))
10458     (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10459       (cond
10460        ((match-end 3)
10461         ;; format match, just advance
10462         (setq start (match-end 0)))
10463        ((and (> (match-beginning 0) 0)
10464              (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10465              (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10466         ;; 3.e5 or something like this.
10467         (setq start (match-end 0)))
10468        (t
10469         (setq start (match-beginning 0)
10470               s (replace-match
10471                  (if (equal (match-string 2 s) "&")
10472                      (format "$%d" (org-letters-to-number (match-string 1 s)))
10473                    (format "@%d$%d"
10474                            (string-to-number (match-string 2 s))
10475                            (org-letters-to-number (match-string 1 s))))
10476                  t t s)))))
10477     s))
10479 (defun org-table-convert-refs-to-an (s)
10480   "Convert spreadsheet references from to @7$28 to AB7.
10481 Works for single references, but also for entire formulas and even the
10482 full TBLFM line."
10483   (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10484     (setq s (replace-match
10485              (format "%s%d"
10486                      (org-number-to-letters
10487                       (string-to-number (match-string 2 s)))
10488                      (string-to-number (match-string 1 s)))
10489              t t s)))
10490   (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10491     (setq s (replace-match (concat "\\1"
10492                                    (org-number-to-letters
10493                                     (string-to-number (match-string 2 s))) "&")
10494                            t nil s)))
10495   s)
10497 (defun org-letters-to-number (s)
10498   "Convert a base 26 number represented by letters into an integer.
10499 For example:  AB -> 28."
10500   (let ((n 0))
10501     (setq s (upcase s))
10502     (while (> (length s) 0)
10503           (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10504                 s (substring s 1)))
10505     n))
10507 (defun org-number-to-letters (n)
10508   "Convert an integer into a base 26 number represented by letters.
10509 For example:  28 -> AB."
10510   (let ((s ""))
10511     (while (> n 0)
10512       (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10513             n (/ (1- n) 26)))
10514     s))
10516 (defun org-table-fedit-convert-buffer (function)
10517   "Convert all references in this buffer, using FUNTION."
10518   (let ((line (org-current-line)))
10519     (goto-char (point-min))
10520     (while (not (eobp))
10521       (insert (funcall function (buffer-substring (point) (point-at-eol))))
10522       (delete-region (point) (point-at-eol))
10523       (or (eobp) (forward-char 1)))
10524     (goto-line line)))
10526 (defun org-table-fedit-toggle-ref-type ()
10527   "Convert all references in the buffer from B3 to @3$2 and back."
10528   (interactive)
10529   (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10530   (org-table-fedit-convert-buffer
10531    (if org-table-buffer-is-an
10532        'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10533   (message "Reference type switched to %s"
10534            (if org-table-buffer-is-an "A1 etc" "@row$column")))
10536 (defun org-table-fedit-ref-up ()
10537   "Shift the reference at point one row/hline up."
10538   (interactive)
10539   (org-table-fedit-shift-reference 'up))
10540 (defun org-table-fedit-ref-down ()
10541   "Shift the reference at point one row/hline down."
10542   (interactive)
10543   (org-table-fedit-shift-reference 'down))
10544 (defun org-table-fedit-ref-left ()
10545   "Shift the reference at point one field to the left."
10546   (interactive)
10547   (org-table-fedit-shift-reference 'left))
10548 (defun org-table-fedit-ref-right ()
10549   "Shift the reference at point one field to the right."
10550   (interactive)
10551   (org-table-fedit-shift-reference 'right))
10553 (defun org-table-fedit-shift-reference (dir)
10554   (cond
10555    ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10556     (if (memq dir '(left right))
10557         (org-rematch-and-replace 1 (eq dir 'left))
10558       (error "Cannot shift reference in this direction")))
10559    ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10560     ;; A B3-like reference
10561     (if (memq dir '(up down))
10562         (org-rematch-and-replace 2 (eq dir 'up))
10563       (org-rematch-and-replace 1 (eq dir 'left))))
10564    ((org-at-regexp-p
10565      "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10566     ;; An internal reference
10567     (if (memq dir '(up down))
10568         (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10569       (org-rematch-and-replace 5 (eq dir 'left))))))
10571 (defun org-rematch-and-replace (n &optional decr hline)
10572   "Re-match the group N, and replace it with the shifted refrence."
10573   (or (match-end n) (error "Cannot shift reference in this direction"))
10574   (goto-char (match-beginning n))
10575   (and (looking-at (regexp-quote (match-string n)))
10576        (replace-match (org-shift-refpart (match-string 0) decr hline)
10577                       t t)))
10579 (defun org-shift-refpart (ref &optional decr hline)
10580   "Shift a refrence part REF.
10581 If DECR is set, decrease the references row/column, else increase.
10582 If HLINE is set, this may be a hline reference, it certainly is not
10583 a translation reference."
10584   (save-match-data
10585     (let* ((sign (string-match "^[-+]" ref)) n)
10587       (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10588       (cond
10589        ((and hline (string-match "^I+" ref))
10590         (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10591         (setq n (+ n (if decr -1 1)))
10592         (if (= n 0) (setq n (+ n (if decr -1 1))))
10593         (if sign
10594             (setq sign (if (< n 0) "-" "+") n (abs n))
10595           (setq n (max 1 n)))
10596         (concat sign (make-string n ?I)))
10598        ((string-match "^[0-9]+" ref)
10599         (setq n (string-to-number (concat sign ref)))
10600         (setq n (+ n (if decr -1 1)))
10601         (if sign
10602             (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10603           (number-to-string (max 1 n))))
10605        ((string-match "^[a-zA-Z]+" ref)
10606         (org-number-to-letters
10607          (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10609        (t (error "Cannot shift reference"))))))
10611 (defun org-table-fedit-toggle-coordinates ()
10612   "Toggle the display of coordinates in the refrenced table."
10613   (interactive)
10614   (let ((pos (marker-position org-pos)))
10615     (with-current-buffer (marker-buffer org-pos)
10616       (save-excursion
10617         (goto-char pos)
10618         (org-table-toggle-coordinate-overlays)))))
10620 (defun org-table-fedit-finish (&optional arg)
10621   "Parse the buffer for formula definitions and install them.
10622 With prefix ARG, apply the new formulas to the table."
10623   (interactive "P")
10624   (org-table-remove-rectangle-highlight)
10625   (if org-table-use-standard-references
10626       (progn
10627         (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10628         (setq org-table-buffer-is-an nil)))
10629   (let ((pos org-pos) eql var form)
10630     (goto-char (point-min))
10631     (while (re-search-forward
10632             "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10633             nil t)
10634       (setq var (if (match-end 2) (match-string 2) (match-string 1))
10635             form (match-string 3))
10636       (setq form (org-trim form))
10637       (when (not (equal form ""))
10638         (while (string-match "[ \t]*\n[ \t]*" form)
10639           (setq form (replace-match " " t t form)))
10640         (when (assoc var eql)
10641           (error "Double formulas for %s" var))
10642         (push (cons var form) eql)))
10643     (setq org-pos nil)
10644     (set-window-configuration org-window-configuration)
10645     (select-window (get-buffer-window (marker-buffer pos)))
10646     (goto-char pos)
10647     (unless (org-at-table-p)
10648       (error "Lost table position - cannot install formulae"))
10649     (org-table-store-formulas eql)
10650     (move-marker pos nil)
10651     (kill-buffer "*Edit Formulas*")
10652     (if arg
10653         (org-table-recalculate 'all)
10654       (message "New formulas installed - press C-u C-c C-c to apply."))))
10656 (defun org-table-fedit-abort ()
10657   "Abort editing formulas, without installing the changes."
10658   (interactive)
10659   (org-table-remove-rectangle-highlight)
10660   (let ((pos org-pos))
10661     (set-window-configuration org-window-configuration)
10662     (select-window (get-buffer-window (marker-buffer pos)))
10663     (goto-char pos)
10664     (move-marker pos nil)
10665     (message "Formula editing aborted without installing changes")))
10667 (defun org-table-fedit-lisp-indent ()
10668   "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10669   (interactive)
10670   (let ((pos (point)) beg end ind)
10671     (beginning-of-line 1)
10672     (cond
10673      ((looking-at "[ \t]")
10674       (goto-char pos)
10675       (call-interactively 'lisp-indent-line))
10676      ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10677      ((not (fboundp 'pp-buffer))
10678       (error "Cannot pretty-print.  Command `pp-buffer' is not available."))
10679      ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10680       (goto-char (- (match-end 0) 2))
10681       (setq beg (point))
10682       (setq ind (make-string (current-column) ?\ ))
10683       (condition-case nil (forward-sexp 1)
10684         (error
10685          (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10686       (setq end (point))
10687       (save-restriction
10688         (narrow-to-region beg end)
10689         (if (eq last-command this-command)
10690             (progn
10691               (goto-char (point-min))
10692               (setq this-command nil)
10693               (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10694                 (replace-match " ")))
10695           (pp-buffer)
10696           (untabify (point-min) (point-max))
10697           (goto-char (1+ (point-min)))
10698           (while (re-search-forward "^." nil t)
10699             (beginning-of-line 1)
10700             (insert ind))
10701           (goto-char (point-max))
10702           (backward-delete-char 1)))
10703       (goto-char beg))
10704      (t nil))))
10706 (defvar org-show-positions nil)
10708 (defun org-table-show-reference (&optional local)
10709   "Show the location/value of the $ expression at point."
10710   (interactive)
10711   (org-table-remove-rectangle-highlight)
10712   (catch 'exit
10713     (let ((pos (if local (point) org-pos))
10714           (face2 'highlight)
10715           (org-inhibit-highlight-removal t)
10716           (win (selected-window))
10717           (org-show-positions nil)
10718           var name e what match dest)
10719       (if local (org-table-get-specials))
10720       (setq what (cond
10721                   ((or (org-at-regexp-p org-table-range-regexp2)
10722                        (org-at-regexp-p org-table-translate-regexp)
10723                        (org-at-regexp-p org-table-range-regexp))
10724                    (setq match
10725                          (save-match-data
10726                            (org-table-convert-refs-to-rc (match-string 0))))
10727                    'range)
10728                   ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10729                   ((org-at-regexp-p "\\$[0-9]+") 'column)
10730                   ((not local) nil)
10731                   (t (error "No reference at point")))
10732             match (and what (or match (match-string 0))))
10733       (when (and  match (not (equal (match-beginning 0) (point-at-bol))))
10734         (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10735                                          'secondary-selection))
10736       (org-add-hook 'before-change-functions
10737                     'org-table-remove-rectangle-highlight)
10738       (if (eq what 'name) (setq var (substring match 1)))
10739       (when (eq what 'range)
10740         (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10741         (setq match (org-table-formula-substitute-names match)))
10742       (unless local
10743         (save-excursion
10744           (end-of-line 1)
10745           (re-search-backward "^\\S-" nil t)
10746           (beginning-of-line 1)
10747           (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10748             (setq dest
10749                   (save-match-data
10750                     (org-table-convert-refs-to-rc (match-string 1))))
10751             (org-table-add-rectangle-overlay
10752              (match-beginning 1) (match-end 1) face2))))
10753       (if (and (markerp pos) (marker-buffer pos))
10754           (if (get-buffer-window (marker-buffer pos))
10755               (select-window (get-buffer-window (marker-buffer pos)))
10756             (org-switch-to-buffer-other-window (get-buffer-window
10757                                             (marker-buffer pos)))))
10758       (goto-char pos)
10759       (org-table-force-dataline)
10760       (when dest
10761         (setq name (substring dest 1))
10762         (cond
10763          ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10764           (setq e (assoc name org-table-named-field-locations))
10765           (goto-line (nth 1 e))
10766           (org-table-goto-column (nth 2 e)))
10767          ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10768           (let ((l (string-to-number (match-string 1 dest)))
10769                 (c (string-to-number (match-string 2 dest))))
10770             (goto-line (aref org-table-dlines l))
10771             (org-table-goto-column c)))
10772          (t (org-table-goto-column (string-to-number name))))
10773         (move-marker pos (point))
10774         (org-table-highlight-rectangle nil nil face2))
10775       (cond
10776        ((equal dest match))
10777        ((not match))
10778        ((eq what 'range)
10779         (condition-case nil
10780             (save-excursion
10781               (org-table-get-range match nil nil 'highlight))
10782           (error nil)))
10783        ((setq e (assoc var org-table-named-field-locations))
10784         (goto-line (nth 1 e))
10785         (org-table-goto-column (nth 2 e))
10786         (org-table-highlight-rectangle (point) (point))
10787         (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10788        ((setq e (assoc var org-table-column-names))
10789         (org-table-goto-column (string-to-number (cdr e)))
10790         (org-table-highlight-rectangle (point) (point))
10791         (goto-char (org-table-begin))
10792         (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10793                                (org-table-end) t)
10794             (progn
10795               (goto-char (match-beginning 1))
10796               (org-table-highlight-rectangle)
10797               (message "Named column (column %s)" (cdr e)))
10798           (error "Column name not found")))
10799        ((eq what 'column)
10800         ;; column number
10801         (org-table-goto-column (string-to-number (substring match 1)))
10802         (org-table-highlight-rectangle (point) (point))
10803         (message "Column %s" (substring match 1)))
10804        ((setq e (assoc var org-table-local-parameters))
10805         (goto-char (org-table-begin))
10806         (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10807             (progn
10808               (goto-char (match-beginning 1))
10809               (org-table-highlight-rectangle)
10810               (message "Local parameter."))
10811           (error "Parameter not found")))
10812        (t
10813         (cond
10814          ((not var) (error "No reference at point"))
10815          ((setq e (assoc var org-table-formula-constants-local))
10816           (message "Local Constant: $%s=%s in #+CONSTANTS line."
10817                    var (cdr e)))
10818          ((setq e (assoc var org-table-formula-constants))
10819           (message "Constant: $%s=%s in `org-table-formula-constants'."
10820                    var (cdr e)))
10821          ((setq e (and (fboundp 'constants-get) (constants-get var)))
10822           (message "Constant: $%s=%s, from `constants.el'%s."
10823                    var e (format " (%s units)" constants-unit-system)))
10824          (t (error "Undefined name $%s" var)))))
10825       (goto-char pos)
10826       (when (and org-show-positions
10827                  (not (memq this-command '(org-table-fedit-scroll
10828                                            org-table-fedit-scroll-down))))
10829         (push pos org-show-positions)
10830         (push org-table-current-begin-pos org-show-positions)
10831         (let ((min (apply 'min org-show-positions))
10832               (max (apply 'max org-show-positions)))
10833           (goto-char min) (recenter 0)
10834           (goto-char max)
10835           (or (pos-visible-in-window-p max) (recenter -1))))
10836       (select-window win))))
10838 (defun org-table-force-dataline ()
10839   "Make sure the cursor is in a dataline in a table."
10840   (unless (save-excursion
10841             (beginning-of-line 1)
10842             (looking-at org-table-dataline-regexp))
10843     (let* ((re org-table-dataline-regexp)
10844            (p1 (save-excursion (re-search-forward re nil 'move)))
10845            (p2 (save-excursion (re-search-backward re nil 'move))))
10846       (cond ((and p1 p2)
10847              (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10848                             p1 p2)))
10849             ((or p1 p2) (goto-char (or p1 p2)))
10850             (t (error "No table dataline around here"))))))
10852 (defun org-table-fedit-line-up ()
10853   "Move cursor one line up in the window showing the table."
10854   (interactive)
10855   (org-table-fedit-move 'previous-line))
10857 (defun org-table-fedit-line-down ()
10858   "Move cursor one line down in the window showing the table."
10859   (interactive)
10860   (org-table-fedit-move 'next-line))
10862 (defun org-table-fedit-move (command)
10863   "Move the cursor in the window shoinw the table.
10864 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
10865   (let ((org-table-allow-automatic-line-recalculation nil)
10866         (pos org-pos) (win (selected-window)) p)
10867     (select-window (get-buffer-window (marker-buffer org-pos)))
10868     (setq p (point))
10869     (call-interactively command)
10870     (while (and (org-at-table-p)
10871                 (org-at-table-hline-p))
10872       (call-interactively command))
10873     (or (org-at-table-p) (goto-char p))
10874     (move-marker pos (point))
10875     (select-window win)))
10877 (defun org-table-fedit-scroll (N)
10878   (interactive "p")
10879   (let ((other-window-scroll-buffer (marker-buffer org-pos)))
10880     (scroll-other-window N)))
10882 (defun org-table-fedit-scroll-down (N)
10883   (interactive "p")
10884   (org-table-fedit-scroll (- N)))
10886 (defvar org-table-rectangle-overlays nil)
10888 (defun org-table-add-rectangle-overlay (beg end &optional face)
10889   "Add a new overlay."
10890   (let ((ov (org-make-overlay beg end)))
10891     (org-overlay-put ov 'face (or face 'secondary-selection))
10892     (push ov org-table-rectangle-overlays)))
10894 (defun org-table-highlight-rectangle (&optional beg end face)
10895   "Highlight rectangular region in a table."
10896   (setq beg (or beg (point)) end (or end (point)))
10897   (let ((b (min beg end))
10898         (e (max beg end))
10899         l1 c1 l2 c2 tmp)
10900     (and (boundp 'org-show-positions)
10901          (setq org-show-positions (cons b (cons e org-show-positions))))
10902     (goto-char (min beg end))
10903     (setq l1 (org-current-line)
10904           c1 (org-table-current-column))
10905     (goto-char (max beg end))
10906     (setq l2 (org-current-line)
10907           c2 (org-table-current-column))
10908     (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
10909     (goto-line l1)
10910     (beginning-of-line 1)
10911     (loop for line from l1 to l2 do
10912           (when (looking-at org-table-dataline-regexp)
10913             (org-table-goto-column c1)
10914             (skip-chars-backward "^|\n") (setq beg (point))
10915             (org-table-goto-column c2)
10916             (skip-chars-forward "^|\n")  (setq end (point))
10917             (org-table-add-rectangle-overlay beg end face))
10918           (beginning-of-line 2))
10919     (goto-char b))
10920   (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
10922 (defun org-table-remove-rectangle-highlight (&rest ignore)
10923   "Remove the rectangle overlays."
10924   (unless org-inhibit-highlight-removal
10925     (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
10926     (mapc 'org-delete-overlay org-table-rectangle-overlays)
10927     (setq org-table-rectangle-overlays nil)))
10929 (defvar org-table-coordinate-overlays nil
10930   "Collects the cooordinate grid overlays, so that they can be removed.")
10931 (make-variable-buffer-local 'org-table-coordinate-overlays)
10933 (defun org-table-overlay-coordinates ()
10934   "Add overlays to the table at point, to show row/column coordinates."
10935   (interactive)
10936   (mapc 'org-delete-overlay org-table-coordinate-overlays)
10937   (setq org-table-coordinate-overlays nil)
10938   (save-excursion
10939     (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
10940       (goto-char (org-table-begin))
10941       (while (org-at-table-p)
10942         (setq eol (point-at-eol))
10943         (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
10944         (push ov org-table-coordinate-overlays)
10945         (setq hline (looking-at org-table-hline-regexp))
10946         (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
10947                     (format "%4d" (setq id (1+ id)))))
10948         (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
10949         (when hline
10950           (setq ic 0)
10951           (while (re-search-forward "[+|]\\(-+\\)" eol t)
10952             (setq beg (1+ (match-beginning 0))
10953                   ic (1+ ic)
10954                   s1 (concat "$" (int-to-string ic))
10955                   s2 (org-number-to-letters ic)
10956                   str (if (eq org-table-use-standard-references t) s2 s1))
10957             (setq ov (org-make-overlay beg (+ beg (length str))))
10958             (push ov org-table-coordinate-overlays)
10959             (org-overlay-display ov str 'org-special-keyword 'evaporate)))
10960         (beginning-of-line 2)))))
10962 (defun org-table-toggle-coordinate-overlays ()
10963   "Toggle the display of Row/Column numbers in tables."
10964   (interactive)
10965   (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
10966   (message "Row/Column number display turned %s"
10967            (if org-table-overlay-coordinates "on" "off"))
10968   (if (and (org-at-table-p) org-table-overlay-coordinates)
10969       (org-table-align))
10970   (unless org-table-overlay-coordinates
10971     (mapc 'org-delete-overlay org-table-coordinate-overlays)
10972     (setq org-table-coordinate-overlays nil)))
10974 (defun org-table-toggle-formula-debugger ()
10975   "Toggle the formula debugger in tables."
10976   (interactive)
10977   (setq org-table-formula-debug (not org-table-formula-debug))
10978   (message "Formula debugging has been turned %s"
10979            (if org-table-formula-debug "on" "off")))
10981 ;;; The orgtbl minor mode
10983 ;; Define a minor mode which can be used in other modes in order to
10984 ;; integrate the org-mode table editor.
10986 ;; This is really a hack, because the org-mode table editor uses several
10987 ;; keys which normally belong to the major mode, for example the TAB and
10988 ;; RET keys.  Here is how it works: The minor mode defines all the keys
10989 ;; necessary to operate the table editor, but wraps the commands into a
10990 ;; function which tests if the cursor is currently inside a table.  If that
10991 ;; is the case, the table editor command is executed.  However, when any of
10992 ;; those keys is used outside a table, the function uses `key-binding' to
10993 ;; look up if the key has an associated command in another currently active
10994 ;; keymap (minor modes, major mode, global), and executes that command.
10995 ;; There might be problems if any of the keys used by the table editor is
10996 ;; otherwise used as a prefix key.
10998 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10999 ;; likewise the binding for RET can be return or \C-m.  Orgtbl-mode
11000 ;; addresses this by checking explicitly for both bindings.
11002 ;; The optimized version (see variable `orgtbl-optimized') takes over
11003 ;; all keys which are bound to `self-insert-command' in the *global map*.
11004 ;; Some modes bind other commands to simple characters, for example
11005 ;; AUCTeX binds the double quote to `Tex-insert-quote'.  With orgtbl-mode
11006 ;; active, this binding is ignored inside tables and replaced with a
11007 ;; modified self-insert.
11009 (defvar orgtbl-mode nil
11010   "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11011 table editor in arbitrary modes.")
11012 (make-variable-buffer-local 'orgtbl-mode)
11014 (defvar orgtbl-mode-map (make-keymap)
11015   "Keymap for `orgtbl-mode'.")
11017 ;;;###autoload
11018 (defun turn-on-orgtbl ()
11019   "Unconditionally turn on `orgtbl-mode'."
11020   (orgtbl-mode 1))
11022 (defvar org-old-auto-fill-inhibit-regexp nil
11023   "Local variable used by `orgtbl-mode'")
11025 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11026   "Matches a line belonging to an orgtbl.")
11028 (defconst orgtbl-extra-font-lock-keywords
11029   (list (list (concat "^" orgtbl-line-start-regexp ".*")
11030               0 (quote 'org-table) 'prepend))
11031   "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11033 ;;;###autoload
11034 (defun orgtbl-mode (&optional arg)
11035   "The `org-mode' table editor as a minor mode for use in other modes."
11036   (interactive)
11037   (if (org-mode-p)
11038       ;; Exit without error, in case some hook functions calls this
11039       ;; by accident in org-mode.
11040       (message "Orgtbl-mode is not useful in org-mode, command ignored")
11041     (setq orgtbl-mode
11042           (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11043     (if orgtbl-mode
11044         (progn
11045           (and (orgtbl-setup) (defun orgtbl-setup () nil))
11046           ;; Make sure we are first in minor-mode-map-alist
11047           (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11048             (and c (setq minor-mode-map-alist
11049                          (cons c (delq c minor-mode-map-alist)))))
11050           (org-set-local (quote org-table-may-need-update) t)
11051           (org-add-hook 'before-change-functions 'org-before-change-function
11052                         nil 'local)
11053           (org-set-local 'org-old-auto-fill-inhibit-regexp
11054                          auto-fill-inhibit-regexp)
11055           (org-set-local 'auto-fill-inhibit-regexp
11056                          (if auto-fill-inhibit-regexp
11057                              (concat orgtbl-line-start-regexp "\\|"
11058                                      auto-fill-inhibit-regexp)
11059                            orgtbl-line-start-regexp))
11060           (org-add-to-invisibility-spec '(org-cwidth))
11061           (when (fboundp 'font-lock-add-keywords)
11062             (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11063             (org-restart-font-lock))
11064           (easy-menu-add orgtbl-mode-menu)
11065           (run-hooks 'orgtbl-mode-hook))
11066       (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11067       (org-cleanup-narrow-column-properties)
11068       (org-remove-from-invisibility-spec '(org-cwidth))
11069       (remove-hook 'before-change-functions 'org-before-change-function t)
11070       (when (fboundp 'font-lock-remove-keywords)
11071         (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11072         (org-restart-font-lock))
11073       (easy-menu-remove orgtbl-mode-menu)
11074       (force-mode-line-update 'all))))
11076 (defun org-cleanup-narrow-column-properties ()
11077   "Remove all properties related to narrow-column invisibility."
11078   (let ((s 1))
11079     (while (setq s (text-property-any s (point-max)
11080                                       'display org-narrow-column-arrow))
11081       (remove-text-properties s (1+ s) '(display t)))
11082     (setq s 1)
11083     (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11084       (remove-text-properties s (1+ s) '(org-cwidth t)))
11085     (setq s 1)
11086     (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11087       (remove-text-properties s (1+ s) '(invisible t)))))
11089 ;; Install it as a minor mode.
11090 (put 'orgtbl-mode :included t)
11091 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11092 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11094 (defun orgtbl-make-binding (fun n &rest keys)
11095   "Create a function for binding in the table minor mode.
11096 FUN is the command to call inside a table.  N is used to create a unique
11097 command name.  KEYS are keys that should be checked in for a command
11098 to execute outside of tables."
11099   (eval
11100    (list 'defun
11101          (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11102          '(arg)
11103          (concat "In tables, run `" (symbol-name fun) "'.\n"
11104                  "Outside of tables, run the binding of `"
11105                  (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11106                  "'.")
11107          '(interactive "p")
11108          (list 'if
11109                '(org-at-table-p)
11110                (list 'call-interactively (list 'quote fun))
11111                (list 'let '(orgtbl-mode)
11112                      (list 'call-interactively
11113                            (append '(or)
11114                                    (mapcar (lambda (k)
11115                                              (list 'key-binding k))
11116                                            keys)
11117                                    '('orgtbl-error))))))))
11119 (defun orgtbl-error ()
11120   "Error when there is no default binding for a table key."
11121   (interactive)
11122   (error "This key has no function outside tables"))
11124 (defun orgtbl-setup ()
11125   "Setup orgtbl keymaps."
11126   (let ((nfunc 0)
11127         (bindings
11128          (list
11129           '([(meta shift left)]  org-table-delete-column)
11130           '([(meta left)]        org-table-move-column-left)
11131           '([(meta right)]       org-table-move-column-right)
11132           '([(meta shift right)] org-table-insert-column)
11133           '([(meta shift up)]    org-table-kill-row)
11134           '([(meta shift down)]  org-table-insert-row)
11135           '([(meta up)]          org-table-move-row-up)
11136           '([(meta down)]        org-table-move-row-down)
11137           '("\C-c\C-w"           org-table-cut-region)
11138           '("\C-c\M-w"           org-table-copy-region)
11139           '("\C-c\C-y"           org-table-paste-rectangle)
11140           '("\C-c-"              org-table-insert-hline)
11141           '("\C-c}"              org-table-toggle-coordinate-overlays)
11142           '("\C-c{"              org-table-toggle-formula-debugger)
11143           '("\C-m"               org-table-next-row)
11144           '([(shift return)]     org-table-copy-down)
11145           '("\C-c\C-q"           org-table-wrap-region)
11146           '("\C-c?"              org-table-field-info)
11147           '("\C-c "              org-table-blank-field)
11148           '("\C-c+"              org-table-sum)
11149           '("\C-c="              org-table-eval-formula)
11150           '("\C-c'"              org-table-edit-formulas)
11151           '("\C-c`"              org-table-edit-field)
11152           '("\C-c*"              org-table-recalculate)
11153           '("\C-c|"              org-table-create-or-convert-from-region)
11154           '("\C-c^"              org-table-sort-lines)
11155           '([(control ?#)]       org-table-rotate-recalc-marks)))
11156         elt key fun cmd)
11157     (while (setq elt (pop bindings))
11158       (setq nfunc (1+ nfunc))
11159       (setq key (org-key (car elt))
11160             fun (nth 1 elt)
11161             cmd (orgtbl-make-binding fun nfunc key))
11162       (org-defkey orgtbl-mode-map key cmd))
11164     ;; Special treatment needed for TAB and RET
11165     (org-defkey orgtbl-mode-map [(return)]
11166       (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11167     (org-defkey orgtbl-mode-map "\C-m"
11168       (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11170     (org-defkey orgtbl-mode-map [(tab)]
11171       (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11172     (org-defkey orgtbl-mode-map "\C-i"
11173       (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11175     (org-defkey orgtbl-mode-map [(shift tab)]
11176       (orgtbl-make-binding 'org-table-previous-field 104
11177                            [(shift tab)] [(tab)] "\C-i"))
11179     (org-defkey orgtbl-mode-map "\M-\C-m"
11180       (orgtbl-make-binding 'org-table-wrap-region 105
11181                            "\M-\C-m" [(meta return)]))
11182     (org-defkey orgtbl-mode-map [(meta return)]
11183       (orgtbl-make-binding 'org-table-wrap-region 106
11184                            [(meta return)] "\M-\C-m"))
11186     (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11187     (when orgtbl-optimized
11188       ;; If the user wants maximum table support, we need to hijack
11189       ;; some standard editing functions
11190       (org-remap orgtbl-mode-map
11191                  'self-insert-command 'orgtbl-self-insert-command
11192                  'delete-char 'org-delete-char
11193                  'delete-backward-char 'org-delete-backward-char)
11194       (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11195     (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11196       '("OrgTbl"
11197         ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11198         ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11199         ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11200         ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11201         "--"
11202         ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11203         ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11204         ["Copy Field from Above"
11205          org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11206         "--"
11207         ("Column"
11208          ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11209          ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11210          ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11211          ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11212         ("Row"
11213          ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11214          ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11215          ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11216          ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11217          ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
11218          "--"
11219          ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11220         ("Rectangle"
11221          ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11222          ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11223          ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11224          ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11225         "--"
11226         ("Radio tables"
11227          ["Insert table template" orgtbl-insert-radio-table
11228           (assq major-mode orgtbl-radio-table-templates)]
11229          ["Comment/uncomment table" orgtbl-toggle-comment t])
11230         "--"
11231         ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11232         ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11233         ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11234         ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11235         ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11236         ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11237         ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11238         ["Sum Column/Rectangle" org-table-sum
11239          :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11240         ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11241         ["Debug Formulas"
11242          org-table-toggle-formula-debugger :active (org-at-table-p)
11243          :keys "C-c {"
11244          :style toggle :selected org-table-formula-debug]
11245         ["Show Col/Row Numbers"
11246          org-table-toggle-coordinate-overlays :active (org-at-table-p)
11247          :keys "C-c }"
11248          :style toggle :selected org-table-overlay-coordinates]
11249         ))
11250     t))
11252 (defun orgtbl-ctrl-c-ctrl-c (arg)
11253   "If the cursor is inside a table, realign the table.
11254 It it is a table to be sent away to a receiver, do it.
11255 With prefix arg, also recompute table."
11256   (interactive "P")
11257   (let ((pos (point)) action)
11258     (save-excursion
11259       (beginning-of-line 1)
11260       (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11261                          ((looking-at "[ \t]*|") pos)
11262                          ((looking-at "#\\+TBLFM:") 'recalc))))
11263     (cond
11264      ((integerp action)
11265       (goto-char action)
11266       (org-table-maybe-eval-formula)
11267       (if arg
11268           (call-interactively 'org-table-recalculate)
11269         (org-table-maybe-recalculate-line))
11270       (call-interactively 'org-table-align)
11271       (orgtbl-send-table 'maybe))
11272      ((eq action 'recalc)
11273       (save-excursion
11274         (beginning-of-line 1)
11275         (skip-chars-backward " \r\n\t")
11276         (if (org-at-table-p)
11277             (org-call-with-arg 'org-table-recalculate t))))
11278      (t (let (orgtbl-mode)
11279           (call-interactively (key-binding "\C-c\C-c")))))))
11281 (defun orgtbl-tab (arg)
11282   "Justification and field motion for `orgtbl-mode'."
11283   (interactive "P")
11284   (if arg (org-table-edit-field t)
11285     (org-table-justify-field-maybe)
11286     (org-table-next-field)))
11288 (defun orgtbl-ret ()
11289   "Justification and field motion for `orgtbl-mode'."
11290   (interactive)
11291   (org-table-justify-field-maybe)
11292   (org-table-next-row))
11294 (defun orgtbl-self-insert-command (N)
11295   "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11296 If the cursor is in a table looking at whitespace, the whitespace is
11297 overwritten, and the table is not marked as requiring realignment."
11298   (interactive "p")
11299   (if (and (org-at-table-p)
11300            (or
11301             (and org-table-auto-blank-field
11302                  (member last-command
11303                          '(orgtbl-hijacker-command-100
11304                            orgtbl-hijacker-command-101
11305                            orgtbl-hijacker-command-102
11306                            orgtbl-hijacker-command-103
11307                            orgtbl-hijacker-command-104
11308                            orgtbl-hijacker-command-105))
11309                  (org-table-blank-field))
11310             t)
11311            (eq N 1)
11312            (looking-at "[^|\n]*  +|"))
11313       (let (org-table-may-need-update)
11314         (goto-char (1- (match-end 0)))
11315         (delete-backward-char 1)
11316         (goto-char (match-beginning 0))
11317         (self-insert-command N))
11318     (setq org-table-may-need-update t)
11319     (let (orgtbl-mode)
11320       (call-interactively (key-binding (vector last-input-event))))))
11322 (defun org-force-self-insert (N)
11323   "Needed to enforce self-insert under remapping."
11324   (interactive "p")
11325   (self-insert-command N))
11327 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11328   "Regula expression matching exponentials as produced by calc.")
11330 (defvar org-table-clean-did-remove-column nil)
11332 (defun orgtbl-export (table target)
11333   (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11334         (lines (org-split-string table "[ \t]*\n[ \t]*"))
11335         org-table-last-alignment org-table-last-column-widths
11336         maxcol column)
11337     (if (not (fboundp func))
11338         (error "Cannot export orgtbl table to %s" target))
11339     (setq lines (org-table-clean-before-export lines))
11340     (setq table
11341           (mapcar
11342            (lambda (x)
11343              (if (string-match org-table-hline-regexp x)
11344                  'hline
11345                (org-split-string (org-trim x) "\\s-*|\\s-*")))
11346            lines))
11347     (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11348                                      table)))
11349     (loop for i from (1- maxcol) downto 0 do
11350           (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11351           (setq column (delq nil column))
11352           (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11353           (push (> (/ (apply '+ (mapcar (lambda (x) (if (string-match org-table-number-regexp x) 1 0)) column)) maxcol) org-table-number-fraction) org-table-last-alignment))
11354     (funcall func table nil)))
11356 (defun orgtbl-send-table (&optional maybe)
11357   "Send a tranformed version of this table to the receiver position.
11358 With argument MAYBE, fail quietly if no transformation is defined for
11359 this table."
11360   (interactive)
11361   (catch 'exit
11362     (unless (org-at-table-p) (error "Not at a table"))
11363     ;; when non-interactive, we assume align has just happened.
11364     (when (interactive-p) (org-table-align))
11365     (save-excursion
11366       (goto-char (org-table-begin))
11367       (beginning-of-line 0)
11368       (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11369         (if maybe
11370             (throw 'exit nil)
11371           (error "Don't know how to transform this table."))))
11372     (let* ((name (match-string 1))
11373            beg
11374            (transform (intern (match-string 2)))
11375            (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11376            (skip (plist-get params :skip))
11377            (skipcols (plist-get params :skipcols))
11378            (txt (buffer-substring-no-properties
11379                  (org-table-begin) (org-table-end)))
11380            (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11381            (lines (org-table-clean-before-export lines))
11382            (i0 (if org-table-clean-did-remove-column 2 1))
11383            (table (mapcar
11384                    (lambda (x)
11385                      (if (string-match org-table-hline-regexp x)
11386                          'hline
11387                        (org-remove-by-index
11388                         (org-split-string (org-trim x) "\\s-*|\\s-*")
11389                         skipcols i0)))
11390                    lines))
11391            (fun (if (= i0 2) 'cdr 'identity))
11392            (org-table-last-alignment
11393             (org-remove-by-index (funcall fun org-table-last-alignment)
11394                                  skipcols i0))
11395            (org-table-last-column-widths
11396             (org-remove-by-index (funcall fun org-table-last-column-widths)
11397                                  skipcols i0)))
11399       (unless (fboundp transform)
11400         (error "No such transformation function %s" transform))
11401       (setq txt (funcall transform table params))
11402       ;; Find the insertion place
11403       (save-excursion
11404         (goto-char (point-min))
11405         (unless (re-search-forward
11406                  (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11407           (error "Don't know where to insert translated table"))
11408         (goto-char (match-beginning 0))
11409         (beginning-of-line 2)
11410         (setq beg (point))
11411         (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11412           (error "Cannot find end of insertion region"))
11413         (beginning-of-line 1)
11414         (delete-region beg (point))
11415         (goto-char beg)
11416         (insert txt "\n"))
11417       (message "Table converted and installed at receiver location"))))
11419 (defun org-remove-by-index (list indices &optional i0)
11420   "Remove the elements in LIST with indices in INDICES.
11421 First element has index 0, or I0 if given."
11422   (if (not indices)
11423       list
11424     (if (integerp indices) (setq indices (list indices)))
11425     (setq i0 (1- (or i0 0)))
11426     (delq :rm (mapcar (lambda (x)
11427                         (setq i0 (1+ i0))
11428                         (if (memq i0 indices) :rm x))
11429                       list))))
11431 (defun orgtbl-toggle-comment ()
11432   "Comment or uncomment the orgtbl at point."
11433   (interactive)
11434   (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11435          (re2 (concat "^" orgtbl-line-start-regexp))
11436          (commented (save-excursion (beginning-of-line 1)
11437                              (cond ((looking-at re1) t)
11438                                    ((looking-at re2) nil)
11439                                    (t (error "Not at an org table")))))
11440          (re (if commented re1 re2))
11441          beg end)
11442     (save-excursion
11443       (beginning-of-line 1)
11444       (while (looking-at re) (beginning-of-line 0))
11445       (beginning-of-line 2)
11446       (setq beg (point))
11447       (while (looking-at re) (beginning-of-line 2))
11448       (setq end (point)))
11449     (comment-region beg end (if commented '(4) nil))))
11451 (defun orgtbl-insert-radio-table ()
11452   "Insert a radio table template appropriate for this major mode."
11453   (interactive)
11454   (let* ((e (assq major-mode orgtbl-radio-table-templates))
11455          (txt (nth 1 e))
11456          name pos)
11457     (unless e (error "No radio table setup defined for %s" major-mode))
11458     (setq name (read-string "Table name: "))
11459     (while (string-match "%n" txt)
11460       (setq txt (replace-match name t t txt)))
11461     (or (bolp) (insert "\n"))
11462     (setq pos (point))
11463     (insert txt)
11464     (goto-char pos)))
11466 (defun org-get-param (params header i sym &optional hsym)
11467   "Get parameter value for symbol SYM.
11468 If this is a header line, actually get the value for the symbol with an
11469 additional \"h\" inserted after the colon.
11470 If the value is a protperty list, get the element for the current column.
11471 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11472   (let ((val (plist-get params sym)))
11473     (and hsym header (setq val (or (plist-get params hsym) val)))
11474     (if (consp val) (plist-get val i) val)))
11476 (defun orgtbl-to-generic (table params)
11477   "Convert the orgtbl-mode TABLE to some other format.
11478 This generic routine can be used for many standard cases.
11479 TABLE is a list, each entry either the symbol `hline' for a horizontal
11480 separator line, or a list of fields for that line.
11481 PARAMS is a property list of parameters that can influence the conversion.
11482 For the generic converter, some parameters are obligatory:  You need to
11483 specify either :lfmt, or all of (:lstart :lend :sep).  If you do not use
11484 :splice, you must have :tstart and :tend.
11486 Valid parameters are
11488 :tstart     String to start the table.  Ignored when :splice is t.
11489 :tend       String to end the table.  Ignored when :splice is t.
11491 :splice     When set to t, return only table body lines, don't wrap
11492             them into :tstart and :tend.  Default is nil.
11494 :hline      String to be inserted on horizontal separation lines.
11495             May be nil to ignore hlines.
11497 :lstart     String to start a new table line.
11498 :lend       String to end a table line
11499 :sep        Separator between two fields
11500 :lfmt       Format for entire line, with enough %s to capture all fields.
11501             If this is present, :lstart, :lend, and :sep are ignored.
11502 :fmt        A format to be used to wrap the field, should contain
11503             %s for the original field value.  For example, to wrap
11504             everything in dollars, you could use :fmt \"$%s$\".
11505             This may also be a property list with column numbers and
11506             formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11508 :hlstart :hlend :hlsep :hlfmt :hfmt
11509             Same as above, specific for the header lines in the table.
11510             All lines before the first hline are treated as header.
11511             If any of these is not present, the data line value is used.
11513 :efmt       Use this format to print numbers with exponentials.
11514             The format should have %s twice for inserting mantissa
11515             and exponent, for example \"%s\\\\times10^{%s}\".  This
11516             may also be a property list with column numbers and
11517             formats.  :fmt will still be applied after :efmt.
11519 In addition to this, the parameters :skip and :skipcols are always handled
11520 directly by `orgtbl-send-table'.  See manual."
11521   (interactive)
11522   (let* ((p params)
11523          (splicep (plist-get p :splice))
11524          (hline (plist-get p :hline))
11525          rtn line i fm efm lfmt h)
11527     ;; Do we have a header?
11528     (if (and (not splicep) (listp (car table)) (memq 'hline table))
11529         (setq h t))
11531     ;; Put header
11532     (unless splicep
11533       (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11535     ;; Now loop over all lines
11536     (while (setq line (pop table))
11537       (if (eq line 'hline)
11538           ;; A horizontal separator line
11539           (progn (if hline (push hline rtn))
11540                  (setq h nil))               ; no longer in header
11541         ;; A normal line.  Convert the fields, push line onto the result list
11542         (setq i 0)
11543         (setq line
11544               (mapcar
11545                (lambda (f)
11546                  (setq i (1+ i)
11547                        fm (org-get-param p h i :fmt :hfmt)
11548                        efm (org-get-param p h i :efmt))
11549                  (if (and efm (string-match orgtbl-exp-regexp f))
11550                      (setq f (format
11551                               efm (match-string 1 f) (match-string 2 f))))
11552                  (if fm (setq f (format fm f)))
11553                  f)
11554                line))
11555         (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11556             (push (apply 'format lfmt line) rtn)
11557           (push (concat
11558                  (org-get-param p h i :lstart :hlstart)
11559                  (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11560                  (org-get-param p h i :lend :hlend))
11561                 rtn))))
11563     (unless splicep
11564       (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11566     (mapconcat 'identity (nreverse rtn) "\n")))
11568 (defun orgtbl-to-latex (table params)
11569   "Convert the orgtbl-mode TABLE to LaTeX.
11570 TABLE is a list, each entry either the symbol `hline' for a horizontal
11571 separator line, or a list of fields for that line.
11572 PARAMS is a property list of parameters that can influence the conversion.
11573 Supports all parameters from `orgtbl-to-generic'.  Most important for
11574 LaTeX are:
11576 :splice    When set to t, return only table body lines, don't wrap
11577            them into a tabular environment.  Default is nil.
11579 :fmt       A format to be used to wrap the field, should contain %s for the
11580            original field value.  For example, to wrap everything in dollars,
11581            use :fmt \"$%s$\".  This may also be a property list with column
11582            numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11584 :efmt      Format for transforming numbers with exponentials.  The format
11585            should have %s twice for inserting mantissa and exponent, for
11586            example \"%s\\\\times10^{%s}\".  LaTeX default is \"%s\\\\,(%s)\".
11587            This may also be a property list with column numbers and formats.
11589 The general parameters :skip and :skipcols have already been applied when
11590 this function is called."
11591   (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11592                                org-table-last-alignment ""))
11593          (params2
11594           (list
11595            :tstart (concat "\\begin{tabular}{" alignment "}")
11596            :tend "\\end{tabular}"
11597            :lstart "" :lend " \\\\" :sep " & "
11598            :efmt "%s\\,(%s)" :hline "\\hline")))
11599     (orgtbl-to-generic table (org-combine-plists params2 params))))
11601 (defun orgtbl-to-html (table params)
11602   "Convert the orgtbl-mode TABLE to LaTeX.
11603 TABLE is a list, each entry either the symbol `hline' for a horizontal
11604 separator line, or a list of fields for that line.
11605 PARAMS is a property list of parameters that can influence the conversion.
11606 Currently this function recognizes the following parameters:
11608 :splice    When set to t, return only table body lines, don't wrap
11609            them into a <table> environment.  Default is nil.
11611 The general parameters :skip and :skipcols have already been applied when
11612 this function is called.  The function does *not* use `orgtbl-to-generic',
11613 so you cannot specify parameters for it."
11614   (let* ((splicep (plist-get params :splice))
11615          html)
11616     ;; Just call the formatter we already have
11617     ;; We need to make text lines for it, so put the fields back together.
11618     (setq html (org-format-org-table-html
11619                 (mapcar
11620                  (lambda (x)
11621                    (if (eq x 'hline)
11622                        "|----+----|"
11623                      (concat "| " (mapconcat 'identity x " | ") " |")))
11624                  table)
11625                 splicep))
11626     (if (string-match "\n+\\'" html)
11627         (setq html (replace-match "" t t html)))
11628     html))
11630 (defun orgtbl-to-texinfo (table params)
11631   "Convert the orgtbl-mode TABLE to TeXInfo.
11632 TABLE is a list, each entry either the symbol `hline' for a horizontal
11633 separator line, or a list of fields for that line.
11634 PARAMS is a property list of parameters that can influence the conversion.
11635 Supports all parameters from `orgtbl-to-generic'.  Most important for
11636 TeXInfo are:
11638 :splice nil/t      When set to t, return only table body lines, don't wrap
11639                    them into a multitable environment.  Default is nil.
11641 :fmt fmt           A format to be used to wrap the field, should contain
11642                    %s for the original field value.  For example, to wrap
11643                    everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11644                    This may also be a property list with column numbers and
11645                    formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11647 :cf \"f1 f2..\"    The column fractions for the table.  Bye default these
11648                    are computed automatically from the width of the columns
11649                    under org-mode.
11651 The general parameters :skip and :skipcols have already been applied when
11652 this function is called."
11653   (let* ((total (float (apply '+ org-table-last-column-widths)))
11654          (colfrac (or (plist-get params :cf)
11655                       (mapconcat
11656                        (lambda (x) (format "%.3f" (/ (float x) total)))
11657                        org-table-last-column-widths " ")))
11658          (params2
11659           (list
11660            :tstart (concat "@multitable @columnfractions " colfrac)
11661            :tend "@end multitable"
11662            :lstart "@item " :lend "" :sep " @tab "
11663            :hlstart "@headitem ")))
11664     (orgtbl-to-generic table (org-combine-plists params2 params))))
11666 ;;;; Link Stuff
11668 ;;; Link abbreviations
11670 (defun org-link-expand-abbrev (link)
11671   "Apply replacements as defined in `org-link-abbrev-alist."
11672   (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11673       (let* ((key (match-string 1 link))
11674              (as (or (assoc key org-link-abbrev-alist-local)
11675                      (assoc key org-link-abbrev-alist)))
11676              (tag (and (match-end 2) (match-string 3 link)))
11677              rpl)
11678         (if (not as)
11679             link
11680           (setq rpl (cdr as))
11681           (cond
11682            ((symbolp rpl) (funcall rpl tag))
11683            ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11684            (t (concat rpl tag)))))
11685     link))
11687 ;;; Storing and inserting links
11689 (defvar org-insert-link-history nil
11690   "Minibuffer history for links inserted with `org-insert-link'.")
11692 (defvar org-stored-links nil
11693   "Contains the links stored with `org-store-link'.")
11695 (defvar org-store-link-plist nil
11696   "Plist with info about the most recently link created with `org-store-link'.")
11698 (defvar org-link-protocols nil
11699   "Link protocols added to Org-mode using `org-add-link-type'.")
11701 (defvar org-store-link-functions nil
11702   "List of functions that are called to create and store a link.
11703 Each function will be called in turn until one returns a non-nil
11704 value.  Each function should check if it is responsible for creating
11705 this link (for example by looking at the major mode).
11706 If not, it must exit and return nil.
11707 If yes, it should return a non-nil value after a calling
11708 `org-store-link-props' with a list of properties and values.
11709 Special properties are:
11711 :type         The link prefix. like \"http\".  This must be given.
11712 :link         The link, like \"http://www.astro.uva.nl/~dominik\".
11713               This is obligatory as well.
11714 :description  Optional default description for the second pair
11715               of brackets in an Org-mode link.  The user can still change
11716               this when inserting this link into an Org-mode buffer.
11718 In addition to these, any additional properties can be specified
11719 and then used in remember templates.")
11721 (defun org-add-link-type (type &optional follow publish)
11722   "Add TYPE to the list of `org-link-types'.
11723 Re-compute all regular expressions depending on `org-link-types'
11724 FOLLOW and PUBLISH are two functions.  Both take the link path as
11725 an argument.
11726 FOLLOW should do whatever is necessary to follow the link, for example
11727 to find a file or display a mail message.
11729 PUBLISH takes the path and retuns the string that should be used when
11730 this document is published. FIMXE: This is actually not yet implemented."
11731   (add-to-list 'org-link-types type t)
11732   (org-make-link-regexps)
11733   (add-to-list 'org-link-protocols
11734                (list type follow publish)))
11736 (defun org-add-agenda-custom-command (entry)
11737   "Replace or add a command in `org-agenda-custom-commands'.
11738 This is mostly for hacking and trying a new command - once the command
11739 works you probably want to add it to `org-agenda-custom-commands' for good."
11740   (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11741     (if ass
11742         (setcdr ass (cdr entry))
11743       (push entry org-agenda-custom-commands))))
11745 ;;;###autoload
11746 (defun org-store-link (arg)
11747   "\\<org-mode-map>Store an org-link to the current location.
11748 This link can later be inserted into an org-buffer with
11749 \\[org-insert-link].
11750 For some link types, a prefix arg is interpreted:
11751 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11752 For file links, arg negates `org-context-in-file-links'."
11753   (interactive "P")
11754   (setq org-store-link-plist nil)  ; reset
11755   (let (link cpltxt desc description search txt)
11756     (cond
11758      ((run-hook-with-args-until-success 'org-store-link-functions)
11759       (setq link (plist-get org-store-link-plist :link)
11760             desc (or (plist-get org-store-link-plist :description) link)))
11762      ((eq major-mode 'bbdb-mode)
11763       (let ((name (bbdb-record-name (bbdb-current-record)))
11764             (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11765         (setq cpltxt (concat "bbdb:" (or name company))
11766               link (org-make-link cpltxt))
11767         (org-store-link-props :type "bbdb" :name name :company company)))
11769      ((eq major-mode 'Info-mode)
11770       (setq link (org-make-link "info:"
11771                                 (file-name-nondirectory Info-current-file)
11772                                 ":" Info-current-node))
11773       (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11774                            ":" Info-current-node))
11775       (org-store-link-props :type "info" :file Info-current-file
11776                             :node Info-current-node))
11778      ((eq major-mode 'calendar-mode)
11779       (let ((cd (calendar-cursor-to-date)))
11780         (setq link
11781               (format-time-string
11782                (car org-time-stamp-formats)
11783                (apply 'encode-time
11784                       (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11785                             nil nil nil))))
11786         (org-store-link-props :type "calendar" :date cd)))
11788      ((or (eq major-mode 'vm-summary-mode)
11789           (eq major-mode 'vm-presentation-mode))
11790       (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11791       (vm-follow-summary-cursor)
11792       (save-excursion
11793        (vm-select-folder-buffer)
11794        (let* ((message (car vm-message-pointer))
11795               (folder buffer-file-name)
11796               (subject (vm-su-subject message))
11797               (to (vm-get-header-contents message "To"))
11798               (from (vm-get-header-contents message "From"))
11799               (message-id (vm-su-message-id message)))
11800          (org-store-link-props :type "vm" :from from :to to :subject subject
11801                                :message-id message-id)
11802          (setq message-id (org-remove-angle-brackets message-id))
11803          (setq folder (abbreviate-file-name folder))
11804          (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11805                            folder)
11806              (setq folder (replace-match "" t t folder)))
11807          (setq cpltxt (org-email-link-description))
11808          (setq link (org-make-link "vm:" folder "#" message-id)))))
11810      ((eq major-mode 'wl-summary-mode)
11811       (let* ((msgnum (wl-summary-message-number))
11812              (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11813                                              msgnum 'message-id))
11814              (wl-message-entity
11815               (if (fboundp 'elmo-message-entity)
11816                   (elmo-message-entity
11817                    wl-summary-buffer-elmo-folder msgnum)
11818                 (elmo-msgdb-overview-get-entity
11819                  msgnum (wl-summary-buffer-msgdb))))
11820              (from (wl-summary-line-from))
11821              (to (car (elmo-message-entity-field wl-message-entity 'to)))
11822              (subject (let (wl-thr-indent-string wl-parent-message-entity)
11823                         (wl-summary-line-subject))))
11824         (org-store-link-props :type "wl" :from from :to to
11825                               :subject subject :message-id message-id)
11826         (setq message-id (org-remove-angle-brackets message-id))
11827         (setq cpltxt (org-email-link-description))
11828         (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11829                                   "#" message-id))))
11831      ((or (equal major-mode 'mh-folder-mode)
11832           (equal major-mode 'mh-show-mode))
11833       (let ((from (org-mhe-get-header "From:"))
11834             (to (org-mhe-get-header "To:"))
11835             (message-id (org-mhe-get-header "Message-Id:"))
11836             (subject (org-mhe-get-header "Subject:")))
11837         (org-store-link-props :type "mh" :from from :to to
11838                               :subject subject :message-id message-id)
11839         (setq cpltxt (org-email-link-description))
11840         (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11841                                   (org-remove-angle-brackets message-id)))))
11843      ((eq major-mode 'rmail-mode)
11844       (save-excursion
11845         (save-restriction
11846           (rmail-narrow-to-non-pruned-header)
11847           (let ((folder buffer-file-name)
11848                 (message-id (mail-fetch-field "message-id"))
11849                 (from (mail-fetch-field "from"))
11850                 (to (mail-fetch-field "to"))
11851                 (subject (mail-fetch-field "subject")))
11852             (org-store-link-props
11853              :type "rmail" :from from :to to
11854              :subject subject :message-id message-id)
11855             (setq message-id (org-remove-angle-brackets message-id))
11856             (setq cpltxt (org-email-link-description))
11857             (setq link (org-make-link "rmail:" folder "#" message-id))))))
11859      ((eq major-mode 'gnus-group-mode)
11860       (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
11861                           (gnus-group-group-name))         ; version
11862                          ((fboundp 'gnus-group-name)
11863                           (gnus-group-name))
11864                          (t "???"))))
11865         (unless group (error "Not on a group"))
11866         (org-store-link-props :type "gnus" :group group)
11867         (setq cpltxt (concat
11868                       (if (org-xor arg org-usenet-links-prefer-google)
11869                           "http://groups.google.com/groups?group="
11870                         "gnus:")
11871                       group)
11872               link (org-make-link cpltxt))))
11874      ((memq major-mode '(gnus-summary-mode gnus-article-mode))
11875       (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
11876       (let* ((group gnus-newsgroup-name)
11877              (article (gnus-summary-article-number))
11878              (header (gnus-summary-article-header article))
11879              (from (mail-header-from header))
11880              (message-id (mail-header-id header))
11881              (date (mail-header-date header))
11882              (subject (gnus-summary-subject-string)))
11883         (org-store-link-props :type "gnus" :from from :subject subject
11884                               :message-id message-id :group group)
11885         (setq cpltxt (org-email-link-description))
11886         (if (org-xor arg org-usenet-links-prefer-google)
11887             (setq link
11888                   (concat
11889                    cpltxt "\n  "
11890                    (format "http://groups.google.com/groups?as_umsgid=%s"
11891                            (org-fixup-message-id-for-http message-id))))
11892           (setq link (org-make-link "gnus:" group
11893                                     "#" (number-to-string article))))))
11895      ((eq major-mode 'w3-mode)
11896       (setq cpltxt (url-view-url t)
11897             link (org-make-link cpltxt))
11898       (org-store-link-props :type "w3" :url (url-view-url t)))
11900      ((eq major-mode 'w3m-mode)
11901       (setq cpltxt (or w3m-current-title w3m-current-url)
11902             link (org-make-link w3m-current-url))
11903       (org-store-link-props :type "w3m" :url (url-view-url t)))
11905      ((setq search (run-hook-with-args-until-success
11906                     'org-create-file-search-functions))
11907       (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
11908                          "::" search))
11909       (setq cpltxt (or description link)))
11911      ((eq major-mode 'image-mode)
11912       (setq cpltxt (concat "file:"
11913                            (abbreviate-file-name buffer-file-name))
11914             link (org-make-link cpltxt))
11915       (org-store-link-props :type "image" :file buffer-file-name))
11917      ((eq major-mode 'dired-mode)
11918       ;; link to the file in the current line
11919       (setq cpltxt (concat "file:"
11920                            (abbreviate-file-name
11921                             (expand-file-name
11922                              (dired-get-filename nil t))))
11923             link (org-make-link cpltxt)))
11925      ((and buffer-file-name (org-mode-p))
11926       ;; Just link to current headline
11927       (setq cpltxt (concat "file:"
11928                            (abbreviate-file-name buffer-file-name)))
11929       ;; Add a context search string
11930       (when (org-xor org-context-in-file-links arg)
11931         ;; Check if we are on a target
11932         (if (org-in-regexp "<<\\(.*?\\)>>")
11933             (setq cpltxt (concat cpltxt "::" (match-string 1)))
11934           (setq txt (cond
11935                      ((org-on-heading-p) nil)
11936                      ((org-region-active-p)
11937                       (buffer-substring (region-beginning) (region-end)))
11938                      (t (buffer-substring (point-at-bol) (point-at-eol)))))
11939           (when (or (null txt) (string-match "\\S-" txt))
11940             (setq cpltxt
11941                   (concat cpltxt "::" (org-make-org-heading-search-string txt))
11942                   desc "NONE"))))
11943       (if (string-match "::\\'" cpltxt)
11944           (setq cpltxt (substring cpltxt 0 -2)))
11945       (setq link (org-make-link cpltxt)))
11947      ((buffer-file-name (buffer-base-buffer))
11948       ;; Just link to this file here.
11949       (setq cpltxt (concat "file:"
11950                            (abbreviate-file-name
11951                             (buffer-file-name (buffer-base-buffer)))))
11952       ;; Add a context string
11953       (when (org-xor org-context-in-file-links arg)
11954         (setq txt (if (org-region-active-p)
11955                       (buffer-substring (region-beginning) (region-end))
11956                     (buffer-substring (point-at-bol) (point-at-eol))))
11957         ;; Only use search option if there is some text.
11958         (when (string-match "\\S-" txt)
11959           (setq cpltxt
11960                 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11961                 desc "NONE")))
11962       (setq link (org-make-link cpltxt)))
11964      ((interactive-p)
11965       (error "Cannot link to a buffer which is not visiting a file"))
11967      (t (setq link nil)))
11969     (if (consp link) (setq cpltxt (car link) link (cdr link)))
11970     (setq link (or link cpltxt)
11971           desc (or desc cpltxt))
11972     (if (equal desc "NONE") (setq desc nil))
11974     (if (and (interactive-p) link)
11975         (progn
11976           (setq org-stored-links
11977                 (cons (list link desc) org-stored-links))
11978           (message "Stored: %s" (or desc link)))
11979       (and link (org-make-link-string link desc)))))
11981 (defun org-store-link-props (&rest plist)
11982   "Store link properties, extract names and addresses."
11983   (let (x adr)
11984     (when (setq x (plist-get plist :from))
11985       (setq adr (mail-extract-address-components x))
11986       (plist-put plist :fromname (car adr))
11987       (plist-put plist :fromaddress (nth 1 adr)))
11988     (when (setq x (plist-get plist :to))
11989       (setq adr (mail-extract-address-components x))
11990       (plist-put plist :toname (car adr))
11991       (plist-put plist :toaddress (nth 1 adr))))
11992   (let ((from (plist-get plist :from))
11993         (to (plist-get plist :to)))
11994     (when (and from to org-from-is-user-regexp)
11995       (plist-put plist :fromto
11996                  (if (string-match org-from-is-user-regexp from)
11997                      (concat "to %t")
11998                    (concat "from %f")))))
11999   (setq org-store-link-plist plist))
12001 (defun org-email-link-description (&optional fmt)
12002   "Return the description part of an email link.
12003 This takes information from `org-store-link-plist' and formats it
12004 according to FMT (default from `org-email-link-description-format')."
12005   (setq fmt (or fmt org-email-link-description-format))
12006   (let* ((p org-store-link-plist)
12007          (to (plist-get p :toaddress))
12008          (from (plist-get p :fromaddress))
12009          (table
12010           (list
12011            (cons "%c" (plist-get p :fromto))
12012            (cons "%F" (plist-get p :from))
12013            (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12014            (cons "%T" (plist-get p :to))
12015            (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12016            (cons "%s" (plist-get p :subject))
12017            (cons "%m" (plist-get p :message-id)))))
12018     (when (string-match "%c" fmt)
12019       ;; Check if the user wrote this message
12020       (if (and org-from-is-user-regexp from to
12021                (save-match-data (string-match org-from-is-user-regexp from)))
12022           (setq fmt (replace-match "to %t" t t fmt))
12023         (setq fmt (replace-match "from %f" t t fmt))))
12024     (org-replace-escapes fmt table)))
12026 (defun org-make-org-heading-search-string (&optional string heading)
12027   "Make search string for STRING or current headline."
12028   (interactive)
12029   (let ((s (or string (org-get-heading))))
12030     (unless (and string (not heading))
12031       ;; We are using a headline, clean up garbage in there.
12032       (if (string-match org-todo-regexp s)
12033           (setq s (replace-match "" t t s)))
12034       (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12035           (setq s (replace-match "" t t s)))
12036       (setq s (org-trim s))
12037       (if (string-match (concat "^\\(" org-quote-string "\\|"
12038                                 org-comment-string "\\)") s)
12039           (setq s (replace-match "" t t s)))
12040       (while (string-match org-ts-regexp s)
12041         (setq s (replace-match "" t t s))))
12042     (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12043       (setq s (replace-match " " t t s)))
12044     (or string (setq s (concat "*" s)))  ; Add * for headlines
12045     (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12047 (defun org-make-link (&rest strings)
12048   "Concatenate STRINGS."
12049   (apply 'concat strings))
12051 (defun org-make-link-string (link &optional description)
12052   "Make a link with brackets, consisting of LINK and DESCRIPTION."
12053   (unless (string-match "\\S-" link)
12054     (error "Empty link"))
12055   (when (stringp description)
12056     ;; Remove brackets from the description, they are fatal.
12057     (while (string-match "\\[" description)
12058       (setq description (replace-match "{" t t description)))
12059     (while (string-match "\\]" description)
12060       (setq description (replace-match "}" t t description))))
12061   (when (equal (org-link-escape link) description)
12062     ;; No description needed, it is identical
12063     (setq description nil))
12064   (when (and (not description)
12065              (not (equal link (org-link-escape link))))
12066     (setq description link))
12067   (concat "[[" (org-link-escape link) "]"
12068           (if description (concat "[" description "]") "")
12069           "]"))
12071 (defconst org-link-escape-chars
12072   '((?\    . "%20")
12073     (?\[   . "%5B")
12074     (?\]   . "%5D")
12075     (?\340 . "%E0")  ; `a
12076     (?\342 . "%E2")  ; ^a
12077     (?\347 . "%E7")  ; ,c
12078     (?\350 . "%E8")  ; `e
12079     (?\351 . "%E9")  ; 'e
12080     (?\352 . "%EA")  ; ^e
12081     (?\356 . "%EE")  ; ^i
12082     (?\364 . "%F4")  ; ^o
12083     (?\371 . "%F9")  ; `u
12084     (?\373 . "%FB")  ; ^u
12085     (?\;   . "%3B")
12086     (??    . "%3F")
12087     (?=    . "%3D")
12088     (?+    . "%2B")
12089     )
12090   "Association list of escapes for some characters problematic in links.
12091 This is the list that is used for internal purposes.")
12093 (defconst org-link-escape-chars-browser
12094   '((?\  . "%20")) ; 32 for the SPC char
12095   "Association list of escapes for some characters problematic in links.
12096 This is the list that is used before handing over to the browser.")
12098 (defun org-link-escape (text &optional table)
12099   "Escape charaters in TEXT that are problematic for links."
12100   (setq table (or table org-link-escape-chars))
12101   (when text
12102     (let ((re (mapconcat (lambda (x) (regexp-quote
12103                                       (char-to-string (car x))))
12104                          table "\\|")))
12105       (while (string-match re text)
12106         (setq text
12107               (replace-match
12108                (cdr (assoc (string-to-char (match-string 0 text))
12109                            table))
12110                t t text)))
12111       text)))
12113 (defun org-link-unescape (text &optional table)
12114   "Reverse the action of `org-link-escape'."
12115   (setq table (or table org-link-escape-chars))
12116   (when text
12117     (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12118                          table "\\|")))
12119       (while (string-match re text)
12120         (setq text
12121               (replace-match
12122                (char-to-string (car (rassoc (match-string 0 text) table)))
12123                t t text)))
12124       text)))
12126 (defun org-xor (a b)
12127   "Exclusive or."
12128   (if a (not b) b))
12130 (defun org-get-header (header)
12131   "Find a header field in the current buffer."
12132   (save-excursion
12133     (goto-char (point-min))
12134     (let ((case-fold-search t) s)
12135       (cond
12136        ((eq header 'from)
12137         (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12138             (setq s (match-string 1)))
12139         (while (string-match "\"" s)
12140           (setq s (replace-match "" t t s)))
12141         (if (string-match "[<(].*" s)
12142             (setq s (replace-match "" t t s))))
12143        ((eq header 'message-id)
12144         (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12145             (setq s (match-string 1))))
12146        ((eq header 'subject)
12147         (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12148             (setq s (match-string 1)))))
12149       (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12150       (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12151       s)))
12154 (defun org-fixup-message-id-for-http (s)
12155   "Replace special characters in a message id, so it can be used in an http query."
12156   (while (string-match "<" s)
12157     (setq s (replace-match "%3C" t t s)))
12158   (while (string-match ">" s)
12159     (setq s (replace-match "%3E" t t s)))
12160   (while (string-match "@" s)
12161     (setq s (replace-match "%40" t t s)))
12162   s)
12164 ;;;###autoload
12165 (defun org-insert-link-global ()
12166   "Insert a link like Org-mode does.
12167 This command can be called in any mode to insert a link in Org-mode syntax."
12168   (interactive)
12169   (org-run-like-in-org-mode 'org-insert-link))
12171 (defun org-insert-link (&optional complete-file)
12172   "Insert a link.  At the prompt, enter the link.
12174 Completion can be used to select a link previously stored with
12175 `org-store-link'.  When the empty string is entered (i.e. if you just
12176 press RET at the prompt), the link defaults to the most recently
12177 stored link.  As SPC triggers completion in the minibuffer, you need to
12178 use M-SPC or C-q SPC to force the insertion of a space character.
12180 You will also be prompted for a description, and if one is given, it will
12181 be displayed in the buffer instead of the link.
12183 If there is already a link at point, this command will allow you to edit link
12184 and description parts.
12186 With a \\[universal-argument] prefix, prompts for a file to link to.  The file name can be
12187 selected using completion.  The path to the file will be relative to
12188 the current directory if the file is in the current directory or a
12189 subdirectory.  Otherwise, the link will be the absolute path as
12190 completed in the minibuffer (i.e. normally ~/path/to/file).
12192 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12193 is in the current directory or below.
12194 With three \\[universal-argument] prefixes, negate the meaning of
12195 `org-keep-stored-link-after-insertion'."
12196   (interactive "P")
12197   (let* ((wcf (current-window-configuration))
12198          (region (if (org-region-active-p)
12199                      (buffer-substring (region-beginning) (region-end))))
12200          (remove (and region (list (region-beginning) (region-end))))
12201          (desc region)
12202          tmphist ; byte-compile incorrectly complains about this
12203          link entry file)
12204     (cond
12205      ((org-in-regexp org-bracket-link-regexp 1)
12206       ;; We do have a link at point, and we are going to edit it.
12207       (setq remove (list (match-beginning 0) (match-end 0)))
12208       (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12209       (setq link (read-string "Link: "
12210                               (org-link-unescape
12211                                (org-match-string-no-properties 1)))))
12212      ((or (org-in-regexp org-angle-link-re)
12213           (org-in-regexp org-plain-link-re))
12214       ;; Convert to bracket link
12215       (setq remove (list (match-beginning 0) (match-end 0))
12216             link (read-string "Link: "
12217                               (org-remove-angle-brackets (match-string 0)))))
12218      ((equal complete-file '(4))
12219       ;; Completing read for file names.
12220       (setq file (read-file-name "File: "))
12221       (let ((pwd (file-name-as-directory (expand-file-name ".")))
12222             (pwd1 (file-name-as-directory (abbreviate-file-name
12223                                            (expand-file-name ".")))))
12224         (cond
12225          ((equal complete-file '(16))
12226           (setq link (org-make-link
12227                       "file:"
12228                       (abbreviate-file-name (expand-file-name file)))))
12229          ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12230           (setq link  (org-make-link "file:" (match-string 1 file))))
12231          ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12232                         (expand-file-name file))
12233           (setq link  (org-make-link
12234                        "file:" (match-string 1 (expand-file-name file)))))
12235          (t (setq link (org-make-link "file:" file))))))
12236      (t
12237       ;; Read link, with completion for stored links.
12238       (with-output-to-temp-buffer "*Org Links*"
12239         (princ "Insert a link.  Use TAB to complete valid link prefixes.\n")
12240         (when org-stored-links
12241           (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12242           (princ (mapconcat
12243                   (lambda (x)
12244                     (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12245                   (reverse org-stored-links) "\n"))))
12246       (let ((cw (selected-window)))
12247         (select-window (get-buffer-window "*Org Links*"))
12248         (shrink-window-if-larger-than-buffer)
12249         (setq truncate-lines t)
12250         (select-window cw))
12251       ;; Fake a link history, containing the stored links.
12252       (setq tmphist (append (mapcar 'car org-stored-links)
12253                             org-insert-link-history))
12254       (unwind-protect
12255           (setq link (org-completing-read
12256                       "Link: "
12257                       (append
12258                        (mapcar (lambda (x) (list (concat (car x) ":")))
12259                                (append org-link-abbrev-alist-local org-link-abbrev-alist))
12260                        (mapcar (lambda (x) (list (concat x ":")))
12261                                org-link-types))
12262                       nil nil nil
12263                       'tmphist
12264                       (or (car (car org-stored-links)))))
12265         (set-window-configuration wcf)
12266         (kill-buffer "*Org Links*"))
12267       (setq entry (assoc link org-stored-links))
12268       (or entry (push link org-insert-link-history))
12269       (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12270                    (not org-keep-stored-link-after-insertion))
12271           (setq org-stored-links (delq (assoc link org-stored-links)
12272                                        org-stored-links)))
12273       (setq desc (or desc (nth 1 entry)))))
12275     (if (string-match org-plain-link-re link)
12276         ;; URL-like link, normalize the use of angular brackets.
12277         (setq link (org-make-link (org-remove-angle-brackets link))))
12279     ;; Check if we are linking to the current file with a search option
12280     ;; If yes, simplify the link by using only the search option.
12281     (when (and buffer-file-name
12282                (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12283       (let* ((path (match-string 1 link))
12284              (case-fold-search nil)
12285              (search (match-string 2 link)))
12286         (save-match-data
12287           (if (equal (file-truename buffer-file-name) (file-truename path))
12288               ;; We are linking to this same file, with a search option
12289               (setq link search)))))
12291     ;; Check if we can/should use a relative path.  If yes, simplify the link
12292     (when (string-match "\\<file:\\(.*\\)" link)
12293       (let* ((path (match-string 1 link))
12294              (origpath path)
12295              (desc-is-link (equal link desc))
12296              (case-fold-search nil))
12297         (cond
12298          ((eq org-link-file-path-type 'absolute)
12299           (setq path (abbreviate-file-name (expand-file-name path))))
12300          ((eq org-link-file-path-type 'noabbrev)
12301           (setq path (expand-file-name path)))
12302          ((eq org-link-file-path-type 'relative)
12303           (setq path (file-relative-name path)))
12304          (t
12305           (save-match-data
12306             (if (string-match (concat "^" (regexp-quote
12307                                            (file-name-as-directory
12308                                             (expand-file-name "."))))
12309                               (expand-file-name path))
12310                 ;; We are linking a file with relative path name.
12311                 (setq path (substring (expand-file-name path)
12312                                       (match-end 0)))))))
12313         (setq link (concat "file:" path))
12314         (if (equal desc origpath)
12315             (setq desc path))))
12317     (setq desc (read-string "Description: " desc))
12318     (unless (string-match "\\S-" desc) (setq desc nil))
12319     (if remove (apply 'delete-region remove))
12320     (insert (org-make-link-string link desc))))
12322 (defun org-completing-read (&rest args)
12323   (let ((minibuffer-local-completion-map
12324          (copy-keymap minibuffer-local-completion-map)))
12325     (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12326     (apply 'completing-read args)))
12328 ;;; Opening/following a link
12329 (defvar org-link-search-failed nil)
12331 (defun org-next-link ()
12332   "Move forward to the next link.
12333 If the link is in hidden text, expose it."
12334   (interactive)
12335   (when (and org-link-search-failed (eq this-command last-command))
12336     (goto-char (point-min))
12337     (message "Link search wrapped back to beginning of buffer"))
12338   (setq org-link-search-failed nil)
12339   (let* ((pos (point))
12340          (ct (org-context))
12341          (a (assoc :link ct)))
12342     (if a (goto-char (nth 2 a)))
12343     (if (re-search-forward org-any-link-re nil t)
12344         (progn
12345           (goto-char (match-beginning 0))
12346           (if (org-invisible-p) (org-show-context)))
12347       (goto-char pos)
12348       (setq org-link-search-failed t)
12349       (error "No further link found"))))
12351 (defun org-previous-link ()
12352   "Move backward to the previous link.
12353 If the link is in hidden text, expose it."
12354   (interactive)
12355   (when (and org-link-search-failed (eq this-command last-command))
12356     (goto-char (point-max))
12357     (message "Link search wrapped back to end of buffer"))
12358   (setq org-link-search-failed nil)
12359   (let* ((pos (point))
12360          (ct (org-context))
12361          (a (assoc :link ct)))
12362     (if a (goto-char (nth 1 a)))
12363     (if (re-search-backward org-any-link-re nil t)
12364         (progn
12365           (goto-char (match-beginning 0))
12366           (if (org-invisible-p) (org-show-context)))
12367       (goto-char pos)
12368       (setq org-link-search-failed t)
12369       (error "No further link found"))))
12371 (defun org-find-file-at-mouse (ev)
12372   "Open file link or URL at mouse."
12373   (interactive "e")
12374   (mouse-set-point ev)
12375   (org-open-at-point 'in-emacs))
12377 (defun org-open-at-mouse (ev)
12378   "Open file link or URL at mouse."
12379   (interactive "e")
12380   (mouse-set-point ev)
12381   (org-open-at-point))
12383 (defvar org-window-config-before-follow-link nil
12384   "The window configuration before following a link.
12385 This is saved in case the need arises to restore it.")
12387 (defvar org-open-link-marker (make-marker)
12388   "Marker pointing to the location where `org-open-at-point; was called.")
12390 ;;;###autoload
12391 (defun org-open-at-point-global ()
12392   "Follow a link like Org-mode does.
12393 This command can be called in any mode to follow a link that has
12394 Org-mode syntax."
12395   (interactive)
12396   (org-run-like-in-org-mode 'org-open-at-point))
12398 (defun org-open-at-point (&optional in-emacs)
12399   "Open link at or after point.
12400 If there is no link at point, this function will search forward up to
12401 the end of the current subtree.
12402 Normally, files will be opened by an appropriate application.  If the
12403 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12404   (interactive "P")
12405   (catch 'abort
12406     (move-marker org-open-link-marker (point))
12407     (setq org-window-config-before-follow-link (current-window-configuration))
12408     (org-remove-occur-highlights nil nil t)
12409     (if (org-at-timestamp-p t)
12410         (org-follow-timestamp-link)
12411       (let (type path link line search (pos (point)))
12412         (catch 'match
12413           (save-excursion
12414             (skip-chars-forward "^]\n\r")
12415             (when (org-in-regexp org-bracket-link-regexp)
12416               (setq link (org-link-unescape (org-match-string-no-properties 1)))
12417               (while (string-match " *\n *" link)
12418                 (setq link (replace-match " " t t link)))
12419               (setq link (org-link-expand-abbrev link))
12420               (if (string-match org-link-re-with-space2 link)
12421                   (setq type (match-string 1 link) path (match-string 2 link))
12422                 (setq type "thisfile" path link))
12423               (throw 'match t)))
12425           (when (get-text-property (point) 'org-linked-text)
12426             (setq type "thisfile"
12427                   pos (if (get-text-property (1+ (point)) 'org-linked-text)
12428                           (1+ (point)) (point))
12429                   path (buffer-substring
12430                         (previous-single-property-change pos 'org-linked-text)
12431                         (next-single-property-change pos 'org-linked-text)))
12432             (throw 'match t))
12434           (save-excursion
12435             (when (or (org-in-regexp org-angle-link-re)
12436                       (org-in-regexp org-plain-link-re))
12437               (setq type (match-string 1) path (match-string 2))
12438               (throw 'match t)))
12439           (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12440             (setq type "tree-match"
12441                   path (match-string 1))
12442             (throw 'match t))
12443           (save-excursion
12444             (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12445               (setq type "tags"
12446                     path (match-string 1))
12447               (while (string-match ":" path)
12448                 (setq path (replace-match "+" t t path)))
12449               (throw 'match t))))
12450         (unless path
12451           (error "No link found"))
12452         ;; Remove any trailing spaces in path
12453         (if (string-match " +\\'" path)
12454             (setq path (replace-match "" t t path)))
12456         (cond
12458          ((assoc type org-link-protocols)
12459           (funcall (nth 1 (assoc type org-link-protocols)) path))
12461          ((equal type "mailto")
12462           (let ((cmd (car org-link-mailto-program))
12463                 (args (cdr org-link-mailto-program)) args1
12464                 (address path) (subject "") a)
12465             (if (string-match "\\(.*\\)::\\(.*\\)" path)
12466                 (setq address (match-string 1 path)
12467                       subject (org-link-escape (match-string 2 path))))
12468             (while args
12469               (cond
12470                ((not (stringp (car args))) (push (pop args) args1))
12471                (t (setq a (pop args))
12472                   (if (string-match "%a" a)
12473                       (setq a (replace-match address t t a)))
12474                   (if (string-match "%s" a)
12475                       (setq a (replace-match subject t t a)))
12476                   (push a args1))))
12477             (apply cmd (nreverse args1))))
12479          ((member type '("http" "https" "ftp" "news"))
12480           (browse-url (concat type ":" (org-link-escape
12481                                         path org-link-escape-chars-browser))))
12483          ((string= type "tags")
12484           (org-tags-view in-emacs path))
12485          ((string= type "thisfile")
12486           (if in-emacs
12487               (switch-to-buffer-other-window
12488                (org-get-buffer-for-internal-link (current-buffer)))
12489             (org-mark-ring-push))
12490           (let ((cmd `(org-link-search
12491                        ,path
12492                        ,(cond ((equal in-emacs '(4)) 'occur)
12493                               ((equal in-emacs '(16)) 'org-occur)
12494                               (t nil))
12495                        ,pos)))
12496             (condition-case nil (eval cmd)
12497               (error (progn (widen) (eval cmd))))))
12499          ((string= type "tree-match")
12500           (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12502          ((string= type "file")
12503           (if (string-match "::\\([0-9]+\\)\\'" path)
12504               (setq line (string-to-number (match-string 1 path))
12505                     path (substring path 0 (match-beginning 0)))
12506             (if (string-match "::\\(.+\\)\\'" path)
12507                 (setq search (match-string 1 path)
12508                       path (substring path 0 (match-beginning 0)))))
12509           (if (string-match "[*?{]" (file-name-nondirectory path))
12510               (dired path)
12511             (org-open-file path in-emacs line search)))
12513          ((string= type "news")
12514           (org-follow-gnus-link path))
12516          ((string= type "bbdb")
12517           (org-follow-bbdb-link path))
12519          ((string= type "info")
12520           (org-follow-info-link path))
12522          ((string= type "gnus")
12523           (let (group article)
12524             (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12525                 (error "Error in Gnus link"))
12526             (setq group (match-string 1 path)
12527                   article (match-string 3 path))
12528             (org-follow-gnus-link group article)))
12530          ((string= type "vm")
12531           (let (folder article)
12532             (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12533                 (error "Error in VM link"))
12534             (setq folder (match-string 1 path)
12535                   article (match-string 3 path))
12536             ;; in-emacs is the prefix arg, will be interpreted as read-only
12537             (org-follow-vm-link folder article in-emacs)))
12539          ((string= type "wl")
12540           (let (folder article)
12541             (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12542                 (error "Error in Wanderlust link"))
12543             (setq folder (match-string 1 path)
12544                   article (match-string 3 path))
12545             (org-follow-wl-link folder article)))
12547          ((string= type "mhe")
12548           (let (folder article)
12549             (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12550                 (error "Error in MHE link"))
12551             (setq folder (match-string 1 path)
12552                   article (match-string 3 path))
12553             (org-follow-mhe-link folder article)))
12555          ((string= type "rmail")
12556           (let (folder article)
12557             (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12558                 (error "Error in RMAIL link"))
12559             (setq folder (match-string 1 path)
12560                   article (match-string 3 path))
12561             (org-follow-rmail-link folder article)))
12563          ((string= type "shell")
12564           (let ((cmd path))
12565             (if (or (not org-confirm-shell-link-function)
12566                     (funcall org-confirm-shell-link-function
12567                              (format "Execute \"%s\" in shell? "
12568                                      (org-add-props cmd nil
12569                                                     'face 'org-warning))))
12570                 (progn
12571                   (message "Executing %s" cmd)
12572                   (shell-command cmd))
12573               (error "Abort"))))
12575          ((string= type "elisp")
12576           (let ((cmd path))
12577             (if (or (not org-confirm-elisp-link-function)
12578                     (funcall org-confirm-elisp-link-function
12579                              (format "Execute \"%s\" as elisp? "
12580                                      (org-add-props cmd nil
12581                                                     'face 'org-warning))))
12582                 (message "%s => %s" cmd (eval (read cmd)))
12583               (error "Abort"))))
12585          (t
12586           (browse-url-at-point)))))
12587     (move-marker org-open-link-marker nil)))
12589 ;;; File search
12591 (defvar org-create-file-search-functions nil
12592   "List of functions to construct the right search string for a file link.
12593 These functions are called in turn with point at the location to
12594 which the link should point.
12596 A function in the hook should first test if it would like to
12597 handle this file type, for example by checking the major-mode or
12598 the file extension.  If it decides not to handle this file, it
12599 should just return nil to give other functions a chance.  If it
12600 does handle the file, it must return the search string to be used
12601 when following the link.  The search string will be part of the
12602 file link, given after a double colon, and `org-open-at-point'
12603 will automatically search for it.  If special measures must be
12604 taken to make the search successful, another function should be
12605 added to the companion hook `org-execute-file-search-functions',
12606 which see.
12608 A function in this hook may also use `setq' to set the variable
12609 `description' to provide a suggestion for the descriptive text to
12610 be used for this link when it gets inserted into an Org-mode
12611 buffer with \\[org-insert-link].")
12613 (defvar org-execute-file-search-functions nil
12614   "List of functions to execute a file search triggered by a link.
12616 Functions added to this hook must accept a single argument, the
12617 search string that was part of the file link, the part after the
12618 double colon.  The function must first check if it would like to
12619 handle this search, for example by checking the major-mode or the
12620 file extension.  If it decides not to handle this search, it
12621 should just return nil to give other functions a chance.  If it
12622 does handle the search, it must return a non-nil value to keep
12623 other functions from trying.
12625 Each function can access the current prefix argument through the
12626 variable `current-prefix-argument'.  Note that a single prefix is
12627 used to force opening a link in Emacs, so it may be good to only
12628 use a numeric or double prefix to guide the search function.
12630 In case this is needed, a function in this hook can also restore
12631 the window configuration before `org-open-at-point' was called using:
12633     (set-window-configuration org-window-config-before-follow-link)")
12635 (defun org-link-search (s &optional type avoid-pos)
12636   "Search for a link search option.
12637 If S is surrounded by forward slashes, it is interpreted as a
12638 regular expression.  In org-mode files, this will create an `org-occur'
12639 sparse tree.  In ordinary files, `occur' will be used to list matches.
12640 If the current buffer is in `dired-mode', grep will be used to search
12641 in all files.  If AVOID-POS is given, ignore matches near that position."
12642   (let ((case-fold-search t)
12643         (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12644         (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12645                                             (append '(("") (" ") ("\t") ("\n"))
12646                                                     org-emphasis-alist)
12647                                             "\\|") "\\)"))
12648         (pos (point))
12649         (pre "") (post "")
12650         words re0 re1 re2 re3 re4 re5 re2a reall)
12651     (cond
12652      ;; First check if there are any special
12653      ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12654      ;; Now try the builtin stuff
12655      ((save-excursion
12656         (goto-char (point-min))
12657         (and
12658          (re-search-forward
12659           (concat "<<" (regexp-quote s0) ">>") nil t)
12660          (setq pos (match-beginning 0))))
12661       ;; There is an exact target for this
12662       (goto-char pos))
12663      ((string-match "^/\\(.*\\)/$" s)
12664       ;; A regular expression
12665       (cond
12666        ((org-mode-p)
12667         (org-occur (match-string 1 s)))
12668        ;;((eq major-mode 'dired-mode)
12669        ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12670        (t (org-do-occur (match-string 1 s)))))
12671      (t
12672       ;; A normal search strings
12673       (when (equal (string-to-char s) ?*)
12674         ;; Anchor on headlines, post may include tags.
12675         (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12676               post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12677               s (substring s 1)))
12678       (remove-text-properties
12679        0 (length s)
12680        '(face nil mouse-face nil keymap nil fontified nil) s)
12681       ;; Make a series of regular expressions to find a match
12682       (setq words (org-split-string s "[ \n\r\t]+")
12683             re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12684             re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12685                         "\\)" markers)
12686             re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12687             re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12688             re1 (concat pre re2 post)
12689             re3 (concat pre re4 post)
12690             re5 (concat pre ".*" re4)
12691             re2 (concat pre re2)
12692             re2a (concat pre re2a)
12693             re4 (concat pre re4)
12694             reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12695                           "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12696                           re5 "\\)"
12697                           ))
12698       (cond
12699        ((eq type 'org-occur) (org-occur reall))
12700        ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12701        (t (goto-char (point-min))
12702           (if (or (org-search-not-self 1 re0 nil t)
12703                   (org-search-not-self 1 re1 nil t)
12704                   (org-search-not-self 1 re2 nil t)
12705                   (org-search-not-self 1 re2a nil t)
12706                   (org-search-not-self 1 re3 nil t)
12707                   (org-search-not-self 1 re4 nil t)
12708                   (org-search-not-self 1 re5 nil t)
12709                   )
12710               (goto-char (match-beginning 1))
12711             (goto-char pos)
12712             (error "No match")))))
12713      (t
12714       ;; Normal string-search
12715       (goto-char (point-min))
12716       (if (search-forward s nil t)
12717           (goto-char (match-beginning 0))
12718         (error "No match"))))
12719     (and (org-mode-p) (org-show-context 'link-search))))
12721 (defun org-search-not-self (group &rest args)
12722   "Execute `re-search-forward', but only accept matches that do not
12723 enclose the position of `org-open-link-marker'."
12724   (let ((m org-open-link-marker))
12725     (catch 'exit
12726       (while (apply 're-search-forward args)
12727         (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12728           (goto-char (match-end group))
12729           (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12730                        (> (match-beginning 0) (marker-position m))
12731                        (< (match-end 0) (marker-position m)))
12732                    (save-match-data
12733                      (or (not (org-in-regexp
12734                                org-bracket-link-analytic-regexp 1))
12735                          (not (match-end 4))  ; no description
12736                          (and (<= (match-beginning 4) (point))
12737                               (>= (match-end 4) (point))))))
12738               (throw 'exit (point))))))))
12740 (defun org-get-buffer-for-internal-link (buffer)
12741   "Return a buffer to be used for displaying the link target of internal links."
12742   (cond
12743    ((not org-display-internal-link-with-indirect-buffer)
12744     buffer)
12745    ((string-match "(Clone)$" (buffer-name buffer))
12746     (message "Buffer is already a clone, not making another one")
12747     ;; we also do not modify visibility in this case
12748     buffer)
12749    (t ; make a new indirect buffer for displaying the link
12750     (let* ((bn (buffer-name buffer))
12751            (ibn (concat bn "(Clone)"))
12752            (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12753       (with-current-buffer ib (org-overview))
12754       ib))))
12756 (defun org-do-occur (regexp &optional cleanup)
12757   "Call the Emacs command `occur'.
12758 If CLEANUP is non-nil, remove the printout of the regular expression
12759 in the *Occur* buffer.  This is useful if the regex is long and not useful
12760 to read."
12761   (occur regexp)
12762   (when cleanup
12763     (let ((cwin (selected-window)) win beg end)
12764       (when (setq win (get-buffer-window "*Occur*"))
12765         (select-window win))
12766       (goto-char (point-min))
12767       (when (re-search-forward "match[a-z]+" nil t)
12768         (setq beg (match-end 0))
12769         (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12770             (setq end (1- (match-beginning 0)))))
12771       (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12772       (goto-char (point-min))
12773       (select-window cwin))))
12775 ;;; The mark ring for links jumps
12777 (defvar org-mark-ring nil
12778   "Mark ring for positions before jumps in Org-mode.")
12779 (defvar org-mark-ring-last-goto nil
12780   "Last position in the mark ring used to go back.")
12781 ;; Fill and close the ring
12782 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12783 (loop for i from 1 to org-mark-ring-length do
12784       (push (make-marker) org-mark-ring))
12785 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12786         org-mark-ring)
12788 (defun org-mark-ring-push (&optional pos buffer)
12789   "Put the current position or POS into the mark ring and rotate it."
12790   (interactive)
12791   (setq pos (or pos (point)))
12792   (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12793   (move-marker (car org-mark-ring)
12794                (or pos (point))
12795                (or buffer (current-buffer)))
12796   (message "%s"
12797    (substitute-command-keys
12798     "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12800 (defun org-mark-ring-goto (&optional n)
12801   "Jump to the previous position in the mark ring.
12802 With prefix arg N, jump back that many stored positions.  When
12803 called several times in succession, walk through the entire ring.
12804 Org-mode commands jumping to a different position in the current file,
12805 or to another Org-mode file, automatically push the old position
12806 onto the ring."
12807   (interactive "p")
12808   (let (p m)
12809     (if (eq last-command this-command)
12810         (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12811       (setq p org-mark-ring))
12812     (setq org-mark-ring-last-goto p)
12813     (setq m (car p))
12814     (switch-to-buffer (marker-buffer m))
12815     (goto-char m)
12816     (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12818 (defun org-remove-angle-brackets (s)
12819   (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12820   (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12821   s)
12822 (defun org-add-angle-brackets (s)
12823   (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12824   (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12825   s)
12827 ;;; Following specific links
12829 (defun org-follow-timestamp-link ()
12830   (cond
12831    ((org-at-date-range-p t)
12832     (let ((org-agenda-start-on-weekday)
12833           (t1 (match-string 1))
12834           (t2 (match-string 2)))
12835       (setq t1 (time-to-days (org-time-string-to-time t1))
12836             t2 (time-to-days (org-time-string-to-time t2)))
12837       (org-agenda-list nil t1 (1+ (- t2 t1)))))
12838    ((org-at-timestamp-p t)
12839     (org-agenda-list nil (time-to-days (org-time-string-to-time
12840                                         (substring (match-string 1) 0 10)))
12841                      1))
12842    (t (error "This should not happen"))))
12845 (defun org-follow-bbdb-link (name)
12846   "Follow a BBDB link to NAME."
12847   (require 'bbdb)
12848   (let ((inhibit-redisplay (not debug-on-error))
12849         (bbdb-electric-p nil))
12850     (catch 'exit
12851       ;; Exact match on name
12852       (bbdb-name (concat "\\`" name "\\'") nil)
12853       (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12854       ;; Exact match on name
12855       (bbdb-company (concat "\\`" name "\\'") nil)
12856       (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12857       ;; Partial match on name
12858       (bbdb-name name nil)
12859       (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12860       ;; Partial match on company
12861       (bbdb-company name nil)
12862       (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12863       ;; General match including network address and notes
12864       (bbdb name nil)
12865       (when (= 0 (buffer-size (get-buffer "*BBDB*")))
12866         (delete-window (get-buffer-window "*BBDB*"))
12867         (error "No matching BBDB record")))))
12869 (defun org-follow-info-link (name)
12870   "Follow an info file & node link  to NAME."
12871   (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
12872           (string-match "\\(.*\\)" name))
12873       (progn
12874         (require 'info)
12875         (if (match-string 2 name) ; If there isn't a node, choose "Top"
12876             (Info-find-node (match-string 1 name) (match-string 2 name))
12877           (Info-find-node (match-string 1 name) "Top")))
12878     (message "Could not open: %s" name)))
12880 (defun org-follow-gnus-link (&optional group article)
12881   "Follow a Gnus link to GROUP and ARTICLE."
12882   (require 'gnus)
12883   (funcall (cdr (assq 'gnus org-link-frame-setup)))
12884   (if gnus-other-frame-object (select-frame gnus-other-frame-object))
12885   (cond ((and group article)
12886          (gnus-group-read-group 1 nil group)
12887          (gnus-summary-goto-article (string-to-number article) nil t))
12888         (group (gnus-group-jump-to-group group))))
12890 (defun org-follow-vm-link (&optional folder article readonly)
12891   "Follow a VM link to FOLDER and ARTICLE."
12892   (require 'vm)
12893   (setq article (org-add-angle-brackets article))
12894   (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
12895       ;; ange-ftp or efs or tramp access
12896       (let ((user (or (match-string 1 folder) (user-login-name)))
12897             (host (match-string 2 folder))
12898             (file (match-string 3 folder)))
12899         (cond
12900          ((featurep 'tramp)
12901           ;; use tramp to access the file
12902           (if (featurep 'xemacs)
12903               (setq folder (format "[%s@%s]%s" user host file))
12904             (setq folder (format "/%s@%s:%s" user host file))))
12905          (t
12906           ;; use ange-ftp or efs
12907           (require (if (featurep 'xemacs) 'efs 'ange-ftp))
12908           (setq folder (format "/%s@%s:%s" user host file))))))
12909   (when folder
12910     (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
12911     (sit-for 0.1)
12912     (when article
12913       (vm-select-folder-buffer)
12914       (widen)
12915       (let ((case-fold-search t))
12916         (goto-char (point-min))
12917         (if (not (re-search-forward
12918                   (concat "^" "message-id: *" (regexp-quote article))))
12919             (error "Could not find the specified message in this folder"))
12920         (vm-isearch-update)
12921         (vm-isearch-narrow)
12922         (vm-beginning-of-message)
12923         (vm-summarize)))))
12925 (defun org-follow-wl-link (folder article)
12926   "Follow a Wanderlust link to FOLDER and ARTICLE."
12927   (if (and (string= folder "%")
12928            article
12929            (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
12930       ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
12931       ;; Thus, we recompose folder and article ids.
12932       (setq folder (format "%s#%s" folder (match-string 1 article))
12933             article (match-string 3 article)))
12934   (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
12935       (error "No such folder: %s" folder))
12936   (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
12937   (and article
12938        (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
12939        (wl-summary-redisplay)))
12941 (defun org-follow-rmail-link (folder article)
12942   "Follow an RMAIL link to FOLDER and ARTICLE."
12943   (setq article (org-add-angle-brackets article))
12944   (let (message-number)
12945     (save-excursion
12946       (save-window-excursion
12947         (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12948         (setq message-number
12949               (save-restriction
12950                 (widen)
12951                 (goto-char (point-max))
12952                 (if (re-search-backward
12953                      (concat "^Message-ID:\\s-+" (regexp-quote
12954                                                   (or article "")))
12955                      nil t)
12956                     (rmail-what-message))))))
12957     (if message-number
12958         (progn
12959           (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12960           (rmail-show-message message-number)
12961           message-number)
12962       (error "Message not found"))))
12964 ;;; mh-e integration based on planner-mode
12965 (defun org-mhe-get-message-real-folder ()
12966   "Return the name of the current message real folder, so if you use
12967 sequences, it will now work."
12968   (save-excursion
12969     (let* ((folder
12970             (if (equal major-mode 'mh-folder-mode)
12971                 mh-current-folder
12972               ;; Refer to the show buffer
12973               mh-show-folder-buffer))
12974            (end-index
12975             (if (boundp 'mh-index-folder)
12976                 (min (length mh-index-folder) (length folder))))
12977            )
12978       ;; a simple test on mh-index-data does not work, because
12979       ;; mh-index-data is always nil in a show buffer.
12980       (if (and (boundp 'mh-index-folder)
12981                (string= mh-index-folder (substring folder 0 end-index)))
12982           (if (equal major-mode 'mh-show-mode)
12983               (save-window-excursion
12984                 (let (pop-up-frames)
12985                   (when (buffer-live-p (get-buffer folder))
12986                     (progn
12987                       (pop-to-buffer folder)
12988                       (org-mhe-get-message-folder-from-index)
12989                       )
12990                     )))
12991             (org-mhe-get-message-folder-from-index)
12992             )
12993         folder
12994         )
12995       )))
12997 (defun org-mhe-get-message-folder-from-index ()
12998   "Returns the name of the message folder in a index folder buffer."
12999   (save-excursion
13000     (mh-index-previous-folder)
13001     (re-search-forward "^\\(+.*\\)$" nil t)
13002     (message "%s" (match-string 1))))
13004 (defun org-mhe-get-message-folder ()
13005   "Return the name of the current message folder.  Be careful if you
13006 use sequences."
13007   (save-excursion
13008     (if (equal major-mode 'mh-folder-mode)
13009         mh-current-folder
13010       ;; Refer to the show buffer
13011       mh-show-folder-buffer)))
13013 (defun org-mhe-get-message-num ()
13014   "Return the number of the current message.  Be careful if you
13015 use sequences."
13016   (save-excursion
13017     (if (equal major-mode 'mh-folder-mode)
13018         (mh-get-msg-num nil)
13019       ;; Refer to the show buffer
13020       (mh-show-buffer-message-number))))
13022 (defun org-mhe-get-header (header)
13023   "Return a header of the message in folder mode. This will create a
13024 show buffer for the corresponding message. If you have a more clever
13025 idea..."
13026   (let* ((folder (org-mhe-get-message-folder))
13027          (num (org-mhe-get-message-num))
13028          (buffer (get-buffer-create (concat "show-" folder)))
13029          (header-field))
13030   (with-current-buffer buffer
13031     (mh-display-msg num folder)
13032     (if (equal major-mode 'mh-folder-mode)
13033         (mh-header-display)
13034       (mh-show-header-display))
13035     (set-buffer buffer)
13036     (setq header-field (mh-get-header-field header))
13037     (if (equal major-mode 'mh-folder-mode)
13038         (mh-show)
13039       (mh-show-show))
13040     header-field)))
13042 (defun org-follow-mhe-link (folder article)
13043   "Follow an MHE link to FOLDER and ARTICLE.
13044 If ARTICLE is nil FOLDER is shown.  If the configuration variable
13045 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13046 ARTICLE is searched in all folders.  Indexed searches (swish++,
13047 namazu, and others supported by MH-E) will always search in all
13048 folders."
13049   (require 'mh-e)
13050   (require 'mh-search)
13051   (require 'mh-utils)
13052   (mh-find-path)
13053   (if (not article)
13054       (mh-visit-folder (mh-normalize-folder-name folder))
13055     (setq article (org-add-angle-brackets article))
13056     (mh-search-choose)
13057     (if (equal mh-searcher 'pick)
13058         (progn
13059           (mh-search folder (list "--message-id" article))
13060           (when (and org-mhe-search-all-folders
13061                      (not (org-mhe-get-message-real-folder)))
13062             (kill-this-buffer)
13063             (mh-search "+" (list "--message-id" article))))
13064       (mh-search "+" article))
13065     (if (org-mhe-get-message-real-folder)
13066         (mh-show-msg 1)
13067       (kill-this-buffer)
13068       (error "Message not found"))))
13070 ;;; BibTeX links
13072 ;; Use the custom search meachnism to construct and use search strings for
13073 ;; file links to BibTeX database entries.
13075 (defun org-create-file-search-in-bibtex ()
13076   "Create the search string and description for a BibTeX database entry."
13077   (when (eq major-mode 'bibtex-mode)
13078     ;; yes, we want to construct this search string.
13079     ;; Make a good description for this entry, using names, year and the title
13080     ;; Put it into the `description' variable which is dynamically scoped.
13081     (let ((bibtex-autokey-names 1)
13082           (bibtex-autokey-names-stretch 1)
13083           (bibtex-autokey-name-case-convert-function 'identity)
13084           (bibtex-autokey-name-separator " & ")
13085           (bibtex-autokey-additional-names " et al.")
13086           (bibtex-autokey-year-length 4)
13087           (bibtex-autokey-name-year-separator " ")
13088           (bibtex-autokey-titlewords 3)
13089           (bibtex-autokey-titleword-separator " ")
13090           (bibtex-autokey-titleword-case-convert-function 'identity)
13091           (bibtex-autokey-titleword-length 'infty)
13092           (bibtex-autokey-year-title-separator ": "))
13093       (setq description (bibtex-generate-autokey)))
13094     ;; Now parse the entry, get the key and return it.
13095     (save-excursion
13096       (bibtex-beginning-of-entry)
13097       (cdr (assoc "=key=" (bibtex-parse-entry))))))
13099 (defun org-execute-file-search-in-bibtex (s)
13100   "Find the link search string S as a key for a database entry."
13101   (when (eq major-mode 'bibtex-mode)
13102     ;; Yes, we want to do the search in this file.
13103     ;; We construct a regexp that searches for "@entrytype{" followed by the key
13104     (goto-char (point-min))
13105     (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13106                                     (regexp-quote s) "[ \t\n]*,") nil t)
13107          (goto-char (match-beginning 0)))
13108     (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13109         ;; Use double prefix to indicate that any web link should be browsed
13110         (let ((b (current-buffer)) (p (point)))
13111           ;; Restore the window configuration because we just use the web link
13112           (set-window-configuration org-window-config-before-follow-link)
13113           (save-excursion (set-buffer b) (goto-char p)
13114             (bibtex-url)))
13115       (recenter 0))  ; Move entry start to beginning of window
13116   ;; return t to indicate that the search is done.
13117     t))
13119 ;; Finally add the functions to the right hooks.
13120 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13121 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13123 ;; end of Bibtex link setup
13125 ;;; Following file links
13127 (defun org-open-file (path &optional in-emacs line search)
13128   "Open the file at PATH.
13129 First, this expands any special file name abbreviations.  Then the
13130 configuration variable `org-file-apps' is checked if it contains an
13131 entry for this file type, and if yes, the corresponding command is launched.
13132 If no application is found, Emacs simply visits the file.
13133 With optional argument IN-EMACS, Emacs will visit the file.
13134 Optional LINE specifies a line to go to, optional SEARCH a string to
13135 search for.  If LINE or SEARCH is given, the file will always be
13136 opened in Emacs.
13137 If the file does not exist, an error is thrown."
13138   (setq in-emacs (or in-emacs line search))
13139   (let* ((file (if (equal path "")
13140                    buffer-file-name
13141                  (substitute-in-file-name (expand-file-name path))))
13142          (apps (append org-file-apps (org-default-apps)))
13143          (remp (and (assq 'remote apps) (org-file-remote-p file)))
13144          (dirp (if remp nil (file-directory-p file)))
13145          (dfile (downcase file))
13146          (old-buffer (current-buffer))
13147          (old-pos (point))
13148          (old-mode major-mode)
13149          ext cmd)
13150     (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13151         (setq ext (match-string 1 dfile))
13152       (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13153           (setq ext (match-string 1 dfile))))
13154     (if in-emacs
13155         (setq cmd 'emacs)
13156       (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13157                     (and dirp (cdr (assoc 'directory apps)))
13158                     (cdr (assoc ext apps))
13159                     (cdr (assoc t apps)))))
13160     (when (eq cmd 'mailcap)
13161       (require 'mailcap)
13162       (mailcap-parse-mailcaps)
13163       (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13164              (command (mailcap-mime-info mime-type)))
13165         (if (stringp command)
13166             (setq cmd command)
13167           (setq cmd 'emacs))))
13168     (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13169              (not (file-exists-p file))
13170              (not org-open-non-existing-files))
13171         (error "No such file: %s" file))
13172     (cond
13173      ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13174       ;; Remove quotes around the file name - we'll use shell-quote-argument.
13175       (while (string-match "['\"]%s['\"]" cmd)
13176         (setq cmd (replace-match "%s" t t cmd)))
13177       (while (string-match "%s" cmd)
13178         (setq cmd (replace-match (shell-quote-argument file) t t cmd)))
13179       (save-window-excursion
13180         (start-process-shell-command cmd nil cmd)))
13181      ((or (stringp cmd)
13182           (eq cmd 'emacs))
13183       (funcall (cdr (assq 'file org-link-frame-setup)) file)
13184       (widen)
13185       (if line (goto-line line)
13186         (if search (org-link-search search))))
13187      ((consp cmd)
13188       (eval cmd))
13189      (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13190     (and (org-mode-p) (eq old-mode 'org-mode)
13191          (or (not (equal old-buffer (current-buffer)))
13192              (not (equal old-pos (point))))
13193          (org-mark-ring-push old-pos old-buffer))))
13195 (defun org-default-apps ()
13196   "Return the default applications for this operating system."
13197   (cond
13198    ((eq system-type 'darwin)
13199     org-file-apps-defaults-macosx)
13200    ((eq system-type 'windows-nt)
13201     org-file-apps-defaults-windowsnt)
13202    (t org-file-apps-defaults-gnu)))
13204 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13205 (defun org-file-remote-p (file)
13206   "Test whether FILE specifies a location on a remote system.
13207 Return non-nil if the location is indeed remote.
13209 For example, the filename \"/user@host:/foo\" specifies a location
13210 on the system \"/user@host:\"."
13211   (cond ((fboundp 'file-remote-p)
13212          (file-remote-p file))
13213         ((fboundp 'tramp-handle-file-remote-p)
13214          (tramp-handle-file-remote-p file))
13215         ((and (boundp 'ange-ftp-name-format)
13216               (string-match (car ange-ftp-name-format) file))
13217          t)
13218         (t nil)))
13221 ;;;; Hooks for remember.el, and refiling
13223 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13224 (defvar initial)    ; from remember.el, dynamically scoped in `remember-mode'
13226 ;;;###autoload
13227 (defun org-remember-insinuate ()
13228   "Setup remember.el for use wiht Org-mode."
13229   (require 'remember)
13230   (setq remember-annotation-functions '(org-remember-annotation))
13231   (setq remember-handler-functions '(org-remember-handler))
13232   (add-hook 'remember-mode-hook 'org-remember-apply-template))
13234 ;;;###autoload
13235 (defun org-remember-annotation ()
13236   "Return a link to the current location as an annotation for remember.el.
13237 If you are using Org-mode files as target for data storage with
13238 remember.el, then the annotations should include a link compatible with the
13239 conventions in Org-mode.  This function returns such a link."
13240   (org-store-link nil))
13242 (defconst org-remember-help
13243 "Select a destination location for the note.
13244 UP/DOWN=headline   TAB=cycle visibility  [Q]uit   RET/<left>/<right>=Store
13245 RET on headline   -> Store as sublevel entry to current headline
13246 RET at beg-of-buf -> Append to file as level 2 headline
13247 <left>/<right>    -> before/after current headline, same headings level")
13249 (defvar org-remember-previous-location nil)
13250 (defvar org-force-remember-template-char) ;; dynamically scoped
13252 (defun org-select-remember-template (&optional use-char)
13253   (when org-remember-templates
13254     (let* ((templates (mapcar (lambda (x)
13255                                 (if (stringp (car x))
13256                                     (append (list (nth 1 x) (car x)) (cddr x))
13257                                   (append (list (car x) "") (cdr x))))
13258                               org-remember-templates))
13259            (char (or use-char
13260                      (cond
13261                       ((= (length templates) 1)
13262                        (caar templates))
13263                       ((and (boundp 'org-force-remember-template-char)
13264                             org-force-remember-template-char)
13265                        (if (stringp org-force-remember-template-char)
13266                            (string-to-char org-force-remember-template-char)
13267                          org-force-remember-template-char))
13268                       (t
13269                        (message "Select template: %s"
13270                                 (mapconcat
13271                                  (lambda (x)
13272                                    (cond
13273                                     ((not (string-match "\\S-" (nth 1 x)))
13274                                      (format "[%c]" (car x)))
13275                                     ((equal (downcase (car x))
13276                                             (downcase (aref (nth 1 x) 0)))
13277                                      (format "[%c]%s" (car x)
13278                                              (substring (nth 1 x) 1)))
13279                                     (t (format "[%c]%s" (car x) (nth 1 x)))))
13280                                  templates " "))
13281                        (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13282                          (when (equal char0 ?\C-g)
13283                            (jump-to-register remember-register)
13284                            (kill-buffer remember-buffer))
13285                          char0))))))
13286       (cddr (assoc char templates)))))
13288 (defvar x-last-selected-text)
13289 (defvar x-last-selected-text-primary)
13291 ;;;###autoload
13292 (defun org-remember-apply-template (&optional use-char skip-interactive)
13293   "Initialize *remember* buffer with template, invoke `org-mode'.
13294 This function should be placed into `remember-mode-hook' and in fact requires
13295 to be run from that hook to function properly."
13296   (unless (fboundp 'remember-finalize)
13297     (defalias 'remember-finalize 'remember-buffer))
13298   (if org-remember-templates
13299       (let* ((entry (org-select-remember-template use-char))
13300              (tpl (car entry))
13301              (plist-p (if org-store-link-plist t nil))
13302              (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13303                             (string-match "\\S-" (nth 1 entry)))
13304                        (nth 1 entry)
13305                      org-default-notes-file))
13306              (headline (nth 2 entry))
13307              (v-c (or (and (eq window-system 'x)
13308                            (fboundp 'x-cut-buffer-or-selection-value)
13309                            (x-cut-buffer-or-selection-value))
13310                       (org-bound-and-true-p x-last-selected-text)
13311                       (org-bound-and-true-p x-last-selected-text-primary)
13312                       (and (> (length kill-ring) 0) (current-kill 0))))
13313              (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13314              (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13315              (v-u (concat "[" (substring v-t 1 -1) "]"))
13316              (v-U (concat "[" (substring v-T 1 -1) "]"))
13317              ;; `initial' and `annotation' are bound in `remember'
13318              (v-i (if (boundp 'initial) initial))
13319              (v-a (if (and (boundp 'annotation) annotation)
13320                       (if (equal annotation "[[]]") "" annotation)
13321                     ""))
13322              (v-A (if (and v-a
13323                            (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13324                       (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13325                     v-a))
13326              (v-n user-full-name)
13327              (org-startup-folded nil)
13328              org-time-was-given org-end-time-was-given x
13329              prompt completions char time pos default histvar)
13330         (setq org-store-link-plist
13331               (append (list :annotation v-a :initial v-i)
13332                       org-store-link-plist))
13333         (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13334         (erase-buffer)
13335         (insert (substitute-command-keys
13336                  (format
13337 "## Filing location: Select interactively, default, or last used:
13338 ## %s  to select file and header location interactively.
13339 ## %s  \"%s\" -> \"* %s\"
13340 ## C-u C-u C-c C-c  \"%s\" -> \"* %s\"
13341 ## To switch templates, use `\\[org-remember]'.  To abort use `C-c C-k'.\n\n"
13342                   (if org-remember-store-without-prompt "    C-u C-c C-c" "        C-c C-c")
13343                   (if org-remember-store-without-prompt "        C-c C-c" "    C-u C-c C-c")
13344                   (abbreviate-file-name (or file org-default-notes-file))
13345                   (or headline "")
13346                   (or (car org-remember-previous-location) "???")
13347                   (or (cdr org-remember-previous-location) "???"))))
13348         (insert tpl) (goto-char (point-min))
13349         ;; Simple %-escapes
13350         (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13351           (when (and initial (equal (match-string 0) "%i"))
13352             (save-match-data
13353               (let* ((lead (buffer-substring
13354                             (point-at-bol) (match-beginning 0))))
13355                 (setq v-i (mapconcat 'identity
13356                                      (org-split-string initial "\n")
13357                                      (concat "\n" lead))))))
13358           (replace-match
13359            (or (eval (intern (concat "v-" (match-string 1)))) "")
13360            t t))
13362         ;; %[] Insert contents of a file.
13363         (goto-char (point-min))
13364         (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13365           (let ((start (match-beginning 0))
13366                 (end (match-end 0))
13367                 (filename (expand-file-name (match-string 1))))
13368             (goto-char start)
13369             (delete-region start end)
13370             (condition-case error
13371                 (insert-file-contents filename)
13372               (error (insert (format "%%![Couldn't insert %s: %s]"
13373                                      filename error))))))
13374         ;; %() embedded elisp
13375         (goto-char (point-min))
13376         (while (re-search-forward "%\\((.+)\\)" nil t)
13377           (goto-char (match-beginning 0))
13378           (let ((template-start (point)))
13379             (forward-char 1)
13380             (let ((result
13381                    (condition-case error
13382                        (eval (read (current-buffer)))
13383                      (error (format "%%![Error: %s]" error)))))
13384               (delete-region template-start (point))
13385               (insert result))))
13387         ;; From the property list
13388         (when plist-p
13389           (goto-char (point-min))
13390           (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13391             (and (setq x (or (plist-get org-store-link-plist
13392                                         (intern (match-string 1))) ""))
13393                  (replace-match x t t))))
13395         ;; Turn on org-mode in the remember buffer, set local variables
13396         (org-mode)
13397         (org-set-local 'org-finish-function 'remember-finalize)
13398         (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13399             (org-set-local 'org-default-notes-file file))
13400         (if (and headline (stringp headline) (string-match "\\S-" headline))
13401             (org-set-local 'org-remember-default-headline headline))
13402         ;; Interactive template entries
13403         (goto-char (point-min))
13404         (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([guUtT]\\)?" nil t)
13405           (setq char (if (match-end 3) (match-string 3))
13406                 prompt (if (match-end 2) (match-string 2)))
13407           (goto-char (match-beginning 0))
13408           (replace-match "")
13409           (setq completions nil default nil)
13410           (when prompt
13411             (setq completions (org-split-string prompt "|")
13412                   prompt (pop completions)
13413                   default (car completions)
13414                   histvar (intern (concat
13415                                    "org-remember-template-prompt-history::"
13416                                    (or prompt "")))
13417                   completions (mapcar 'list completions)))
13418           (cond
13419            ((member char '("G" "g"))
13420             (let* ((org-last-tags-completion-table
13421                     (org-global-tags-completion-table
13422                      (if (equal char "G") (org-agenda-files) (and file (list file)))))
13423                    (org-add-colon-after-tag-completion t)
13424                    (ins (completing-read
13425                          (if prompt (concat prompt ": ") "Tags: ")
13426                          'org-tags-completion-function nil nil nil
13427                          'org-tags-history)))
13428               (setq ins (mapconcat 'identity
13429                                   (org-split-string ins (org-re "[^[:alnum:]]+"))
13430                                   ":"))
13431               (when (string-match "\\S-" ins)
13432                 (or (equal (char-before) ?:) (insert ":"))
13433                 (insert ins)
13434                 (or (equal (char-after) ?:) (insert ":")))))
13435            (char
13436             (setq org-time-was-given (equal (upcase char) char))
13437             (setq time (org-read-date (equal (upcase char) "U") t nil
13438                                       prompt))
13439             (org-insert-time-stamp time org-time-was-given
13440                                    (member char '("u" "U"))
13441                                    nil nil (list org-end-time-was-given)))
13442            (t
13443             (insert (org-completing-read
13444                      (concat (if prompt prompt "Enter string")
13445                              (if default (concat " [" default "]"))
13446                              ": ")
13447                      completions nil nil nil histvar default)))))
13448         (goto-char (point-min))
13449         (if (re-search-forward "%\\?" nil t)
13450             (replace-match "")
13451           (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13452     (org-mode)
13453     (org-set-local 'org-finish-function 'remember-finalize))
13454   (when (save-excursion
13455           (goto-char (point-min))
13456           (re-search-forward "%!" nil t))
13457     (replace-match "")
13458     (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13460 (defun org-remember-finish-immediately ()
13461   "File remember note immediately.
13462 This should be run in `post-command-hook' and will remove itself
13463 from that hook."
13464   (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13465   (when org-finish-function
13466     (funcall org-finish-function)))
13469 ;;;###autoload
13470 (defun org-remember (&optional goto org-force-remember-template-char)
13471   "Call `remember'.  If this is already a remember buffer, re-apply template.
13472 If there is an active region, make sure remember uses it as initial content
13473 of the remember buffer.
13475 When called interactively with a `C-u' prefix argument GOTO, don't remember
13476 anything, just go to the file/headline where the selected templated usually
13477 stores its notes.  With a double prefix arg `C-u C-u', got to the last
13478 note stored by remember.
13480 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13481 associated with a template in `org-remember-tempates'."
13482   (interactive "P")
13483   (cond
13484    ((equal goto '(4)) (org-go-to-remember-target))
13485    ((equal goto '(16)) (org-remember-goto-last-stored))
13486    (t
13487     (if (memq org-finish-function '(remember-buffer remember-finalize))
13488         (progn
13489           (when (< (length org-remember-templates) 2)
13490             (error "No other template available"))
13491           (erase-buffer)
13492           (let ((annotation (plist-get org-store-link-plist :annotation))
13493                 (initial (plist-get org-store-link-plist :initial)))
13494             (org-remember-apply-template))
13495           (message "Press C-c C-c to remember data"))
13496       (if (org-region-active-p)
13497           (remember (buffer-substring (point) (mark)))
13498         (call-interactively 'remember))))))
13500 (defun org-remember-goto-last-stored ()
13501   "Go to the location where the last remember note was stored."
13502   (interactive)
13503   (bookmark-jump "org-remember-last-stored")
13504   (message "This is the last note stored by remember"))
13506 (defun org-go-to-remember-target (&optional template-key)
13507   "Go to the target location of a remember template.
13508 The user is queried for the template."
13509   (interactive)
13510   (let* ((entry (org-select-remember-template template-key))
13511          (file (nth 1 entry))
13512          (heading (nth 2 entry))
13513          visiting)
13514     (unless (and file (stringp file) (string-match "\\S-" file))
13515       (setq file org-default-notes-file))
13516     (unless (and heading (stringp heading) (string-match "\\S-" heading))
13517       (setq heading org-remember-default-headline))
13518     (setq visiting (org-find-base-buffer-visiting file))
13519     (if (not visiting) (find-file-noselect file))
13520     (switch-to-buffer (or visiting (get-file-buffer file)))
13521     (widen)
13522     (goto-char (point-min))
13523     (if (re-search-forward
13524          (concat "^\\*+[ \t]+" (regexp-quote heading)
13525                  (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13526          nil t)
13527         (goto-char (match-beginning 0))
13528       (error "Target headline not found: %s" heading))))
13530 (defvar org-note-abort nil) ; dynamically scoped
13532 ;;;###autoload
13533 (defun org-remember-handler ()
13534   "Store stuff from remember.el into an org file.
13535 First prompts for an org file.  If the user just presses return, the value
13536 of `org-default-notes-file' is used.
13537 Then the command offers the headings tree of the selected file in order to
13538 file the text at a specific location.
13539 You can either immediately press RET to get the note appended to the
13540 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13541 find a better place.  Then press RET or <left> or <right> in insert the note.
13543 Key      Cursor position   Note gets inserted
13544 -----------------------------------------------------------------------------
13545 RET      buffer-start      as level 1 heading at end of file
13546 RET      on headline       as sublevel of the heading at cursor
13547 RET      no heading        at cursor position, level taken from context.
13548                            Or use prefix arg to specify level manually.
13549 <left>   on headline       as same level, before current heading
13550 <right>  on headline       as same level, after current heading
13552 So the fastest way to store the note is to press RET RET to append it to
13553 the default file.  This way your current train of thought is not
13554 interrupted, in accordance with the principles of remember.el.
13555 You can also get the fast execution without prompting by using
13556 C-u C-c C-c to exit the remember buffer.  See also the variable
13557 `org-remember-store-without-prompt'.
13559 Before being stored away, the function ensures that the text has a
13560 headline, i.e. a first line that starts with a \"*\".  If not, a headline
13561 is constructed from the current date and some additional data.
13563 If the variable `org-adapt-indentation' is non-nil, the entire text is
13564 also indented so that it starts in the same column as the headline
13565 \(i.e. after the stars).
13567 See also the variable `org-reverse-note-order'."
13568   (goto-char (point-min))
13569   (while (looking-at "^[ \t]*\n\\|^##.*\n")
13570     (replace-match ""))
13571   (goto-char (point-max))
13572   (beginning-of-line 1)
13573   (while (looking-at "[ \t]*$\\|##.*")
13574     (delete-region (1- (point)) (point-max))
13575     (beginning-of-line 1))
13576   (catch 'quit
13577     (if org-note-abort (throw 'quit nil))
13578     (let* ((txt (buffer-substring (point-min) (point-max)))
13579            (fastp (org-xor (equal current-prefix-arg '(4))
13580                            org-remember-store-without-prompt))
13581            (file (if fastp org-default-notes-file (org-get-org-file)))
13582            (heading org-remember-default-headline)
13583            (visiting (org-find-base-buffer-visiting file))
13584            (org-startup-folded nil)
13585            (org-startup-align-all-tables nil)
13586            (org-goto-start-pos 1)
13587            spos exitcmd level indent reversed)
13588       (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13589           (setq file (car org-remember-previous-location)
13590                 heading (cdr org-remember-previous-location)))
13591       (setq current-prefix-arg nil)
13592       (if (string-match "[ \t\n]+\\'" txt)
13593           (setq txt (replace-match "" t t txt)))
13594       ;; Modify text so that it becomes a nice subtree which can be inserted
13595       ;; into an org tree.
13596       (let* ((lines (split-string txt "\n"))
13597              first)
13598         (setq first (car lines) lines (cdr lines))
13599         (if (string-match "^\\*+ " first)
13600             ;; Is already a headline
13601             (setq indent nil)
13602           ;; We need to add a headline:  Use time and first buffer line
13603           (setq lines (cons first lines)
13604                 first (concat "* " (current-time-string)
13605                               " (" (remember-buffer-desc) ")")
13606                 indent "  "))
13607         (if (and org-adapt-indentation indent)
13608             (setq lines (mapcar
13609                          (lambda (x)
13610                            (if (string-match "\\S-" x)
13611                                (concat indent x) x))
13612                          lines)))
13613         (setq txt (concat first "\n"
13614                           (mapconcat 'identity lines "\n"))))
13615       (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13616           (setq txt (replace-match "\n\n" t t txt))
13617         (if (string-match "[ \t\n]*\\'" txt)
13618             (setq txt (replace-match "\n" t t txt))))
13619       ;; Find the file
13620       (if (not visiting) (find-file-noselect file))
13621       (with-current-buffer (or visiting (get-file-buffer file))
13622         (unless (org-mode-p)
13623           (error "Target files for remember notes must be in Org-mode"))
13624         (save-excursion
13625           (save-restriction
13626             (widen)
13627             (and (goto-char (point-min))
13628                  (not (re-search-forward "^\\* " nil t))
13629                  (insert "\n* " (or heading "Notes") "\n"))
13630             (setq reversed (org-notes-order-reversed-p))
13632             ;; Find the default location
13633             (when (and heading (stringp heading) (string-match "\\S-" heading))
13634               (goto-char (point-min))
13635               (if (re-search-forward
13636                    (concat "^\\*+[ \t]+" (regexp-quote heading)
13637                            (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13638                    nil t)
13639                   (setq org-goto-start-pos (match-beginning 0))
13640                 (when fastp
13641                   (goto-char (point-max))
13642                   (unless (bolp) (newline))
13643                   (insert "* " heading "\n")
13644                   (setq org-goto-start-pos (point-at-bol 0)))))
13646             ;; Ask the User for a location
13647             (if fastp
13648                 (setq spos org-goto-start-pos
13649                       exitcmd 'return)
13650               (setq spos (org-get-location (current-buffer) org-remember-help)
13651                     exitcmd (cdr spos)
13652                     spos (car spos)))
13653             (if (not spos) (throw 'quit nil)) ; return nil to show we did
13654                                         ; not handle this note
13655             (goto-char spos)
13656             (cond ((org-on-heading-p t)
13657                    (org-back-to-heading t)
13658                    (setq level (funcall outline-level))
13659                    (cond
13660                     ((eq exitcmd 'return)
13661                      ;; sublevel of current
13662                      (setq org-remember-previous-location
13663                            (cons (abbreviate-file-name file)
13664                                  (org-get-heading 'notags)))
13665                      (if reversed
13666                          (outline-next-heading)
13667                        (org-end-of-subtree)
13668                        (if (not (bolp))
13669                            (if (looking-at "[ \t]*\n")
13670                                (beginning-of-line 2)
13671                              (end-of-line 1)
13672                              (insert "\n"))))
13673                      (bookmark-set "org-remember-last-stored")
13674                      (org-paste-subtree (org-get-legal-level level 1) txt))
13675                     ((eq exitcmd 'left)
13676                      ;; before current
13677                      (bookmark-set "org-remember-last-stored")
13678                      (org-paste-subtree level txt))
13679                     ((eq exitcmd 'right)
13680                      ;; after current
13681                      (org-end-of-subtree t)
13682                      (bookmark-set "org-remember-last-stored")
13683                      (org-paste-subtree level txt))
13684                     (t (error "This should not happen"))))
13686                   ((and (bobp) (not reversed))
13687                    ;; Put it at the end, one level below level 1
13688                    (save-restriction
13689                      (widen)
13690                      (goto-char (point-max))
13691                      (if (not (bolp)) (newline))
13692                      (bookmark-set "org-remember-last-stored")
13693                      (org-paste-subtree (org-get-legal-level 1 1) txt)))
13695                   ((and (bobp) reversed)
13696                    ;; Put it at the start, as level 1
13697                    (save-restriction
13698                      (widen)
13699                      (goto-char (point-min))
13700                      (re-search-forward "^\\*+ " nil t)
13701                      (beginning-of-line 1)
13702                      (bookmark-set "org-remember-last-stored")
13703                      (org-paste-subtree 1 txt)))
13704                   (t
13705                    ;; Put it right there, with automatic level determined by
13706                    ;; org-paste-subtree or from prefix arg
13707                    (bookmark-set "org-remember-last-stored")
13708                    (org-paste-subtree
13709                     (if (numberp current-prefix-arg) current-prefix-arg)
13710                     txt)))
13711             (when remember-save-after-remembering
13712               (save-buffer)
13713               (if (not visiting) (kill-buffer (current-buffer)))))))))
13714   
13715   t)    ;; return t to indicate that we took care of this note.
13717 (defun org-get-org-file ()
13718   "Read a filename, with default directory `org-directory'."
13719   (let ((default (or org-default-notes-file remember-data-file)))
13720     (read-file-name (format "File name [%s]: " default)
13721                     (file-name-as-directory org-directory)
13722                     default)))
13724 (defun org-notes-order-reversed-p ()
13725   "Check if the current file should receive notes in reversed order."
13726   (cond
13727    ((not org-reverse-note-order) nil)
13728    ((eq t org-reverse-note-order) t)
13729    ((not (listp org-reverse-note-order)) nil)
13730    (t (catch 'exit
13731         (let  ((all org-reverse-note-order)
13732                entry)
13733           (while (setq entry (pop all))
13734             (if (string-match (car entry) buffer-file-name)
13735                 (throw 'exit (cdr entry))))
13736           nil)))))
13738 ;;; Refiling
13740 (defvar org-refile-target-table nil
13741   "The list of refile targets, created by `org-refile'.")
13743 (defvar org-agenda-new-buffers nil
13744   "Buffers created to visit agenda files.")
13746 (defun org-get-refile-targets ()
13747   "Produce a table with refile targets."
13748   (let ((entries org-refile-targets)
13749         org-agenda-new-files targets txt re files f desc descre)
13750     (while (setq entry (pop entries))
13751       (setq files (car entry) desc (cdr entry))
13752       (cond
13753        ((null files) (setq files (list (current-buffer))))
13754        ((eq files 'org-agenda-files)
13755         (setq files (org-agenda-files 'unrestricted)))
13756        ((and (symbolp files) (fboundp files))
13757         (setq files (funcall files)))
13758        ((and (symbolp files) (boundp files))
13759         (setq files (symbol-value files))))
13760       (if (stringp files) (setq files (list files)))
13761       (cond
13762        ((eq (car desc) :tag)
13763         (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
13764        ((eq (car desc) :todo)
13765         (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
13766        ((eq (car desc) :regexp)
13767         (setq descre (cdr desc)))
13768        ((eq (car desc) :level)
13769         (setq descre (concat "^\\*\\{" (number-to-string
13770                                         (if org-odd-levels-only
13771                                             (1- (* 2 (cdr desc)))
13772                                           (cdr desc)))
13773                              "\\}[ \t]")))
13774        ((eq (car desc) :maxlevel)
13775         (setq descre (concat "^\\*\\{1," (number-to-string
13776                                         (if org-odd-levels-only
13777                                             (1- (* 2 (cdr desc)))
13778                                           (cdr desc)))
13779                              "\\}[ \t]")))
13780        (t (error "Bad refiling target description %s" desc)))
13781       (while (setq f (pop files))
13782         (save-excursion
13783           (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
13784           (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
13785           (save-excursion
13786             (save-restriction
13787               (widen)
13788               (goto-char (point-min))
13789               (while (re-search-forward descre nil t)
13790                 (goto-char (point-at-bol))
13791                 (when (looking-at org-complex-heading-regexp)
13792                   (setq txt (match-string 4)
13793                         re (concat "^" (regexp-quote
13794                                         (buffer-substring (match-beginning 1)
13795                                                           (match-end 4)))))
13796                   (if (match-end 5) (setq re (concat re "[ \t]+"
13797                                                      (regexp-quote
13798                                                       (match-string 5)))))
13799                   (setq re (concat re "[ \t]*$"))
13800                   (when org-refile-use-outline-path
13801                     (setq txt (mapconcat 'identity
13802                                          (append
13803                                           (if (eq org-refile-use-outline-path 'file)
13804                                               (list (file-name-nondirectory
13805                                                      (buffer-file-name (buffer-base-buffer))))
13806                                             (if (eq org-refile-use-outline-path 'full-file-path)
13807                                                 (list (buffer-file-name (buffer-base-buffer)))))
13808                                           (org-get-outline-path)
13809                                           (list txt))
13810                                          "/")))
13811                   (push (list txt f re (point)) targets))
13812                 (goto-char (point-at-eol))))))))
13813     (org-release-buffers org-agenda-new-buffers)
13814     (nreverse targets)))
13816 (defun org-get-outline-path ()
13817   (let (rtn)
13818     (save-excursion
13819       (while (org-up-heading-safe)
13820         (when (looking-at org-complex-heading-regexp)
13821           (push (org-match-string-no-properties 4) rtn)))
13822       rtn)))
13824 (defvar org-refile-history nil
13825   "History for refiling operations.")
13827 (defun org-refile (&optional reversed-or-update)
13828   "Move the entry at point to another heading.
13829 The list of target headings is compiled using the information in
13830 `org-refile-targets', which see.  This list is created upon first use, and
13831 you can update it by calling this command with a double prefix (`C-u C-u').
13833 At the target location, the entry is filed as a subitem of the target heading.
13834 Depending on `org-reverse-note-order', the new subitem will either be the
13835 first of the last subitem.  A single C-u prefix will toggle the value of this
13836 variable for the duration of the command."
13837   (interactive "P")
13838   (if (equal reversed-or-update '(16))
13839       (progn
13840         (setq org-refile-target-table (org-get-refile-targets))
13841         (message "Refile targets updated (%d targets)"
13842                  (length org-refile-target-table)))
13843     (when (or (not org-refile-target-table)
13844               (and (= (length org-refile-targets) 1)
13845                    (not (caar org-refile-targets))))
13846       (setq org-refile-target-table (org-get-refile-targets)))
13847     (unless org-refile-target-table
13848       (error "No refile targets"))
13849     (let* ((cbuf (current-buffer))
13850            (filename (buffer-file-name (buffer-base-buffer cbuf)))
13851            (fname (and filename (file-truename filename)))
13852            (tbl (mapcar
13853                  (lambda (x)
13854                    (if (not (equal fname (file-truename (nth 1 x))))
13855                        (cons (concat (car x) " (" (file-name-nondirectory
13856                                                    (nth 1 x)) ")")
13857                              (cdr x))
13858                      x))
13859                  org-refile-target-table))
13860            (completion-ignore-case t)
13861            pos it nbuf file re level reversed)
13862       (when (setq it (completing-read "Refile to: " tbl
13863                                       nil t nil 'org-refile-history))
13864         (setq it (assoc it tbl)
13865               file (nth 1 it)
13866               re (nth 2 it))
13867         (org-copy-special)
13868         (save-excursion
13869           (set-buffer (setq nbuf (or (find-buffer-visiting file)
13870                                      (find-file-noselect file))))
13871           (setq reversed (org-notes-order-reversed-p))
13872           (if (equal reversed-or-update '(16)) (setq reversed (not reversed)))
13873           (save-excursion
13874             (save-restriction
13875               (widen)
13876               (goto-char (point-min))
13877               (unless (re-search-forward re nil t)
13878                 (error "Cannot find target location - try again with `C-u' prefix."))
13879               (goto-char (match-beginning 0))
13880               (looking-at outline-regexp)
13881               (setq level (org-get-legal-level (funcall outline-level) 1))
13882               (goto-char (or (save-excursion
13883                                (if reversed
13884                                    (outline-next-heading)
13885                                  (outline-get-next-sibling)))
13886                              (point-max)))
13887               (org-paste-subtree level))))
13888         (org-cut-special)
13889         (message "Entry refiled to \"%s\"" (car it))))))
13891 ;;;; Dynamic blocks
13893 (defun org-find-dblock (name)
13894   "Find the first dynamic block with name NAME in the buffer.
13895 If not found, stay at current position and return nil."
13896   (let (pos)
13897     (save-excursion
13898       (goto-char (point-min))
13899       (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
13900                                         nil t)
13901                      (match-beginning 0))))
13902     (if pos (goto-char pos))
13903     pos))
13905 (defconst org-dblock-start-re
13906   "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
13907   "Matches the startline of a dynamic block, with parameters.")
13909 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
13910   "Matches the end of a dyhamic block.")
13912 (defun org-create-dblock (plist)
13913   "Create a dynamic block section, with parameters taken from PLIST.
13914 PLIST must containe a :name entry which is used as name of the block."
13915   (unless (bolp) (newline))
13916   (let ((name (plist-get plist :name)))
13917     (insert "#+BEGIN: " name)
13918     (while plist
13919       (if (eq (car plist) :name)
13920           (setq plist (cddr plist))
13921         (insert " " (prin1-to-string (pop plist)))))
13922     (insert "\n\n#+END:\n")
13923     (beginning-of-line -2)))
13925 (defun org-prepare-dblock ()
13926   "Prepare dynamic block for refresh.
13927 This empties the block, puts the cursor at the insert position and returns
13928 the property list including an extra property :name with the block name."
13929   (unless (looking-at org-dblock-start-re)
13930     (error "Not at a dynamic block"))
13931   (let* ((begdel (1+ (match-end 0)))
13932          (name (org-no-properties (match-string 1)))
13933          (params (append (list :name name)
13934                          (read (concat "(" (match-string 3) ")")))))
13935     (unless (re-search-forward org-dblock-end-re nil t)
13936       (error "Dynamic block not terminated"))
13937     (delete-region begdel (match-beginning 0))
13938     (goto-char begdel)
13939     (open-line 1)
13940     params))
13942 (defun org-map-dblocks (&optional command)
13943   "Apply COMMAND to all dynamic blocks in the current buffer.
13944 If COMMAND is not given, use `org-update-dblock'."
13945   (let ((cmd (or command 'org-update-dblock))
13946         pos)
13947     (save-excursion
13948       (goto-char (point-min))
13949       (while (re-search-forward org-dblock-start-re nil t)
13950         (goto-char (setq pos (match-beginning 0)))
13951         (condition-case nil
13952             (funcall cmd)
13953           (error (message "Error during update of dynamic block")))
13954         (goto-char pos)
13955         (unless (re-search-forward org-dblock-end-re nil t)
13956           (error "Dynamic block not terminated"))))))
13958 (defun org-dblock-update (&optional arg)
13959   "User command for updating dynamic blocks.
13960 Update the dynamic block at point.  With prefix ARG, update all dynamic
13961 blocks in the buffer."
13962   (interactive "P")
13963   (if arg
13964       (org-update-all-dblocks)
13965     (or (looking-at org-dblock-start-re)
13966         (org-beginning-of-dblock))
13967     (org-update-dblock)))
13969 (defun org-update-dblock ()
13970   "Update the dynamic block at point
13971 This means to empty the block, parse for parameters and then call
13972 the correct writing function."
13973   (save-window-excursion
13974     (let* ((pos (point))
13975            (line (org-current-line))
13976            (params (org-prepare-dblock))
13977            (name (plist-get params :name))
13978            (cmd (intern (concat "org-dblock-write:" name))))
13979       (message "Updating dynamic block `%s' at line %d..." name line)
13980       (funcall cmd params)
13981       (message "Updating dynamic block `%s' at line %d...done" name line)
13982       (goto-char pos))))
13984 (defun org-beginning-of-dblock ()
13985   "Find the beginning of the dynamic block at point.
13986 Error if there is no scuh block at point."
13987   (let ((pos (point))
13988         beg)
13989     (end-of-line 1)
13990     (if (and (re-search-backward org-dblock-start-re nil t)
13991              (setq beg (match-beginning 0))
13992              (re-search-forward org-dblock-end-re nil t)
13993              (> (match-end 0) pos))
13994         (goto-char beg)
13995       (goto-char pos)
13996       (error "Not in a dynamic block"))))
13998 (defun org-update-all-dblocks ()
13999   "Update all dynamic blocks in the buffer.
14000 This function can be used in a hook."
14001   (when (org-mode-p)
14002     (org-map-dblocks 'org-update-dblock)))
14005 ;;;; Completion
14007 (defconst org-additional-option-like-keywords
14008   '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14009     "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14010     "BEGIN_EXAMPLE" "END_EXAMPLE"))
14012 (defun org-complete (&optional arg)
14013   "Perform completion on word at point.
14014 At the beginning of a headline, this completes TODO keywords as given in
14015 `org-todo-keywords'.
14016 If the current word is preceded by a backslash, completes the TeX symbols
14017 that are supported for HTML support.
14018 If the current word is preceded by \"#+\", completes special words for
14019 setting file options.
14020 In the line after \"#+STARTUP:, complete valid keywords.\"
14021 At all other locations, this simply calls the value of
14022 `org-completion-fallback-command'."
14023   (interactive "P")
14024   (org-without-partial-completion
14025    (catch 'exit
14026      (let* ((end (point))
14027             (beg1 (save-excursion
14028                     (skip-chars-backward (org-re "[:alnum:]_@"))
14029                     (point)))
14030             (beg (save-excursion
14031                    (skip-chars-backward "a-zA-Z0-9_:$")
14032                    (point)))
14033             (confirm (lambda (x) (stringp (car x))))
14034             (searchhead (equal (char-before beg) ?*))
14035             (tag (and (equal (char-before beg1) ?:)
14036                       (equal (char-after (point-at-bol)) ?*)))
14037             (prop (and (equal (char-before beg1) ?:)
14038                        (not (equal (char-after (point-at-bol)) ?*))))
14039             (texp (equal (char-before beg) ?\\))
14040             (link (equal (char-before beg) ?\[))
14041             (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14042                                           beg)
14043                         "#+"))
14044             (startup (string-match "^#\\+STARTUP:.*"
14045                                    (buffer-substring (point-at-bol) (point))))
14046             (completion-ignore-case opt)
14047             (type nil)
14048             (tbl nil)
14049             (table (cond
14050                     (opt
14051                      (setq type :opt)
14052                      (append
14053                       (mapcar
14054                        (lambda (x)
14055                          (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14056                          (cons (match-string 2 x) (match-string 1 x)))
14057                        (org-split-string (org-get-current-options) "\n"))
14058                       (mapcar 'list org-additional-option-like-keywords)))
14059                     (startup
14060                      (setq type :startup)
14061                      org-startup-options)
14062                     (link (append org-link-abbrev-alist-local
14063                                   org-link-abbrev-alist))
14064                     (texp
14065                      (setq type :tex)
14066                      org-html-entities)
14067                     ((string-match "\\`\\*+[ \t]+\\'"
14068                                    (buffer-substring (point-at-bol) beg))
14069                      (setq type :todo)
14070                      (mapcar 'list org-todo-keywords-1))
14071                     (searchhead
14072                      (setq type :searchhead)
14073                      (save-excursion
14074                        (goto-char (point-min))
14075                        (while (re-search-forward org-todo-line-regexp nil t)
14076                          (push (list
14077                                 (org-make-org-heading-search-string
14078                                  (match-string 3) t))
14079                                tbl)))
14080                      tbl)
14081                     (tag (setq type :tag beg beg1)
14082                          (or org-tag-alist (org-get-buffer-tags)))
14083                     (prop (setq type :prop beg beg1)
14084                           (mapcar 'list (org-buffer-property-keys)))
14085                     (t (progn
14086                          (call-interactively org-completion-fallback-command)
14087                          (throw 'exit nil)))))
14088             (pattern (buffer-substring-no-properties beg end))
14089             (completion (try-completion pattern table confirm)))
14090        (cond ((eq completion t)
14091               (if (not (assoc (upcase pattern) table))
14092                   (message "Already complete")
14093                 (if (equal type :opt)
14094                     (insert (substring (cdr (assoc (upcase pattern) table))
14095                                        (length pattern)))
14096                   (if (memq type '(:tag :prop)) (insert ":")))))
14097              ((null completion)
14098               (message "Can't find completion for \"%s\"" pattern)
14099               (ding))
14100              ((not (string= pattern completion))
14101               (delete-region beg end)
14102               (if (string-match " +$" completion)
14103                   (setq completion (replace-match "" t t completion)))
14104               (insert completion)
14105               (if (get-buffer-window "*Completions*")
14106                   (delete-window (get-buffer-window "*Completions*")))
14107               (if (assoc completion table)
14108                   (if (eq type :todo) (insert " ")
14109                     (if (memq type '(:tag :prop)) (insert ":"))))
14110               (if (and (equal type :opt) (assoc completion table))
14111                   (message "%s" (substitute-command-keys
14112                                  "Press \\[org-complete] again to insert example settings"))))
14113              (t
14114               (message "Making completion list...")
14115               (let ((list (sort (all-completions pattern table confirm)
14116                                 'string<)))
14117                 (with-output-to-temp-buffer "*Completions*"
14118                   (condition-case nil
14119                       ;; Protection needed for XEmacs and emacs 21
14120                       (display-completion-list list pattern)
14121                     (error (display-completion-list list)))))
14122               (message "Making completion list...%s" "done")))))))
14124 ;;;; TODO, DEADLINE, Comments
14126 (defun org-toggle-comment ()
14127   "Change the COMMENT state of an entry."
14128   (interactive)
14129   (save-excursion
14130     (org-back-to-heading)
14131     (let (case-fold-search)
14132       (if (looking-at (concat outline-regexp
14133                               "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14134           (replace-match "" t t nil 1)
14135         (if (looking-at outline-regexp)
14136             (progn
14137               (goto-char (match-end 0))
14138               (insert org-comment-string " ")))))))
14140 (defvar org-last-todo-state-is-todo nil
14141   "This is non-nil when the last TODO state change led to a TODO state.
14142 If the last change removed the TODO tag or switched to DONE, then
14143 this is nil.")
14145 (defvar org-setting-tags nil) ; dynamically skiped
14147 ;; FIXME: better place
14148 (defun org-property-or-variable-value (var &optional inherit)
14149   "Check if there is a property fixing the value of VAR.
14150 If yes, return this value.  If not, return the current value of the variable."
14151   (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14152     (if (and prop (stringp prop) (string-match "\\S-" prop))
14153         (read prop)
14154       (symbol-value var))))
14156 (defun org-parse-local-options (string var)
14157   "Parse STRING for startup setting relevant for variable VAR."
14158   (let ((rtn (symbol-value var))
14159         e opts)
14160     (save-match-data
14161       (if (or (not string) (not (string-match "\\S-" string)))
14162           rtn
14163         (setq opts (delq nil (mapcar (lambda (x)
14164                                        (setq e (assoc x org-startup-options))
14165                                        (if (eq (nth 1 e) var) e nil))
14166                                      (org-split-string string "[ \t]+"))))
14167         (if (not opts)
14168             rtn
14169           (setq rtn nil)
14170           (while (setq e (pop opts))
14171             (if (not (nth 3 e))
14172                 (setq rtn (nth 2 e))
14173               (if (not (listp rtn)) (setq rtn nil))
14174               (push (nth 2 e) rtn)))
14175           rtn)))))
14177 (defvar org-blocker-hook nil
14178   "Hook for functions that are allowed to block a state change.
14180 Each function gets as its single argument a property list, see
14181 `org-trigger-hook' for more information about this list.
14183 If any of the functions in this hook returns nil, the state change
14184 is blocked.")
14186 (defvar org-trigger-hook nil
14187   "Hook for functions that are triggered by a state change.
14189 Each function gets as its single argument a property list with at least
14190 the following elements:
14192  (:type type-of-change :position pos-at-entry-start
14193   :from old-state :to new-state)
14195 Depending on the type, more properties may be present.
14197 This mechanism is currently implemented for:
14199 TODO state changes
14200 ------------------
14201 :type  todo-state-change
14202 :from  previous state (keyword as a string), or nil
14203 :to    new state (keyword as a string), or nil")
14206 (defun org-todo (&optional arg)
14207   "Change the TODO state of an item.
14208 The state of an item is given by a keyword at the start of the heading,
14209 like
14210      *** TODO Write paper
14211      *** DONE Call mom
14213 The different keywords are specified in the variable `org-todo-keywords'.
14214 By default the available states are \"TODO\" and \"DONE\".
14215 So for this example: when the item starts with TODO, it is changed to DONE.
14216 When it starts with DONE, the DONE is removed.  And when neither TODO nor
14217 DONE are present, add TODO at the beginning of the heading.
14219 With C-u prefix arg, use completion to determine the new state.
14220 With numeric prefix arg, switch to that state.
14222 For calling through lisp, arg is also interpreted in the following way:
14223 'none             -> empty state
14224 \"\"(empty string)  -> switch to empty state
14225 'done             -> switch to DONE
14226 'nextset          -> switch to the next set of keywords
14227 'previousset      -> switch to the previous set of keywords
14228 \"WAITING\"         -> switch to the specified keyword, but only if it
14229                      really is a member of `org-todo-keywords'."
14230   (interactive "P")
14231   (save-excursion
14232     (catch 'exit
14233       (org-back-to-heading)
14234       (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14235       (or (looking-at (concat " +" org-todo-regexp " *"))
14236           (looking-at " *"))
14237       (let* ((match-data (match-data))
14238              (startpos (point-at-bol))
14239              (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14240              (org-log-done (org-parse-local-options logging 'org-log-done))
14241              (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
14242              (this (match-string 1))
14243              (hl-pos (match-beginning 0))
14244              (head (org-get-todo-sequence-head this))
14245              (ass (assoc head org-todo-kwd-alist))
14246              (interpret (nth 1 ass))
14247              (done-word (nth 3 ass))
14248              (final-done-word (nth 4 ass))
14249              (last-state (or this ""))
14250              (completion-ignore-case t)
14251              (member (member this org-todo-keywords-1))
14252              (tail (cdr member))
14253              (state (cond
14254                      ((and org-todo-key-trigger
14255                            (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14256                                (and (not arg) org-use-fast-todo-selection
14257                                     (not (eq org-use-fast-todo-selection 'prefix)))))
14258                       ;; Use fast selection
14259                       (org-fast-todo-selection))
14260                      ((and (equal arg '(4))
14261                            (or (not org-use-fast-todo-selection)
14262                                (not org-todo-key-trigger)))
14263                       ;; Read a state with completion
14264                       (completing-read "State: " (mapcar (lambda(x) (list x))
14265                                                          org-todo-keywords-1)
14266                                        nil t))
14267                      ((eq arg 'right)
14268                       (if this
14269                           (if tail (car tail) nil)
14270                         (car org-todo-keywords-1)))
14271                      ((eq arg 'left)
14272                       (if (equal member org-todo-keywords-1)
14273                           nil
14274                         (if this
14275                             (nth (- (length org-todo-keywords-1) (length tail) 2)
14276                                  org-todo-keywords-1)
14277                           (org-last org-todo-keywords-1))))
14278                      ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14279                            (setq arg nil))) ; hack to fall back to cycling
14280                      (arg
14281                       ;; user or caller requests a specific state
14282                       (cond
14283                        ((equal arg "") nil)
14284                        ((eq arg 'none) nil)
14285                        ((eq arg 'done) (or done-word (car org-done-keywords)))
14286                        ((eq arg 'nextset)
14287                         (or (car (cdr (member head org-todo-heads)))
14288                             (car org-todo-heads)))
14289                        ((eq arg 'previousset)
14290                         (let ((org-todo-heads (reverse org-todo-heads)))
14291                           (or (car (cdr (member head org-todo-heads)))
14292                               (car org-todo-heads))))
14293                        ((car (member arg org-todo-keywords-1)))
14294                        ((nth (1- (prefix-numeric-value arg))
14295                              org-todo-keywords-1))))
14296                      ((null member) (or head (car org-todo-keywords-1)))
14297                      ((equal this final-done-word) nil) ;; -> make empty
14298                      ((null tail) nil) ;; -> first entry
14299                      ((eq interpret 'sequence)
14300                       (car tail))
14301                      ((memq interpret '(type priority))
14302                       (if (eq this-command last-command)
14303                           (car tail)
14304                         (if (> (length tail) 0)
14305                             (or done-word (car org-done-keywords))
14306                           nil)))
14307                      (t nil)))
14308              (next (if state (concat " " state " ") " "))
14309              (change-plist (list :type 'todo-state-change :from this :to state
14310                                  :position startpos))
14311              dostates)
14312         (when org-blocker-hook
14313           (unless (save-excursion
14314                     (save-match-data
14315                       (run-hook-with-args-until-failure
14316                        'org-blocker-hook change-plist)))
14317             (if (interactive-p)
14318                 (error "TODO state change from %s to %s blocked" this state)
14319               ;; fail silently
14320               (message "TODO state change from %s to %s blocked" this state)
14321               (throw 'exit nil))))
14322         (store-match-data match-data)
14323         (replace-match next t t)
14324         (unless (pos-visible-in-window-p hl-pos)
14325           (message "TODO state changed to %s" (org-trim next)))
14326         (unless head
14327           (setq head (org-get-todo-sequence-head state)
14328                 ass (assoc head org-todo-kwd-alist)
14329                 interpret (nth 1 ass)
14330                 done-word (nth 3 ass)
14331                 final-done-word (nth 4 ass)))
14332         (when (memq arg '(nextset previousset))
14333           (message "Keyword-Set %d/%d: %s"
14334                    (- (length org-todo-sets) -1
14335                       (length (memq (assoc state org-todo-sets) org-todo-sets)))
14336                    (length org-todo-sets)
14337                    (mapconcat 'identity (assoc state org-todo-sets) " ")))
14338         (setq org-last-todo-state-is-todo
14339               (not (member state org-done-keywords)))
14340         (when (and org-log-done (not (memq arg '(nextset previousset))))
14341           (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
14342                               (or (not org-todo-log-states)
14343                                   (member state org-todo-log-states))))
14345           (cond
14346            ((and state (member state org-not-done-keywords)
14347                  (not (member this org-not-done-keywords)))
14348             ;; This is now a todo state and was not one before
14349             ;; Remove any CLOSED timestamp, and possibly log the state change
14350             (org-add-planning-info nil nil 'closed)
14351             (and dostates (org-add-log-maybe 'state state 'findpos)))
14352            ((and state dostates)
14353             ;; This is a non-nil state, and we need to log it
14354             (org-add-log-maybe 'state state 'findpos))
14355            ((and (member state org-done-keywords)
14356                  (not (member this org-done-keywords)))
14357             ;; It is now done, and it was not done before
14358             (org-add-planning-info 'closed (org-current-time))
14359             (org-add-log-maybe 'done state 'findpos))))
14360         ;; Fixup tag positioning
14361         (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14362         (run-hooks 'org-after-todo-state-change-hook)
14363         (and (member state org-done-keywords) (org-auto-repeat-maybe))
14364         (if (and arg (not (member state org-done-keywords)))
14365             (setq head (org-get-todo-sequence-head state)))
14366         (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14367         ;; Fixup cursor location if close to the keyword
14368         (if (and (outline-on-heading-p)
14369                  (not (bolp))
14370                  (save-excursion (beginning-of-line 1)
14371                                  (looking-at org-todo-line-regexp))
14372                  (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14373             (progn
14374               (goto-char (or (match-end 2) (match-end 1)))
14375               (just-one-space)))
14376         (when org-trigger-hook
14377           (save-excursion
14378             (run-hook-with-args 'org-trigger-hook change-plist)))))))
14380 (defun org-get-todo-sequence-head (kwd)
14381   "Return the head of the TODO sequence to which KWD belongs.
14382 If KWD is not set, check if there is a text property remembering the
14383 right sequence."
14384   (let (p)
14385     (cond
14386      ((not kwd)
14387       (or (get-text-property (point-at-bol) 'org-todo-head)
14388           (progn
14389             (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14390                                                  nil (point-at-eol)))
14391             (get-text-property p 'org-todo-head))))
14392      ((not (member kwd org-todo-keywords-1))
14393       (car org-todo-keywords-1))
14394      (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14396 (defun org-fast-todo-selection ()
14397   "Fast TODO keyword selection with single keys.
14398 Returns the new TODO keyword, or nil if no state change should occur."
14399   (let* ((fulltable org-todo-key-alist)
14400          (done-keywords org-done-keywords) ;; needed for the faces.
14401          (maxlen (apply 'max (mapcar
14402                               (lambda (x)
14403                                 (if (stringp (car x)) (string-width (car x)) 0))
14404                               fulltable)))
14405          (expert nil)
14406          (fwidth (+ maxlen 3 1 3))
14407          (ncol (/ (- (window-width) 4) fwidth))
14408          tg cnt e c tbl
14409          groups ingroup)
14410     (save-window-excursion
14411       (if expert
14412           (set-buffer (get-buffer-create " *Org todo*"))
14413         (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14414       (erase-buffer)
14415       (org-set-local 'org-done-keywords done-keywords)
14416       (setq tbl fulltable cnt 0)
14417       (while (setq e (pop tbl))
14418         (cond
14419          ((equal e '(:startgroup))
14420           (push '() groups) (setq ingroup t)
14421           (when (not (= cnt 0))
14422             (setq cnt 0)
14423             (insert "\n"))
14424           (insert "{ "))
14425          ((equal e '(:endgroup))
14426           (setq ingroup nil cnt 0)
14427           (insert "}\n"))
14428          (t
14429           (setq tg (car e) c (cdr e))
14430           (if ingroup (push tg (car groups)))
14431           (setq tg (org-add-props tg nil 'face
14432                                   (org-get-todo-face tg)))
14433           (if (and (= cnt 0) (not ingroup)) (insert "  "))
14434           (insert "[" c "] " tg (make-string
14435                                  (- fwidth 4 (length tg)) ?\ ))
14436           (when (= (setq cnt (1+ cnt)) ncol)
14437             (insert "\n")
14438             (if ingroup (insert "  "))
14439             (setq cnt 0)))))
14440       (insert "\n")
14441       (goto-char (point-min))
14442       (if (and (not expert) (fboundp 'fit-window-to-buffer))
14443           (fit-window-to-buffer))
14444       (message "[a-z..]:Set [SPC]:clear")
14445       (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14446       (cond
14447        ((or (= c ?\C-g)
14448             (and (= c ?q) (not (rassoc c fulltable))))
14449         (setq quit-flag t))
14450        ((= c ?\ ) nil)
14451        ((setq e (rassoc c fulltable) tg (car e))
14452         tg)
14453        (t (setq quit-flag t))))))
14455 (defun org-get-repeat ()
14456   "Check if tere is a deadline/schedule with repeater in this entry."
14457   (save-match-data
14458     (save-excursion
14459       (org-back-to-heading t)
14460       (if (re-search-forward
14461            org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14462           (match-string 1)))))
14464 (defvar org-last-changed-timestamp)
14465 (defvar org-log-post-message)
14466 (defun org-auto-repeat-maybe ()
14467   "Check if the current headline contains a repeated deadline/schedule.
14468 If yes, set TODO state back to what it was and change the base date
14469 of repeating deadline/scheduled time stamps to new date.
14470 This function should be run in the `org-after-todo-state-change-hook'."
14471   ;; last-state is dynamically scoped into this function
14472   (let* ((repeat (org-get-repeat))
14473          (aa (assoc last-state org-todo-kwd-alist))
14474          (interpret (nth 1 aa))
14475          (head (nth 2 aa))
14476          (done-word (nth 3 aa))
14477          (whata '(("d" . day) ("m" . month) ("y" . year)))
14478          (msg "Entry repeats: ")
14479          (org-log-done)
14480          re type n what ts)
14481     (when repeat
14482       (org-todo (if (eq interpret 'type) last-state head))
14483       (when (and org-log-repeat
14484                  (not (memq 'org-add-log-note
14485                             (default-value 'post-command-hook))))
14486         ;; Make sure a note is taken
14487         (let ((org-log-done '(done)))
14488           (org-add-log-maybe 'done (or done-word (car org-done-keywords))
14489                              'findpos)))
14490       (org-back-to-heading t)
14491       (org-add-planning-info nil nil 'closed)
14492       (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14493                        org-deadline-time-regexp "\\)"))
14494       (while (re-search-forward
14495               re (save-excursion (outline-next-heading) (point)) t)
14496         (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
14497               ts (match-string (if (match-end 2) 2 4)))
14498         (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14499           (setq n (string-to-number (match-string 1 ts))
14500                 what (match-string 2 ts))
14501           (if (equal what "w") (setq n (* n 7) what "d"))
14502           (org-timestamp-change n (cdr (assoc what whata))))
14503         (setq msg (concat msg type org-last-changed-timestamp " ")))
14504       (setq org-log-post-message msg)
14505       (message "%s" msg))))
14507 (defun org-show-todo-tree (arg)
14508   "Make a compact tree which shows all headlines marked with TODO.
14509 The tree will show the lines where the regexp matches, and all higher
14510 headlines above the match.
14511 With \\[universal-argument] prefix, also show the DONE entries.
14512 With a numeric prefix N, construct a sparse tree for the Nth element
14513 of `org-todo-keywords-1'."
14514   (interactive "P")
14515   (let ((case-fold-search nil)
14516         (kwd-re
14517          (cond ((null arg) org-not-done-regexp)
14518                ((equal arg '(4))
14519                 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14520                                             (mapcar 'list org-todo-keywords-1))))
14521                   (concat "\\("
14522                           (mapconcat 'identity (org-split-string kwd "|") "\\|")
14523                           "\\)\\>")))
14524                ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14525                 (regexp-quote (nth (1- (prefix-numeric-value arg))
14526                                    org-todo-keywords-1)))
14527                (t (error "Invalid prefix argument: %s" arg)))))
14528     (message "%d TODO entries found"
14529              (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14531 (defun org-deadline (&optional remove)
14532   "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14533 With argument REMOVE, remove any deadline from the item."
14534   (interactive "P")
14535   (if remove
14536       (progn
14537         (org-add-planning-info nil nil 'deadline)
14538         (message "Item no longer has a deadline."))
14539     (org-add-planning-info 'deadline nil 'closed)))
14541 (defun org-schedule (&optional remove)
14542   "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14543 With argument REMOVE, remove any scheduling date from the item."
14544   (interactive "P")
14545   (if remove
14546       (progn
14547         (org-add-planning-info nil nil 'scheduled)
14548         (message "Item is no longer scheduled."))
14549     (org-add-planning-info 'scheduled nil 'closed)))
14551 (defun org-add-planning-info (what &optional time &rest remove)
14552   "Insert new timestamp with keyword in the line directly after the headline.
14553 WHAT indicates what kind of time stamp to add.  TIME indicated the time to use.
14554 If non is given, the user is prompted for a date.
14555 REMOVE indicates what kind of entries to remove.  An old WHAT entry will also
14556 be removed."
14557   (interactive)
14558   (let (org-time-was-given org-end-time-was-given)
14559     (when what (setq time (or time (org-read-date nil 'to-time))))
14560     (when (and org-insert-labeled-timestamps-at-point
14561                (member what '(scheduled deadline)))
14562       (insert
14563        (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14564       (org-insert-time-stamp time org-time-was-given
14565                              nil nil nil (list org-end-time-was-given))
14566       (setq what nil))
14567     (save-excursion
14568       (save-restriction
14569         (let (col list elt ts buffer-invisibility-spec)
14570           (org-back-to-heading t)
14571           (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14572           (goto-char (match-end 1))
14573           (setq col (current-column))
14574           (goto-char (match-end 0))
14575           (if (eobp) (insert "\n") (forward-char 1))
14576           (if (and (not (looking-at outline-regexp))
14577                    (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14578                                        "[^\r\n]*"))
14579                    (not (equal (match-string 1) org-clock-string)))
14580               (narrow-to-region (match-beginning 0) (match-end 0))
14581             (insert-before-markers "\n")
14582             (backward-char 1)
14583             (narrow-to-region (point) (point))
14584             (indent-to-column col))
14585           ;; Check if we have to remove something.
14586           (setq list (cons what remove))
14587           (while list
14588             (setq elt (pop list))
14589             (goto-char (point-min))
14590             (when (or (and (eq elt 'scheduled)
14591                            (re-search-forward org-scheduled-time-regexp nil t))
14592                       (and (eq elt 'deadline)
14593                            (re-search-forward org-deadline-time-regexp nil t))
14594                       (and (eq elt 'closed)
14595                            (re-search-forward org-closed-time-regexp nil t)))
14596               (replace-match "")
14597               (if (looking-at "--+<[^>]+>") (replace-match ""))
14598               (if (looking-at " +") (replace-match ""))))
14599           (goto-char (point-max))
14600           (when what
14601             (insert
14602              (if (not (equal (char-before) ?\ )) " " "")
14603              (cond ((eq what 'scheduled) org-scheduled-string)
14604                    ((eq what 'deadline) org-deadline-string)
14605                    ((eq what 'closed) org-closed-string))
14606              " ")
14607             (setq ts (org-insert-time-stamp
14608                       time
14609                       (or org-time-was-given
14610                           (and (eq what 'closed) org-log-done-with-time))
14611                       (eq what 'closed)
14612                       nil nil (list org-end-time-was-given)))
14613             (end-of-line 1))
14614           (goto-char (point-min))
14615           (widen)
14616           (if (looking-at "[ \t]+\r?\n")
14617               (replace-match ""))
14618           ts)))))
14620 (defvar org-log-note-marker (make-marker))
14621 (defvar org-log-note-purpose nil)
14622 (defvar org-log-note-state nil)
14623 (defvar org-log-note-window-configuration nil)
14624 (defvar org-log-note-return-to (make-marker))
14625 (defvar org-log-post-message nil
14626   "Message to be displayed after a log note has been stored.
14627 The auto-repeater uses this.")
14629 (defun org-add-log-maybe (&optional purpose state findpos)
14630   "Set up the post command hook to take a note."
14631   (save-excursion
14632     (when (and (listp org-log-done)
14633                (memq purpose org-log-done))
14634       (when findpos
14635         (org-back-to-heading t)
14636         (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14637                             "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14638                             "[^\r\n]*\\)?"))
14639         (goto-char (match-end 0))
14640         (unless org-log-states-order-reversed
14641           (and (= (char-after) ?\n) (forward-char 1))
14642           (org-skip-over-state-notes)
14643           (skip-chars-backward " \t\n\r")))
14644       (move-marker org-log-note-marker (point))
14645       (setq org-log-note-purpose purpose)
14646       (setq org-log-note-state state)
14647       (add-hook 'post-command-hook 'org-add-log-note 'append))))
14649 (defun org-skip-over-state-notes ()
14650   "Skip past the list of State notes in an entry."
14651   (if (looking-at "\n[ \t]*- State") (forward-char 1))
14652   (while (looking-at "[ \t]*- State")
14653     (condition-case nil
14654         (org-next-item)
14655       (error (org-end-of-item)))))
14657 (defun org-add-log-note (&optional purpose)
14658   "Pop up a window for taking a note, and add this note later at point."
14659   (remove-hook 'post-command-hook 'org-add-log-note)
14660   (setq org-log-note-window-configuration (current-window-configuration))
14661   (delete-other-windows)
14662   (move-marker org-log-note-return-to (point))
14663   (switch-to-buffer (marker-buffer org-log-note-marker))
14664   (goto-char org-log-note-marker)
14665   (org-switch-to-buffer-other-window "*Org Note*")
14666   (erase-buffer)
14667   (let ((org-inhibit-startup t)) (org-mode))
14668   (insert (format "# Insert note for %s.
14669 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14670                   (cond
14671                    ((eq org-log-note-purpose 'clock-out) "stopped clock")
14672                    ((eq org-log-note-purpose 'done)  "closed todo item")
14673                    ((eq org-log-note-purpose 'state)
14674                     (format "state change to \"%s\"" org-log-note-state))
14675                    (t (error "This should not happen")))))
14676   (org-set-local 'org-finish-function 'org-store-log-note))
14678 (defun org-store-log-note ()
14679   "Finish taking a log note, and insert it to where it belongs."
14680   (let ((txt (buffer-string))
14681         (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14682         lines ind)
14683     (kill-buffer (current-buffer))
14684     (while (string-match "\\`#.*\n[ \t\n]*" txt)
14685       (setq txt (replace-match "" t t txt)))
14686     (if (string-match "\\s-+\\'" txt)
14687         (setq txt (replace-match "" t t txt)))
14688     (setq lines (org-split-string txt "\n"))
14689     (when (and note (string-match "\\S-" note))
14690       (setq note
14691             (org-replace-escapes
14692              note
14693              (list (cons "%u" (user-login-name))
14694                    (cons "%U" user-full-name)
14695                    (cons "%t" (format-time-string
14696                                (org-time-stamp-format 'long 'inactive)
14697                                (current-time)))
14698                    (cons "%s" (if org-log-note-state
14699                                   (concat "\"" org-log-note-state "\"")
14700                                 "")))))
14701       (if lines (setq note (concat note " \\\\")))
14702       (push note lines))
14703     (when (or current-prefix-arg org-note-abort) (setq lines nil))
14704     (when lines
14705       (save-excursion
14706         (set-buffer (marker-buffer org-log-note-marker))
14707         (save-excursion
14708           (goto-char org-log-note-marker)
14709           (move-marker org-log-note-marker nil)
14710           (end-of-line 1)
14711           (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
14712           (indent-relative nil)
14713           (insert "- " (pop lines))
14714           (org-indent-line-function)
14715           (beginning-of-line 1)
14716           (looking-at "[ \t]*")
14717           (setq ind (concat (match-string 0) "  "))
14718           (end-of-line 1)
14719           (while lines (insert "\n" ind (pop lines)))))))
14720   (set-window-configuration org-log-note-window-configuration)
14721   (with-current-buffer (marker-buffer org-log-note-return-to)
14722     (goto-char org-log-note-return-to))
14723   (move-marker org-log-note-return-to nil)
14724   (and org-log-post-message (message "%s" org-log-post-message)))
14726 ;; FIXME: what else would be useful?
14727 ;; - priority
14728 ;; - date
14730 (defun org-sparse-tree (&optional arg)
14731   "Create a sparse tree, prompt for the details.
14732 This command can create sparse trees.  You first need to select the type
14733 of match used to create the tree:
14735 t      Show entries with a specific TODO keyword.
14736 T      Show entries selected by a tags match.
14737 p      Enter a property name and its value (both with completion on existing
14738        names/values) and show entries with that property.
14739 r      Show entries matching a regular expression
14740 d      Show deadlines due within `org-deadline-warning-days'."
14741   (interactive "P")
14742   (let (ans kwd value)
14743     (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
14744     (setq ans (read-char-exclusive))
14745     (cond
14746      ((equal ans ?d)
14747       (call-interactively 'org-check-deadlines))
14748      ((equal ans ?b)
14749       (call-interactively 'org-check-before-date))
14750      ((equal ans ?t)
14751       (org-show-todo-tree '(4)))
14752      ((equal ans ?T)
14753       (call-interactively 'org-tags-sparse-tree))
14754      ((member ans '(?p ?P))
14755       (setq kwd (completing-read "Property: "
14756                                  (mapcar 'list (org-buffer-property-keys))))
14757       (setq value (completing-read "Value: "
14758                                    (mapcar 'list (org-property-values kwd))))
14759       (unless (string-match "\\`{.*}\\'" value)
14760         (setq value (concat "\"" value "\"")))
14761       (org-tags-sparse-tree arg (concat kwd "=" value)))
14762      ((member ans '(?r ?R ?/))
14763       (call-interactively 'org-occur))
14764      (t (error "No such sparse tree command \"%c\"" ans)))))
14766 (defvar org-occur-highlights nil)
14767 (make-variable-buffer-local 'org-occur-highlights)
14769 (defun org-occur (regexp &optional keep-previous callback)
14770   "Make a compact tree which shows all matches of REGEXP.
14771 The tree will show the lines where the regexp matches, and all higher
14772 headlines above the match.  It will also show the heading after the match,
14773 to make sure editing the matching entry is easy.
14774 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
14775 call to `org-occur' will be kept, to allow stacking of calls to this
14776 command.
14777 If CALLBACK is non-nil, it is a function which is called to confirm
14778 that the match should indeed be shown."
14779   (interactive "sRegexp: \nP")
14780   (or keep-previous (org-remove-occur-highlights nil nil t))
14781   (let ((cnt 0))
14782     (save-excursion
14783       (goto-char (point-min))
14784       (if (or (not keep-previous)          ; do not want to keep
14785               (not org-occur-highlights))  ; no previous matches
14786           ;; hide everything
14787           (org-overview))
14788       (while (re-search-forward regexp nil t)
14789         (when (or (not callback)
14790                   (save-match-data (funcall callback)))
14791           (setq cnt (1+ cnt))
14792           (when org-highlight-sparse-tree-matches
14793             (org-highlight-new-match (match-beginning 0) (match-end 0)))
14794           (org-show-context 'occur-tree))))
14795     (when org-remove-highlights-with-change
14796       (org-add-hook 'before-change-functions 'org-remove-occur-highlights
14797                     nil 'local))
14798     (unless org-sparse-tree-open-archived-trees
14799       (org-hide-archived-subtrees (point-min) (point-max)))
14800     (run-hooks 'org-occur-hook)
14801     (if (interactive-p)
14802         (message "%d match(es) for regexp %s" cnt regexp))
14803     cnt))
14805 (defun org-show-context (&optional key)
14806   "Make sure point and context and visible.
14807 How much context is shown depends upon the variables
14808 `org-show-hierarchy-above', `org-show-following-heading'. and
14809 `org-show-siblings'."
14810   (let ((heading-p   (org-on-heading-p t))
14811         (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
14812         (following-p (org-get-alist-option org-show-following-heading key))
14813         (entry-p     (org-get-alist-option org-show-entry-below key))
14814         (siblings-p  (org-get-alist-option org-show-siblings key)))
14815     (catch 'exit
14816       ;; Show heading or entry text
14817       (if (and heading-p (not entry-p))
14818           (org-flag-heading nil)    ; only show the heading
14819         (and (or entry-p (org-invisible-p) (org-invisible-p2))
14820              (org-show-hidden-entry)))    ; show entire entry
14821       (when following-p
14822         ;; Show next sibling, or heading below text
14823         (save-excursion
14824           (and (if heading-p (org-goto-sibling) (outline-next-heading))
14825                (org-flag-heading nil))))
14826       (when siblings-p (org-show-siblings))
14827       (when hierarchy-p
14828         ;; show all higher headings, possibly with siblings
14829         (save-excursion
14830           (while (and (condition-case nil
14831                           (progn (org-up-heading-all 1) t)
14832                         (error nil))
14833                       (not (bobp)))
14834             (org-flag-heading nil)
14835             (when siblings-p (org-show-siblings))))))))
14837 (defun org-reveal (&optional siblings)
14838   "Show current entry, hierarchy above it, and the following headline.
14839 This can be used to show a consistent set of context around locations
14840 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
14841 not t for the search context.
14843 With optional argument SIBLINGS, on each level of the hierarchy all
14844 siblings are shown.  This repairs the tree structure to what it would
14845 look like when opened with hierarchical calls to `org-cycle'."
14846   (interactive "P")
14847   (let ((org-show-hierarchy-above t)
14848         (org-show-following-heading t)
14849         (org-show-siblings (if siblings t org-show-siblings)))
14850     (org-show-context nil)))
14852 (defun org-highlight-new-match (beg end)
14853   "Highlight from BEG to END and mark the highlight is an occur headline."
14854   (let ((ov (org-make-overlay beg end)))
14855     (org-overlay-put ov 'face 'secondary-selection)
14856     (push ov org-occur-highlights)))
14858 (defun org-remove-occur-highlights (&optional beg end noremove)
14859   "Remove the occur highlights from the buffer.
14860 BEG and END are ignored.  If NOREMOVE is nil, remove this function
14861 from the `before-change-functions' in the current buffer."
14862   (interactive)
14863   (unless org-inhibit-highlight-removal
14864     (mapc 'org-delete-overlay org-occur-highlights)
14865     (setq org-occur-highlights nil)
14866     (unless noremove
14867       (remove-hook 'before-change-functions
14868                    'org-remove-occur-highlights 'local))))
14870 ;;;; Priorities
14872 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14873   "Regular expression matching the priority indicator.")
14875 (defvar org-remove-priority-next-time nil)
14877 (defun org-priority-up ()
14878   "Increase the priority of the current item."
14879   (interactive)
14880   (org-priority 'up))
14882 (defun org-priority-down ()
14883   "Decrease the priority of the current item."
14884   (interactive)
14885   (org-priority 'down))
14887 (defun org-priority (&optional action)
14888   "Change the priority of an item by ARG.
14889 ACTION can be `set', `up', `down', or a character."
14890   (interactive)
14891   (setq action (or action 'set))
14892   (let (current new news have remove)
14893     (save-excursion
14894       (org-back-to-heading)
14895       (if (looking-at org-priority-regexp)
14896           (setq current (string-to-char (match-string 2))
14897                 have t)
14898         (setq current org-default-priority))
14899       (cond
14900        ((or (eq action 'set) (integerp action))
14901         (if (integerp action)
14902             (setq new action)
14903           (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
14904           (setq new (read-char-exclusive)))
14905         (if (and (= (upcase org-highest-priority) org-highest-priority)
14906                  (= (upcase org-lowest-priority) org-lowest-priority))
14907             (setq new (upcase new)))
14908         (cond ((equal new ?\ ) (setq remove t))
14909               ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14910                (error "Priority must be between `%c' and `%c'"
14911                       org-highest-priority org-lowest-priority))))
14912        ((eq action 'up)
14913         (if (and (not have) (eq last-command this-command))
14914             (setq new org-lowest-priority)
14915           (setq new (if (and org-priority-start-cycle-with-default (not have))
14916                         org-default-priority (1- current)))))
14917        ((eq action 'down)
14918         (if (and (not have) (eq last-command this-command))
14919             (setq new org-highest-priority)
14920           (setq new (if (and org-priority-start-cycle-with-default (not have))
14921                         org-default-priority (1+ current)))))
14922        (t (error "Invalid action")))
14923       (if (or (< (upcase new) org-highest-priority)
14924               (> (upcase new) org-lowest-priority))
14925           (setq remove t))
14926       (setq news (format "%c" new))
14927       (if have
14928           (if remove
14929               (replace-match "" t t nil 1)
14930             (replace-match news t t nil 2))
14931         (if remove
14932             (error "No priority cookie found in line")
14933           (looking-at org-todo-line-regexp)
14934           (if (match-end 2)
14935               (progn
14936                 (goto-char (match-end 2))
14937                 (insert " [#" news "]"))
14938             (goto-char (match-beginning 3))
14939             (insert "[#" news "] ")))))
14940     (org-preserve-lc (org-set-tags nil 'align))
14941     (if remove
14942         (message "Priority removed")
14943       (message "Priority of current item set to %s" news))))
14946 (defun org-get-priority (s)
14947   "Find priority cookie and return priority."
14948   (save-match-data
14949     (if (not (string-match org-priority-regexp s))
14950         (* 1000 (- org-lowest-priority org-default-priority))
14951       (* 1000 (- org-lowest-priority
14952                  (string-to-char (match-string 2 s)))))))
14954 ;;;; Tags
14956 (defun org-scan-tags (action matcher &optional todo-only)
14957   "Scan headline tags with inheritance and produce output ACTION.
14958 ACTION can be `sparse-tree' or `agenda'.  MATCHER is a Lisp form to be
14959 evaluated, testing if a given set of tags qualifies a headline for
14960 inclusion.  When TODO-ONLY is non-nil, only lines with a TODO keyword
14961 are included in the output."
14962   (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
14963                      (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14964                      (org-re
14965                       "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
14966          (props (list 'face nil
14967                       'done-face 'org-done
14968                       'undone-face nil
14969                       'mouse-face 'highlight
14970                       'org-not-done-regexp org-not-done-regexp
14971                       'org-todo-regexp org-todo-regexp
14972                       'keymap org-agenda-keymap
14973                       'help-echo
14974                       (format "mouse-2 or RET jump to org file %s"
14975                               (abbreviate-file-name
14976                                (or (buffer-file-name (buffer-base-buffer))
14977                                    (buffer-name (buffer-base-buffer)))))))
14978          (case-fold-search nil)
14979          lspos
14980          tags tags-list tags-alist (llast 0) rtn level category i txt
14981          todo marker entry priority)
14982     (save-excursion
14983       (goto-char (point-min))
14984       (when (eq action 'sparse-tree)
14985         (org-overview)
14986         (org-remove-occur-highlights))
14987       (while (re-search-forward re nil t)
14988         (catch :skip
14989           (setq todo (if (match-end 1) (match-string 2))
14990                 tags (if (match-end 4) (match-string 4)))
14991           (goto-char (setq lspos (1+ (match-beginning 0))))
14992           (setq level (org-reduced-level (funcall outline-level))
14993                 category (org-get-category))
14994           (setq i llast llast level)
14995           ;; remove tag lists from same and sublevels
14996           (while (>= i level)
14997             (when (setq entry (assoc i tags-alist))
14998               (setq tags-alist (delete entry tags-alist)))
14999             (setq i (1- i)))
15000           ;; add the nex tags
15001           (when tags
15002             (setq tags (mapcar 'downcase (org-split-string tags ":"))
15003                   tags-alist
15004                   (cons (cons level tags) tags-alist)))
15005           ;; compile tags for current headline
15006           (setq tags-list
15007                 (if org-use-tag-inheritance
15008                     (apply 'append (mapcar 'cdr tags-alist))
15009                   tags))
15010           (when (and (or (not todo-only) (member todo org-not-done-keywords))
15011                      (eval matcher)
15012                      (or (not org-agenda-skip-archived-trees)
15013                          (not (member org-archive-tag tags-list))))
15014             (and (eq action 'agenda) (org-agenda-skip))
15015             ;; list this headline
15017             (if (eq action 'sparse-tree)
15018                 (progn
15019                   (and org-highlight-sparse-tree-matches
15020                        (org-get-heading) (match-end 0)
15021                        (org-highlight-new-match
15022                         (match-beginning 0) (match-beginning 1)))
15023                   (org-show-context 'tags-tree))
15024               (setq txt (org-format-agenda-item
15025                          ""
15026                          (concat
15027                           (if org-tags-match-list-sublevels
15028                               (make-string (1- level) ?.) "")
15029                           (org-get-heading))
15030                          category tags-list)
15031                     priority (org-get-priority txt))
15032               (goto-char lspos)
15033               (setq marker (org-agenda-new-marker))
15034               (org-add-props txt props
15035                 'org-marker marker 'org-hd-marker marker 'org-category category
15036                 'priority priority 'type "tagsmatch")
15037               (push txt rtn))
15038             ;; if we are to skip sublevels, jump to end of subtree
15039             (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15040     (when (and (eq action 'sparse-tree)
15041                (not org-sparse-tree-open-archived-trees))
15042       (org-hide-archived-subtrees (point-min) (point-max)))
15043     (nreverse rtn)))
15045 (defvar todo-only) ;; dynamically scoped
15047 (defun org-tags-sparse-tree (&optional todo-only match)
15048   "Create a sparse tree according to tags  string MATCH.
15049 MATCH can contain positive and negative selection of tags, like
15050 \"+WORK+URGENT-WITHBOSS\".
15051 If optional argument TODO_ONLY is non-nil, only select lines that are
15052 also TODO lines."
15053   (interactive "P")
15054   (org-prepare-agenda-buffers (list (current-buffer)))
15055   (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15057 (defvar org-cached-props nil)
15058 (defun org-cached-entry-get (pom property)
15059   (if (or (eq t org-use-property-inheritance)
15060           (member property org-use-property-inheritance))
15061       ;; Caching is not possible, check it directly
15062       (org-entry-get pom property 'inherit)
15063     ;; Get all properties, so that we can do complicated checks easily
15064     (cdr (assoc property (or org-cached-props
15065                              (setq org-cached-props
15066                                    (org-entry-properties pom)))))))
15068 (defun org-global-tags-completion-table (&optional files)
15069   "Return the list of all tags in all agenda buffer/files."
15070   (save-excursion
15071     (org-uniquify
15072      (apply 'append
15073             (mapcar
15074              (lambda (file)
15075                (set-buffer (find-file-noselect file))
15076                (org-get-buffer-tags))
15077              (if (and files (car files))
15078                  files
15079                (org-agenda-files)))))))
15081 (defun org-make-tags-matcher (match)
15082   "Create the TAGS//TODO matcher form for the selection string MATCH."
15083   ;; todo-only is scoped dynamically into this function, and the function
15084   ;; may change it it the matcher asksk for it.
15085   (unless match
15086     ;; Get a new match request, with completion
15087     (let ((org-last-tags-completion-table
15088            (org-global-tags-completion-table)))
15089       (setq match (completing-read
15090                    "Match: " 'org-tags-completion-function nil nil nil
15091                    'org-tags-history))))
15093   ;; Parse the string and create a lisp form
15094   (let ((match0 match)
15095         (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
15096         minus tag mm
15097         tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15098         orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15099     (if (string-match "/+" match)
15100         ;; match contains also a todo-matching request
15101         (progn
15102           (setq tagsmatch (substring match 0 (match-beginning 0))
15103                 todomatch (substring match (match-end 0)))
15104           (if (string-match "^!" todomatch)
15105               (setq todo-only t todomatch (substring todomatch 1)))
15106           (if (string-match "^\\s-*$" todomatch)
15107               (setq todomatch nil)))
15108       ;; only matching tags
15109       (setq tagsmatch match todomatch nil))
15111     ;; Make the tags matcher
15112     (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15113         (setq tagsmatcher t)
15114       (setq orterms (org-split-string tagsmatch "|") orlist nil)
15115       (while (setq term (pop orterms))
15116         (while (and (equal (substring term -1) "\\") orterms)
15117           (setq term (concat term "|" (pop orterms)))) ; repair bad split
15118         (while (string-match re term)
15119           (setq minus (and (match-end 1)
15120                            (equal (match-string 1 term) "-"))
15121                 tag (match-string 2 term)
15122                 re-p (equal (string-to-char tag) ?{)
15123                 level-p (match-end 3)
15124                 prop-p (match-end 4)
15125                 mm (cond
15126                     (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15127                     (level-p `(= level ,(string-to-number
15128                                          (match-string 3 term))))
15129                     (prop-p
15130                      (setq pn (match-string 4 term)
15131                            pv (match-string 5 term)
15132                            cat-p (equal pn "CATEGORY")
15133                            re-p (equal (string-to-char pv) ?{)
15134                            pv (substring pv 1 -1))
15135                      (if (equal pn "CATEGORY")
15136                          (setq gv '(get-text-property (point) 'org-category))
15137                        (setq gv `(org-cached-entry-get nil ,pn)))
15138                      (if re-p
15139                          `(string-match ,pv (or ,gv ""))
15140                        `(equal ,pv ,gv)))
15141                     (t `(member ,(downcase tag) tags-list)))
15142                 mm (if minus (list 'not mm) mm)
15143                 term (substring term (match-end 0)))
15144           (push mm tagsmatcher))
15145         (push (if (> (length tagsmatcher) 1)
15146                   (cons 'and tagsmatcher)
15147                 (car tagsmatcher))
15148               orlist)
15149         (setq tagsmatcher nil))
15150       (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15151       (setq tagsmatcher
15152             (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15154     ;; Make the todo matcher
15155     (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15156         (setq todomatcher t)
15157       (setq orterms (org-split-string todomatch "|") orlist nil)
15158       (while (setq term (pop orterms))
15159         (while (string-match re term)
15160           (setq minus (and (match-end 1)
15161                            (equal (match-string 1 term) "-"))
15162                 kwd (match-string 2 term)
15163                 re-p (equal (string-to-char kwd) ?{)
15164                 term (substring term (match-end 0))
15165                 mm (if re-p
15166                        `(string-match  ,(substring kwd 1 -1) todo)
15167                      (list 'equal 'todo kwd))
15168                 mm (if minus (list 'not mm) mm))
15169           (push mm todomatcher))
15170         (push (if (> (length todomatcher) 1)
15171                   (cons 'and todomatcher)
15172                 (car todomatcher))
15173               orlist)
15174         (setq todomatcher nil))
15175       (setq todomatcher (if (> (length orlist) 1)
15176                             (cons 'or orlist) (car orlist))))
15178     ;; Return the string and lisp forms of the matcher
15179     (setq matcher (if todomatcher
15180                       (list 'and tagsmatcher todomatcher)
15181                     tagsmatcher))
15182     (cons match0 matcher)))
15184 (defun org-match-any-p (re list)
15185   "Does re match any element of list?"
15186   (setq list (mapcar (lambda (x) (string-match re x)) list))
15187   (delq nil list))
15189 (defvar org-add-colon-after-tag-completion nil)  ;; dynamically skoped param
15190 (defvar org-tags-overlay (org-make-overlay 1 1))
15191 (org-detach-overlay org-tags-overlay)
15193 (defun org-align-tags-here (to-col)
15194   ;; Assumes that this is a headline
15195   (let ((pos (point)) (col (current-column)) tags)
15196     (beginning-of-line 1)
15197     (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15198              (< pos (match-beginning 2)))
15199         (progn
15200           (setq tags (match-string 2))
15201           (goto-char (match-beginning 1))
15202           (insert " ")
15203           (delete-region (point) (1+ (match-end 0)))
15204           (backward-char 1)
15205           (move-to-column
15206            (max (1+ (current-column))
15207                 (1+ col)
15208                 (if (> to-col 0)
15209                     to-col
15210                   (- (abs to-col) (length tags))))
15211            t)
15212           (insert tags)
15213           (move-to-column (min (current-column) col) t))
15214       (goto-char pos))))
15216 (defun org-set-tags (&optional arg just-align)
15217   "Set the tags for the current headline.
15218 With prefix ARG, realign all tags in headings in the current buffer."
15219   (interactive "P")
15220   (let* ((re (concat "^" outline-regexp))
15221          (current (org-get-tags-string))
15222          (col (current-column))
15223          (org-setting-tags t)
15224          table current-tags inherited-tags ; computed below when needed
15225          tags p0 c0 c1 rpl)
15226     (if arg
15227         (save-excursion
15228           (goto-char (point-min))
15229           (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15230             (while (re-search-forward re nil t)
15231               (org-set-tags nil t)
15232               (end-of-line 1)))
15233           (message "All tags realigned to column %d" org-tags-column))
15234       (if just-align
15235           (setq tags current)
15236         ;; Get a new set of tags from the user
15237         (save-excursion
15238           (setq table (or org-tag-alist (org-get-buffer-tags))
15239                 org-last-tags-completion-table table
15240                 current-tags (org-split-string current ":")
15241                 inherited-tags (nreverse
15242                                 (nthcdr (length current-tags)
15243                                         (nreverse (org-get-tags-at))))
15244                 tags
15245                 (if (or (eq t org-use-fast-tag-selection)
15246                         (and org-use-fast-tag-selection
15247                              (delq nil (mapcar 'cdr table))))
15248                     (org-fast-tag-selection
15249                      current-tags inherited-tags table
15250                      (if org-fast-tag-selection-include-todo org-todo-key-alist))
15251                   (let ((org-add-colon-after-tag-completion t))
15252                     (org-trim
15253                      (org-without-partial-completion
15254                       (completing-read "Tags: " 'org-tags-completion-function
15255                                        nil nil current 'org-tags-history)))))))
15256         (while (string-match "[-+&]+" tags)
15257           ;; No boolean logic, just a list
15258           (setq tags (replace-match ":" t t tags))))
15260       (if (string-match "\\`[\t ]*\\'" tags)
15261           (setq tags "")
15262         (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15263         (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15265       ;; Insert new tags at the correct column
15266       (beginning-of-line 1)
15267       (cond
15268        ((and (equal current "") (equal tags "")))
15269        ((re-search-forward
15270          (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15271          (point-at-eol) t)
15272         (if (equal tags "")
15273             (setq rpl "")
15274           (goto-char (match-beginning 0))
15275           (setq c0 (current-column) p0 (point)
15276                 c1 (max (1+ c0) (if (> org-tags-column 0)
15277                                     org-tags-column
15278                                   (- (- org-tags-column) (length tags))))
15279                 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15280         (replace-match rpl t t)
15281         (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
15282         tags)
15283        (t (error "Tags alignment failed")))
15284       (move-to-column col)
15285       (unless just-align
15286         (run-hooks 'org-after-tags-change-hook)))))
15288 (defun org-change-tag-in-region (beg end tag off)
15289   "Add or remove TAG for each entry in the region.
15290 This works in the agenda, and also in an org-mode buffer."
15291   (interactive
15292    (list (region-beginning) (region-end)
15293          (let ((org-last-tags-completion-table
15294                 (if (org-mode-p)
15295                     (org-get-buffer-tags)
15296                   (org-global-tags-completion-table))))
15297            (completing-read
15298             "Tag: " 'org-tags-completion-function nil nil nil
15299             'org-tags-history))
15300          (progn
15301            (message "[s]et or [r]emove? ")
15302            (equal (read-char-exclusive) ?r))))
15303   (if (fboundp 'deactivate-mark) (deactivate-mark))
15304   (let ((agendap (equal major-mode 'org-agenda-mode))
15305         l1 l2 m buf pos newhead (cnt 0))
15306     (goto-char end)
15307     (setq l2 (1- (org-current-line)))
15308     (goto-char beg)
15309     (setq l1 (org-current-line))
15310     (loop for l from l1 to l2 do
15311           (goto-line l)
15312           (setq m (get-text-property (point) 'org-hd-marker))
15313           (when (or (and (org-mode-p) (org-on-heading-p))
15314                     (and agendap m))
15315             (setq buf (if agendap (marker-buffer m) (current-buffer))
15316                   pos (if agendap m (point)))
15317             (with-current-buffer buf
15318               (save-excursion
15319                 (save-restriction
15320                   (goto-char pos)
15321                   (setq cnt (1+ cnt))
15322                   (org-toggle-tag tag (if off 'off 'on))
15323                   (setq newhead (org-get-heading)))))
15324             (and agendap (org-agenda-change-all-lines newhead m))))
15325     (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15327 (defun org-tags-completion-function (string predicate &optional flag)
15328   (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15329            (confirm (lambda (x) (stringp (car x)))))
15330     (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15331         (setq s1 (match-string 1 string)
15332               s2 (match-string 2 string))
15333       (setq s1 "" s2 string))
15334     (cond
15335      ((eq flag nil)
15336       ;; try completion
15337       (setq rtn (try-completion s2 ctable confirm))
15338       (if (stringp rtn)
15339           (setq rtn
15340                 (concat s1 s2 (substring rtn (length s2))
15341                         (if (and org-add-colon-after-tag-completion
15342                                  (assoc rtn ctable))
15343                             ":" ""))))
15344       rtn)
15345      ((eq flag t)
15346       ;; all-completions
15347       (all-completions s2 ctable confirm)
15348       )
15349      ((eq flag 'lambda)
15350       ;; exact match?
15351       (assoc s2 ctable)))
15352     ))
15354 (defun org-fast-tag-insert (kwd tags face &optional end)
15355   "Insert KDW, and the TAGS, the latter with face FACE.  Also inser END."
15356   (insert (format "%-12s" (concat kwd ":"))
15357           (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15358           (or end "")))
15360 (defun org-fast-tag-show-exit (flag)
15361   (save-excursion
15362     (goto-line 3)
15363     (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15364         (replace-match ""))
15365     (when flag
15366       (end-of-line 1)
15367       (move-to-column (- (window-width) 19) t)
15368       (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15370 (defun org-set-current-tags-overlay (current prefix)
15371   (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15372     (if (featurep 'xemacs)
15373         (org-overlay-display org-tags-overlay (concat prefix s)
15374                              'secondary-selection)
15375       (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15376       (org-overlay-display org-tags-overlay (concat prefix s)))))
15378 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15379   "Fast tag selection with single keys.
15380 CURRENT is the current list of tags in the headline, INHERITED is the
15381 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15382 possibly with grouping information.  TODO-TABLE is a similar table with
15383 TODO keywords, should these have keys assigned to them.
15384 If the keys are nil, a-z are automatically assigned.
15385 Returns the new tags string, or nil to not change the current settings."
15386   (let* ((fulltable (append table todo-table))
15387          (maxlen (apply 'max (mapcar
15388                               (lambda (x)
15389                                 (if (stringp (car x)) (string-width (car x)) 0))
15390                               fulltable)))
15391          (buf (current-buffer))
15392          (expert (eq org-fast-tag-selection-single-key 'expert))
15393          (buffer-tags nil)
15394          (fwidth (+ maxlen 3 1 3))
15395          (ncol (/ (- (window-width) 4) fwidth))
15396          (i-face 'org-done)
15397          (c-face 'org-todo)
15398          tg cnt e c char c1 c2 ntable tbl rtn
15399          ov-start ov-end ov-prefix
15400          (exit-after-next org-fast-tag-selection-single-key)
15401          (done-keywords org-done-keywords)
15402          groups ingroup)
15403     (save-excursion
15404       (beginning-of-line 1)
15405       (if (looking-at
15406            (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15407           (setq ov-start (match-beginning 1)
15408                 ov-end (match-end 1)
15409                 ov-prefix "")
15410         (setq ov-start (1- (point-at-eol))
15411               ov-end (1+ ov-start))
15412         (skip-chars-forward "^\n\r")
15413         (setq ov-prefix
15414               (concat
15415                (buffer-substring (1- (point)) (point))
15416                (if (> (current-column) org-tags-column)
15417                    " "
15418                  (make-string (- org-tags-column (current-column)) ?\ ))))))
15419     (org-move-overlay org-tags-overlay ov-start ov-end)
15420     (save-window-excursion
15421       (if expert
15422           (set-buffer (get-buffer-create " *Org tags*"))
15423         (delete-other-windows)
15424         (split-window-vertically)
15425         (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15426       (erase-buffer)
15427       (org-set-local 'org-done-keywords done-keywords)
15428       (org-fast-tag-insert "Inherited" inherited i-face "\n")
15429       (org-fast-tag-insert "Current" current c-face "\n\n")
15430       (org-fast-tag-show-exit exit-after-next)
15431       (org-set-current-tags-overlay current ov-prefix)
15432       (setq tbl fulltable char ?a cnt 0)
15433       (while (setq e (pop tbl))
15434         (cond
15435          ((equal e '(:startgroup))
15436           (push '() groups) (setq ingroup t)
15437           (when (not (= cnt 0))
15438             (setq cnt 0)
15439             (insert "\n"))
15440           (insert "{ "))
15441          ((equal e '(:endgroup))
15442           (setq ingroup nil cnt 0)
15443           (insert "}\n"))
15444          (t
15445           (setq tg (car e) c2 nil)
15446           (if (cdr e)
15447               (setq c (cdr e))
15448             ;; automatically assign a character.
15449             (setq c1 (string-to-char
15450                       (downcase (substring
15451                                  tg (if (= (string-to-char tg) ?@) 1 0)))))
15452             (if (or (rassoc c1 ntable) (rassoc c1 table))
15453                 (while (or (rassoc char ntable) (rassoc char table))
15454                   (setq char (1+ char)))
15455               (setq c2 c1))
15456             (setq c (or c2 char)))
15457           (if ingroup (push tg (car groups)))
15458           (setq tg (org-add-props tg nil 'face
15459                                   (cond
15460                                    ((not (assoc tg table))
15461                                     (org-get-todo-face tg))
15462                                    ((member tg current) c-face)
15463                                    ((member tg inherited) i-face)
15464                                    (t nil))))
15465           (if (and (= cnt 0) (not ingroup)) (insert "  "))
15466           (insert "[" c "] " tg (make-string
15467                                  (- fwidth 4 (length tg)) ?\ ))
15468           (push (cons tg c) ntable)
15469           (when (= (setq cnt (1+ cnt)) ncol)
15470             (insert "\n")
15471             (if ingroup (insert "  "))
15472             (setq cnt 0)))))
15473       (setq ntable (nreverse ntable))
15474       (insert "\n")
15475       (goto-char (point-min))
15476       (if (and (not expert) (fboundp 'fit-window-to-buffer))
15477           (fit-window-to-buffer))
15478       (setq rtn
15479             (catch 'exit
15480               (while t
15481                 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15482                          (if groups " [!] no groups" " [!]groups")
15483                          (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15484                 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15485                 (cond
15486                  ((= c ?\r) (throw 'exit t))
15487                  ((= c ?!)
15488                   (setq groups (not groups))
15489                   (goto-char (point-min))
15490                   (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15491                  ((= c ?\C-c)
15492                   (if (not expert)
15493                       (org-fast-tag-show-exit
15494                        (setq exit-after-next (not exit-after-next)))
15495                     (setq expert nil)
15496                     (delete-other-windows)
15497                     (split-window-vertically)
15498                     (org-switch-to-buffer-other-window " *Org tags*")
15499                     (and (fboundp 'fit-window-to-buffer)
15500                          (fit-window-to-buffer))))
15501                  ((or (= c ?\C-g)
15502                       (and (= c ?q) (not (rassoc c ntable))))
15503                   (org-detach-overlay org-tags-overlay)
15504                   (setq quit-flag t))
15505                  ((= c ?\ )
15506                   (setq current nil)
15507                   (if exit-after-next (setq exit-after-next 'now)))
15508                  ((= c ?\t)
15509                   (condition-case nil
15510                       (setq tg (completing-read
15511                                 "Tag: "
15512                                 (or buffer-tags
15513                                     (with-current-buffer buf
15514                                       (org-get-buffer-tags)))))
15515                     (quit (setq tg "")))
15516                   (when (string-match "\\S-" tg)
15517                     (add-to-list 'buffer-tags (list tg))
15518                     (if (member tg current)
15519                         (setq current (delete tg current))
15520                       (push tg current)))
15521                   (if exit-after-next (setq exit-after-next 'now)))
15522                  ((setq e (rassoc c todo-table) tg (car e))
15523                   (with-current-buffer buf
15524                     (save-excursion (org-todo tg)))
15525                   (if exit-after-next (setq exit-after-next 'now)))
15526                  ((setq e (rassoc c ntable) tg (car e))
15527                   (if (member tg current)
15528                       (setq current (delete tg current))
15529                     (loop for g in groups do
15530                           (if (member tg g)
15531                               (mapc (lambda (x)
15532                                       (setq current (delete x current)))
15533                                     g)))
15534                     (push tg current))
15535                   (if exit-after-next (setq exit-after-next 'now))))
15537                 ;; Create a sorted list
15538                 (setq current
15539                       (sort current
15540                             (lambda (a b)
15541                               (assoc b (cdr (memq (assoc a ntable) ntable))))))
15542                 (if (eq exit-after-next 'now) (throw 'exit t))
15543                 (goto-char (point-min))
15544                 (beginning-of-line 2)
15545                 (delete-region (point) (point-at-eol))
15546                 (org-fast-tag-insert "Current" current c-face)
15547                 (org-set-current-tags-overlay current ov-prefix)
15548                 (while (re-search-forward
15549                         (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15550                   (setq tg (match-string 1))
15551                   (add-text-properties
15552                    (match-beginning 1) (match-end 1)
15553                    (list 'face
15554                          (cond
15555                           ((member tg current) c-face)
15556                           ((member tg inherited) i-face)
15557                           (t (get-text-property (match-beginning 1) 'face))))))
15558                 (goto-char (point-min)))))
15559       (org-detach-overlay org-tags-overlay)
15560       (if rtn
15561           (mapconcat 'identity current ":")
15562         nil))))
15564 (defun org-get-tags-string ()
15565   "Get the TAGS string in the current headline."
15566   (unless (org-on-heading-p t)
15567     (error "Not on a heading"))
15568   (save-excursion
15569     (beginning-of-line 1)
15570     (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15571         (org-match-string-no-properties 1)
15572       "")))
15574 (defun org-get-tags ()
15575   "Get the list of tags specified in the current headline."
15576   (org-split-string (org-get-tags-string) ":"))
15578 (defun org-get-buffer-tags ()
15579   "Get a table of all tags used in the buffer, for completion."
15580   (let (tags)
15581     (save-excursion
15582       (goto-char (point-min))
15583       (while (re-search-forward
15584               (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15585         (when (equal (char-after (point-at-bol 0)) ?*)
15586           (mapc (lambda (x) (add-to-list 'tags x))
15587                 (org-split-string (org-match-string-no-properties 1) ":")))))
15588     (mapcar 'list tags)))
15591 ;;;; Properties
15593 ;;; Setting and retrieving properties
15595 (defconst org-special-properties
15596   '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15597     "TIMESTAMP" "TIMESTAMP_IA")
15598   "The special properties valid in Org-mode.
15600 These are properties that are not defined in the property drawer,
15601 but in some other way.")
15603 (defconst org-default-properties
15604   '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15605     "LOCATION" "LOGGING" "COLUMNS")
15606   "Some properties that are used by Org-mode for various purposes.
15607 Being in this list makes sure that they are offered for completion.")
15609 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15610   "Regular expression matching the first line of a property drawer.")
15612 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15613   "Regular expression matching the first line of a property drawer.")
15615 (defun org-property-action ()
15616   "Do an action on properties."
15617   (interactive)
15618   (let (c)
15619     (org-at-property-p)
15620     (message "Property Action:  [s]et  [d]elete  [D]elete globally  [c]ompute")
15621     (setq c (read-char-exclusive))
15622     (cond
15623      ((equal c ?s)
15624       (call-interactively 'org-set-property))
15625      ((equal c ?d)
15626       (call-interactively 'org-delete-property))
15627      ((equal c ?D)
15628       (call-interactively 'org-delete-property-globally))
15629      ((equal c ?c)
15630       (call-interactively 'org-compute-property-at-point))
15631      (t (error "No such property action %c" c)))))
15633 (defun org-at-property-p ()
15634   "Is the cursor in a property line?"
15635   ;; FIXME: Does not check if we are actually in the drawer.
15636   ;; FIXME: also returns true on any drawers.....
15637   ;; This is used by C-c C-c for property action.
15638   (save-excursion
15639     (beginning-of-line 1)
15640     (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15642 (defmacro org-with-point-at (pom &rest body)
15643   "Move to buffer and point of point-or-marker POM for the duration of BODY."
15644   (declare (indent 1) (debug t))
15645   `(save-excursion
15646      (if (markerp pom) (set-buffer (marker-buffer pom)))
15647      (save-excursion
15648        (goto-char (or pom (point)))
15649        ,@body)))
15651 (defun org-get-property-block (&optional beg end force)
15652   "Return the (beg . end) range of the body of the property drawer.
15653 BEG and END can be beginning and end of subtree, if not given
15654 they will be found.
15655 If the drawer does not exist and FORCE is non-nil, create the drawer."
15656   (catch 'exit
15657     (save-excursion
15658       (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15659              (end (or end (progn (outline-next-heading) (point)))))
15660         (goto-char beg)
15661         (if (re-search-forward org-property-start-re end t)
15662             (setq beg (1+ (match-end 0)))
15663           (if force
15664               (save-excursion
15665                 (org-insert-property-drawer)
15666                 (setq end (progn (outline-next-heading) (point))))
15667             (throw 'exit nil))
15668           (goto-char beg)
15669           (if (re-search-forward org-property-start-re end t)
15670               (setq beg (1+ (match-end 0)))))
15671         (if (re-search-forward org-property-end-re end t)
15672             (setq end (match-beginning 0))
15673           (or force (throw 'exit nil))
15674           (goto-char beg)
15675           (setq end beg)
15676           (org-indent-line-function)
15677           (insert ":END:\n"))
15678         (cons beg end)))))
15680 (defun org-entry-properties (&optional pom which)
15681   "Get all properties of the entry at point-or-marker POM.
15682 This includes the TODO keyword, the tags, time strings for deadline,
15683 scheduled, and clocking, and any additional properties defined in the
15684 entry.  The return value is an alist, keys may occur multiple times
15685 if the property key was used several times.
15686 POM may also be nil, in which case the current entry is used.
15687 If WHICH is nil or `all', get all properties.  If WHICH is
15688 `special' or `standard', only get that subclass."
15689   (setq which (or which 'all))
15690   (org-with-point-at pom
15691     (let ((clockstr (substring org-clock-string 0 -1))
15692           (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15693           beg end range props sum-props key value string)
15694       (save-excursion
15695         (when (condition-case nil (org-back-to-heading t) (error nil))
15696           (setq beg (point))
15697           (setq sum-props (get-text-property (point) 'org-summaries))
15698           (outline-next-heading)
15699           (setq end (point))
15700           (when (memq which '(all special))
15701             ;; Get the special properties, like TODO and tags
15702             (goto-char beg)
15703             (when (and (looking-at org-todo-line-regexp) (match-end 2))
15704               (push (cons "TODO" (org-match-string-no-properties 2)) props))
15705             (when (looking-at org-priority-regexp)
15706               (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15707             (when (and (setq value (org-get-tags-string))
15708                        (string-match "\\S-" value))
15709               (push (cons "TAGS" value) props))
15710             (when (setq value (org-get-tags-at))
15711               (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
15712                     props))
15713             (while (re-search-forward org-maybe-keyword-time-regexp end t)
15714               (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
15715                     string (if (equal key clockstr)
15716                                (org-no-properties
15717                                 (org-trim
15718                                  (buffer-substring
15719                                   (match-beginning 3) (goto-char (point-at-eol)))))
15720                              (substring (org-match-string-no-properties 3) 1 -1)))
15721               (unless key
15722                 (if (= (char-after (match-beginning 3)) ?\[)
15723                     (setq key "TIMESTAMP_IA")
15724                   (setq key "TIMESTAMP")))
15725               (when (or (equal key clockstr) (not (assoc key props)))
15726                 (push (cons key string) props)))
15728             )
15730           (when (memq which '(all standard))
15731             ;; Get the standard properties, like :PORP: ...
15732             (setq range (org-get-property-block beg end))
15733             (when range
15734               (goto-char (car range))
15735               (while (re-search-forward
15736                       (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15737                       (cdr range) t)
15738                 (setq key (org-match-string-no-properties 1)
15739                       value (org-trim (or (org-match-string-no-properties 2) "")))
15740                 (unless (member key excluded)
15741                   (push (cons key (or value "")) props)))))
15742           (append sum-props (nreverse props)))))))
15744 (defun org-entry-get (pom property &optional inherit)
15745   "Get value of PROPERTY for entry at point-or-marker POM.
15746 If INHERIT is non-nil and the entry does not have the property,
15747 then also check higher levels of the hierarchy.
15748 If the property is present but empty, the return value is the empty string.
15749 If the property is not present at all, nil is returned."
15750   (org-with-point-at pom
15751     (if inherit
15752         (org-entry-get-with-inheritance property)
15753       (if (member property org-special-properties)
15754           ;; We need a special property.  Use brute force, get all properties.
15755           (cdr (assoc property (org-entry-properties nil 'special)))
15756         (let ((range (org-get-property-block)))
15757           (if (and range
15758                    (goto-char (car range))
15759                    (re-search-forward
15760                     (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
15761                     (cdr range) t))
15762               ;; Found the property, return it.
15763               (if (match-end 1)
15764                   (org-match-string-no-properties 1)
15765                 "")))))))
15767 (defun org-entry-delete (pom property)
15768   "Delete the property PROPERTY from entry at point-or-marker POM."
15769   (org-with-point-at pom
15770     (if (member property org-special-properties)
15771         nil ; cannot delete these properties.
15772       (let ((range (org-get-property-block)))
15773         (if (and range
15774                  (goto-char (car range))
15775                  (re-search-forward
15776                   (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
15777                   (cdr range) t))
15778             (progn
15779               (delete-region (match-beginning 0) (1+ (point-at-eol)))
15780               t)
15781           nil)))))
15783 ;; Multi-values properties are properties that contain multiple values
15784 ;; These values are assumed to be single words, separated by whitespace.
15785 (defun org-entry-add-to-multivalued-property (pom property value)
15786   "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15787   (let* ((old (org-entry-get pom property))
15788          (values (and old (org-split-string old "[ \t]"))))
15789     (unless (member value values)
15790       (setq values (cons value values))
15791       (org-entry-put pom property
15792                      (mapconcat 'identity values " ")))))
15794 (defun org-entry-remove-from-multivalued-property (pom property value)
15795   "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15796   (let* ((old (org-entry-get pom property))
15797          (values (and old (org-split-string old "[ \t]"))))
15798     (when (member value values)
15799       (setq values (delete value values))
15800       (org-entry-put pom property
15801                      (mapconcat 'identity values " ")))))
15803 (defun org-entry-member-in-multivalued-property (pom property value)
15804   "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15805   (let* ((old (org-entry-get pom property))
15806          (values (and old (org-split-string old "[ \t]"))))
15807     (member value values)))
15809 (defvar org-entry-property-inherited-from (make-marker))
15811 (defun org-entry-get-with-inheritance (property)
15812   "Get entry property, and search higher levels if not present."
15813   (let (tmp)
15814     (save-excursion
15815       (save-restriction
15816         (widen)
15817         (catch 'ex
15818           (while t
15819             (when (setq tmp (org-entry-get nil property))
15820               (org-back-to-heading t)
15821               (move-marker org-entry-property-inherited-from (point))
15822               (throw 'ex tmp))
15823             (or (org-up-heading-safe) (throw 'ex nil)))))
15824       (or tmp (cdr (assoc property org-local-properties))
15825           (cdr (assoc property org-global-properties))))))
15827 (defun org-entry-put (pom property value)
15828   "Set PROPERTY to VALUE for entry at point-or-marker POM."
15829   (org-with-point-at pom
15830     (org-back-to-heading t)
15831     (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15832           range)
15833       (cond
15834        ((equal property "TODO")
15835         (when (and (stringp value) (string-match "\\S-" value)
15836                    (not (member value org-todo-keywords-1)))
15837           (error "\"%s\" is not a valid TODO state" value))
15838         (if (or (not value)
15839                 (not (string-match "\\S-" value)))
15840             (setq value 'none))
15841         (org-todo value)
15842         (org-set-tags nil 'align))
15843        ((equal property "PRIORITY")
15844         (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15845                                (string-to-char value) ?\ ))
15846         (org-set-tags nil 'align))
15847        ((equal property "SCHEDULED")
15848         (if (re-search-forward org-scheduled-time-regexp end t)
15849             (cond
15850              ((eq value 'earlier) (org-timestamp-change -1 'day))
15851              ((eq value 'later) (org-timestamp-change 1 'day))
15852              (t (call-interactively 'org-schedule)))
15853           (call-interactively 'org-schedule)))
15854        ((equal property "DEADLINE")
15855         (if (re-search-forward org-deadline-time-regexp end t)
15856             (cond
15857              ((eq value 'earlier) (org-timestamp-change -1 'day))
15858              ((eq value 'later) (org-timestamp-change 1 'day))
15859              (t (call-interactively 'org-deadline)))
15860           (call-interactively 'org-deadline)))
15861        ((member property org-special-properties)
15862         (error "The %s property can not yet be set with `org-entry-put'"
15863                property))
15864        (t ; a non-special property
15865         (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15866           (setq range (org-get-property-block beg end 'force))
15867           (goto-char (car range))
15868           (if (re-search-forward
15869                (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
15870               (progn
15871                 (delete-region (match-beginning 1) (match-end 1))
15872                 (goto-char (match-beginning 1)))
15873             (goto-char (cdr range))
15874             (insert "\n")
15875             (backward-char 1)
15876             (org-indent-line-function)
15877             (insert ":" property ":"))
15878           (and value (insert " " value))
15879           (org-indent-line-function)))))))
15881 (defun org-buffer-property-keys (&optional include-specials include-defaults)
15882   "Get all property keys in the current buffer.
15883 With INCLUDE-SPECIALS, also list the special properties that relect things
15884 like tags and TODO state.
15885 With INCLUDE-DEFAULTS, also include properties that has special meaning
15886 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
15887   (let (rtn range)
15888     (save-excursion
15889       (save-restriction
15890         (widen)
15891         (goto-char (point-min))
15892         (while (re-search-forward org-property-start-re nil t)
15893           (setq range (org-get-property-block))
15894           (goto-char (car range))
15895           (while (re-search-forward
15896                   (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
15897                   (cdr range) t)
15898             (add-to-list 'rtn (org-match-string-no-properties 1)))
15899           (outline-next-heading))))
15901     (when include-specials
15902       (setq rtn (append org-special-properties rtn)))
15904     (when include-defaults
15905       (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
15907     (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15909 (defun org-property-values (key)
15910   "Return a list of all values of property KEY."
15911   (save-excursion
15912     (save-restriction
15913       (widen)
15914       (goto-char (point-min))
15915       (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
15916             values)
15917         (while (re-search-forward re nil t)
15918           (add-to-list 'values (org-trim (match-string 1))))
15919         (delete "" values)))))
15921 (defun org-insert-property-drawer ()
15922   "Insert a property drawer into the current entry."
15923   (interactive)
15924   (org-back-to-heading t)
15925   (looking-at outline-regexp)
15926   (let ((indent (- (match-end 0)(match-beginning 0)))
15927         (beg (point))
15928         (re (concat "^[ \t]*" org-keyword-time-regexp))
15929         end hiddenp)
15930     (outline-next-heading)
15931     (setq end (point))
15932     (goto-char beg)
15933     (while (re-search-forward re end t))
15934     (setq hiddenp (org-invisible-p))
15935     (end-of-line 1)
15936     (and (equal (char-after) ?\n) (forward-char 1))
15937     (org-skip-over-state-notes)
15938     (skip-chars-backward " \t\n\r")
15939     (if (eq (char-before) ?*) (forward-char 1))
15940     (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15941     (beginning-of-line 0)
15942     (indent-to-column indent)
15943     (beginning-of-line 2)
15944     (indent-to-column indent)
15945     (beginning-of-line 0)
15946     (if hiddenp
15947         (save-excursion
15948           (org-back-to-heading t)
15949           (hide-entry))
15950       (org-flag-drawer t))))
15952 (defun org-set-property (property value)
15953   "In the current entry, set PROPERTY to VALUE.
15954 When called interactively, this will prompt for a property name, offering
15955 completion on existing and default properties.  And then it will prompt
15956 for a value, offering competion either on allowed values (via an inherited
15957 xxx_ALL property) or on existing values in other instances of this property
15958 in the current file."
15959   (interactive
15960    (let* ((prop (completing-read
15961                  "Property: " (mapcar 'list (org-buffer-property-keys nil t))))
15962           (cur (org-entry-get nil prop))
15963           (allowed (org-property-get-allowed-values nil prop 'table))
15964           (existing (mapcar 'list (org-property-values prop)))
15965           (val (if allowed
15966                    (completing-read "Value: " allowed nil 'req-match)
15967                  (completing-read
15968                   (concat "Value" (if (and cur (string-match "\\S-" cur))
15969                                       (concat "[" cur "]") "")
15970                           ": ")
15971                   existing nil nil "" nil cur))))
15972      (list prop (if (equal val "") cur val))))
15973   (unless (equal (org-entry-get nil property) value)
15974     (org-entry-put nil property value)))
15976 (defun org-delete-property (property)
15977   "In the current entry, delete PROPERTY."
15978   (interactive
15979    (let* ((prop (completing-read
15980                  "Property: " (org-entry-properties nil 'standard))))
15981      (list prop)))
15982   (message "Property %s %s" property
15983            (if (org-entry-delete nil property)
15984                "deleted"
15985              "was not present in the entry")))
15987 (defun org-delete-property-globally (property)
15988   "Remove PROPERTY globally, from all entries."
15989   (interactive
15990    (let* ((prop (completing-read
15991                  "Globally remove property: "
15992                  (mapcar 'list (org-buffer-property-keys)))))
15993      (list prop)))
15994   (save-excursion
15995     (save-restriction
15996       (widen)
15997       (goto-char (point-min))
15998       (let ((cnt 0))
15999         (while (re-search-forward
16000                 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16001                 nil t)
16002           (setq cnt (1+ cnt))
16003           (replace-match ""))
16004         (message "Property \"%s\" removed from %d entries" property cnt)))))
16006 (defvar org-columns-current-fmt-compiled) ; defined below
16008 (defun org-compute-property-at-point ()
16009   "Compute the property at point.
16010 This looks for an enclosing column format, extracts the operator and
16011 then applies it to the proerty in the column format's scope."
16012   (interactive)
16013   (unless (org-at-property-p)
16014     (error "Not at a property"))
16015   (let ((prop (org-match-string-no-properties 2)))
16016     (org-columns-get-format-and-top-level)
16017     (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16018       (error "No operator defined for property %s" prop))
16019     (org-columns-compute prop)))
16021 (defun org-property-get-allowed-values (pom property &optional table)
16022   "Get allowed values for the property PROPERTY.
16023 When TABLE is non-nil, return an alist that can directly be used for
16024 completion."
16025   (let (vals)
16026     (cond
16027      ((equal property "TODO")
16028       (setq vals (org-with-point-at pom
16029                    (append org-todo-keywords-1 '("")))))
16030      ((equal property "PRIORITY")
16031       (let ((n org-lowest-priority))
16032         (while (>= n org-highest-priority)
16033           (push (char-to-string n) vals)
16034           (setq n (1- n)))))
16035      ((member property org-special-properties))
16036      (t
16037       (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16039       (when (and vals (string-match "\\S-" vals))
16040         (setq vals (car (read-from-string (concat "(" vals ")"))))
16041         (setq vals (mapcar (lambda (x)
16042                              (cond ((stringp x) x)
16043                                    ((numberp x) (number-to-string x))
16044                                    ((symbolp x) (symbol-name x))
16045                                    (t "???")))
16046                            vals)))))
16047     (if table (mapcar 'list vals) vals)))
16049 (defun org-property-previous-allowed-value (&optional previous)
16050   "Switch to the next allowed value for this property."
16051   (interactive)
16052   (org-property-next-allowed-value t))
16054 (defun org-property-next-allowed-value (&optional previous)
16055   "Switch to the next allowed value for this property."
16056   (interactive)
16057   (unless (org-at-property-p)
16058     (error "Not at a property"))
16059   (let* ((key (match-string 2))
16060          (value (match-string 3))
16061          (allowed (or (org-property-get-allowed-values (point) key)
16062                       (and (member value  '("[ ]" "[-]" "[X]"))
16063                            '("[ ]" "[X]"))))
16064          nval)
16065     (unless allowed
16066       (error "Allowed values for this property have not been defined"))
16067     (if previous (setq allowed (reverse allowed)))
16068     (if (member value allowed)
16069         (setq nval (car (cdr (member value allowed)))))
16070     (setq nval (or nval (car allowed)))
16071     (if (equal nval value)
16072         (error "Only one allowed value for this property"))
16073     (org-at-property-p)
16074     (replace-match (concat " :" key ": " nval) t t)
16075     (org-indent-line-function)
16076     (beginning-of-line 1)
16077     (skip-chars-forward " \t")))
16079 (defun org-find-entry-with-id (ident)
16080   "Locate the entry that contains the ID property with exact value IDENT.
16081 IDENT can be a string, a symbol or a number, this function will search for
16082 the string representation of it.
16083 Return the position where this entry starts, or nil if there is no such entry."
16084   (let ((id (cond
16085              ((stringp ident) ident)
16086              ((symbol-name ident) (symbol-name ident))
16087              ((numberp ident) (number-to-string ident))
16088              (t (error "IDENT %s must be a string, symbol or number" ident))))
16089         (case-fold-search nil))
16090     (save-excursion
16091       (save-restriction
16092         (goto-char (point-min))
16093         (when (re-search-forward
16094                (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16095                nil t)
16096           (org-back-to-heading)
16097           (point))))))
16099 ;;; Column View
16101 (defvar org-columns-overlays nil
16102   "Holds the list of current column overlays.")
16104 (defvar org-columns-current-fmt nil
16105   "Local variable, holds the currently active column format.")
16106 (defvar org-columns-current-fmt-compiled nil
16107   "Local variable, holds the currently active column format.
16108 This is the compiled version of the format.")
16109 (defvar org-columns-current-widths nil
16110   "Loval variable, holds the currently widths of fields.")
16111 (defvar org-columns-current-maxwidths nil
16112   "Loval variable, holds the currently active maximum column widths.")
16113 (defvar org-columns-begin-marker (make-marker)
16114   "Points to the position where last a column creation command was called.")
16115 (defvar org-columns-top-level-marker (make-marker)
16116   "Points to the position where current columns region starts.")
16118 (defvar org-columns-map (make-sparse-keymap)
16119   "The keymap valid in column display.")
16121 (defun org-columns-content ()
16122   "Switch to contents view while in columns view."
16123   (interactive)
16124   (org-overview)
16125   (org-content))
16127 (org-defkey org-columns-map "c" 'org-columns-content)
16128 (org-defkey org-columns-map "o" 'org-overview)
16129 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16130 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16131 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16132 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16133 (org-defkey org-columns-map "v" 'org-columns-show-value)
16134 (org-defkey org-columns-map "q" 'org-columns-quit)
16135 (org-defkey org-columns-map "r" 'org-columns-redo)
16136 (org-defkey org-columns-map [left] 'backward-char)
16137 (org-defkey org-columns-map "\M-b" 'backward-char)
16138 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16139 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16140 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16141 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16142 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16143 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16144 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16145 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16146 (org-defkey org-columns-map "<" 'org-columns-narrow)
16147 (org-defkey org-columns-map ">" 'org-columns-widen)
16148 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16149 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16150 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16151 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16153 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16154   '("Column"
16155     ["Edit property" org-columns-edit-value t]
16156     ["Next allowed value" org-columns-next-allowed-value t]
16157     ["Previous allowed value" org-columns-previous-allowed-value t]
16158     ["Show full value" org-columns-show-value t]
16159     ["Edit allowed values" org-columns-edit-allowed t]
16160     "--"
16161     ["Edit column attributes" org-columns-edit-attributes t]
16162     ["Increase column width" org-columns-widen t]
16163     ["Decrease column width" org-columns-narrow t]
16164     "--"
16165     ["Move column right" org-columns-move-right t]
16166     ["Move column left" org-columns-move-left t]
16167     ["Add column" org-columns-new t]
16168     ["Delete column" org-columns-delete t]
16169     "--"
16170     ["CONTENTS" org-columns-content t]
16171     ["OVERVIEW" org-overview t]
16172     ["Refresh columns display" org-columns-redo t]
16173     "--"
16174     ["Open link" org-columns-open-link t]
16175     "--"
16176     ["Quit" org-columns-quit t]))
16178 (defun org-columns-new-overlay (beg end &optional string face)
16179   "Create a new column overlay and add it to the list."
16180   (let ((ov (org-make-overlay beg end)))
16181     (org-overlay-put ov 'face (or face 'secondary-selection))
16182     (org-overlay-display ov string face)
16183     (push ov org-columns-overlays)
16184     ov))
16186 (defun org-columns-display-here (&optional props)
16187   "Overlay the current line with column display."
16188   (interactive)
16189   (let* ((fmt org-columns-current-fmt-compiled)
16190          (beg (point-at-bol))
16191          (level-face (save-excursion
16192                        (beginning-of-line 1)
16193                        (and (looking-at "\\(\\**\\)\\(\\* \\)")
16194                             (org-get-level-face 2))))
16195          (color (list :foreground
16196                       (face-attribute (or level-face 'default) :foreground)))
16197          props pom property ass width f string ov column val modval)
16198     ;; Check if the entry is in another buffer.
16199     (unless props
16200       (if (eq major-mode 'org-agenda-mode)
16201           (setq pom (or (get-text-property (point) 'org-hd-marker)
16202                         (get-text-property (point) 'org-marker))
16203                 props (if pom (org-entry-properties pom) nil))
16204         (setq props (org-entry-properties nil))))
16205     ;; Walk the format
16206     (while (setq column (pop fmt))
16207       (setq property (car column)
16208             ass (if (equal property "ITEM")
16209                     (cons "ITEM"
16210                           (save-match-data
16211                             (org-no-properties
16212                              (org-remove-tabs
16213                               (buffer-substring-no-properties
16214                                (point-at-bol) (point-at-eol))))))
16215                   (assoc property props))
16216             width (or (cdr (assoc property org-columns-current-maxwidths))
16217                       (nth 2 column)
16218                       (length property))
16219             f (format "%%-%d.%ds | " width width)
16220             val (or (cdr ass) "")
16221             modval (if (equal property "ITEM")
16222                        (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16223             string (format f (or modval val)))
16224       ;; Create the overlay
16225       (org-unmodified
16226        (setq ov (org-columns-new-overlay
16227                  beg (setq beg (1+ beg)) string
16228                  (list color 'org-column)))
16229 ;;;       (list (get-text-property (point-at-bol) 'face) 'org-column)))
16230        (org-overlay-put ov 'keymap org-columns-map)
16231        (org-overlay-put ov 'org-columns-key property)
16232        (org-overlay-put ov 'org-columns-value (cdr ass))
16233        (org-overlay-put ov 'org-columns-value-modified modval)
16234        (org-overlay-put ov 'org-columns-pom pom)
16235        (org-overlay-put ov 'org-columns-format f))
16236       (if (or (not (char-after beg))
16237               (equal (char-after beg) ?\n))
16238           (let ((inhibit-read-only t))
16239             (save-excursion
16240               (goto-char beg)
16241               (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16242     ;; Make the rest of the line disappear.
16243     (org-unmodified
16244      (setq ov (org-columns-new-overlay beg (point-at-eol)))
16245      (org-overlay-put ov 'invisible t)
16246      (org-overlay-put ov 'keymap org-columns-map)
16247      (org-overlay-put ov 'intangible t)
16248      (push ov org-columns-overlays)
16249      (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16250      (org-overlay-put ov 'keymap org-columns-map)
16251      (push ov org-columns-overlays)
16252      (let ((inhibit-read-only t))
16253        (put-text-property (max (point-min) (1- (point-at-bol)))
16254                           (min (point-max) (1+ (point-at-eol)))
16255                           'read-only "Type `e' to edit property")))))
16257 (defvar org-previous-header-line-format nil
16258   "The header line format before column view was turned on.")
16259 (defvar org-columns-inhibit-recalculation nil
16260   "Inhibit recomputing of columns on column view startup.")
16263 (defvar header-line-format)
16264 (defun org-columns-display-here-title ()
16265   "Overlay the newline before the current line with the table title."
16266   (interactive)
16267   (let ((fmt org-columns-current-fmt-compiled)
16268         string (title "")
16269         property width f column str widths)
16270     (while (setq column (pop fmt))
16271       (setq property (car column)
16272             str (or (nth 1 column) property)
16273             width (or (cdr (assoc property org-columns-current-maxwidths))
16274                       (nth 2 column)
16275                       (length str))
16276             widths (push width widths)
16277             f (format "%%-%d.%ds | " width width)
16278             string (format f str)
16279             title (concat title string)))
16280     (setq title (concat
16281                  (org-add-props " " nil 'display '(space :align-to 0))
16282                  (org-add-props title nil 'face '(:weight bold :underline t))))
16283     (org-set-local 'org-previous-header-line-format header-line-format)
16284     (org-set-local 'org-columns-current-widths (nreverse widths))
16285     (setq header-line-format title)))
16287 (defun org-columns-remove-overlays ()
16288   "Remove all currently active column overlays."
16289   (interactive)
16290   (when (marker-buffer org-columns-begin-marker)
16291     (with-current-buffer (marker-buffer org-columns-begin-marker)
16292       (when (local-variable-p 'org-previous-header-line-format)
16293         (setq header-line-format org-previous-header-line-format)
16294         (kill-local-variable 'org-previous-header-line-format))
16295       (move-marker org-columns-begin-marker nil)
16296       (move-marker org-columns-top-level-marker nil)
16297       (org-unmodified
16298        (mapc 'org-delete-overlay org-columns-overlays)
16299        (setq org-columns-overlays nil)
16300        (let ((inhibit-read-only t))
16301          (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16303 (defun org-columns-cleanup-item (item fmt)
16304   "Remove from ITEM what is a column in the format FMT."
16305   (if (not org-complex-heading-regexp)
16306       item
16307     (when (string-match org-complex-heading-regexp item)
16308       (concat
16309        (org-add-props (concat (match-string 1 item) " ") nil
16310          'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16311        (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16312        (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16313        " " (match-string 4 item)
16314        (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16316 (defun org-columns-show-value ()
16317   "Show the full value of the property."
16318   (interactive)
16319   (let ((value (get-char-property (point) 'org-columns-value)))
16320     (message "Value is: %s" (or value ""))))
16322 (defun org-columns-quit ()
16323   "Remove the column overlays and in this way exit column editing."
16324   (interactive)
16325   (org-unmodified
16326    (org-columns-remove-overlays)
16327    (let ((inhibit-read-only t))
16328      (remove-text-properties (point-min) (point-max) '(read-only t))))
16329   (when (eq major-mode 'org-agenda-mode)
16330     (message
16331      "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16333 (defun org-columns-check-computed ()
16334   "Check if this column value is computed.
16335 If yes, throw an error indicating that changing it does not make sense."
16336   (let ((val (get-char-property (point) 'org-columns-value)))
16337     (when (and (stringp val)
16338                (get-char-property 0 'org-computed val))
16339       (error "This value is computed from the entry's children"))))
16341 (defun org-columns-todo (&optional arg)
16342   "Change the TODO state during column view."
16343   (interactive "P")
16344   (org-columns-edit-value "TODO"))
16346 (defun org-columns-set-tags-or-toggle (&optional arg)
16347   "Toggle checkbox at point, or set tags for current headline."
16348   (interactive "P")
16349   (if (string-match "\\`\\[[ xX-]\\]\\'"
16350                     (get-char-property (point) 'org-columns-value))
16351       (org-columns-next-allowed-value)
16352     (org-columns-edit-value "TAGS")))
16354 (defun org-columns-edit-value (&optional key)
16355   "Edit the value of the property at point in column view.
16356 Where possible, use the standard interface for changing this line."
16357   (interactive)
16358   (org-columns-check-computed)
16359   (let* ((external-key key)
16360          (col (current-column))
16361          (key (or key (get-char-property (point) 'org-columns-key)))
16362          (value (get-char-property (point) 'org-columns-value))
16363          (bol (point-at-bol)) (eol (point-at-eol))
16364          (pom (or (get-text-property bol 'org-hd-marker)
16365                   (point))) ; keep despite of compiler waring
16366          (line-overlays
16367           (delq nil (mapcar (lambda (x)
16368                               (and (eq (overlay-buffer x) (current-buffer))
16369                                    (>= (overlay-start x) bol)
16370                                    (<= (overlay-start x) eol)
16371                                    x))
16372                             org-columns-overlays)))
16373          nval eval allowed)
16374     (cond
16375      ((equal key "ITEM")
16376       (setq eval '(org-with-point-at pom
16377                     (org-edit-headline))))
16378      ((equal key "TODO")
16379       (setq eval '(org-with-point-at pom
16380                     (let ((current-prefix-arg
16381                            (if external-key current-prefix-arg '(4))))
16382                       (call-interactively 'org-todo)))))
16383      ((equal key "PRIORITY")
16384       (setq eval '(org-with-point-at pom
16385                     (call-interactively 'org-priority))))
16386      ((equal key "TAGS")
16387       (setq eval '(org-with-point-at pom
16388                     (let ((org-fast-tag-selection-single-key
16389                            (if (eq org-fast-tag-selection-single-key 'expert)
16390                                t org-fast-tag-selection-single-key)))
16391                       (call-interactively 'org-set-tags)))))
16392      ((equal key "DEADLINE")
16393       (setq eval '(org-with-point-at pom
16394                     (call-interactively 'org-deadline))))
16395      ((equal key "SCHEDULED")
16396       (setq eval '(org-with-point-at pom
16397                     (call-interactively 'org-schedule))))
16398      (t
16399       (setq allowed (org-property-get-allowed-values pom key 'table))
16400       (if allowed
16401           (setq nval (completing-read "Value: " allowed nil t))
16402         (setq nval (read-string "Edit: " value)))
16403       (setq nval (org-trim nval))
16404       (when (not (equal nval value))
16405         (setq eval '(org-entry-put pom key nval)))))
16406     (when eval
16407       (let ((inhibit-read-only t))
16408         (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16409         (unwind-protect
16410             (progn
16411               (setq org-columns-overlays
16412                     (org-delete-all line-overlays org-columns-overlays))
16413               (mapc 'org-delete-overlay line-overlays)
16414               (org-columns-eval eval))
16415           (org-columns-display-here))))
16416     (move-to-column col)
16417     (if (nth 3 (assoc key org-columns-current-fmt-compiled))
16418         (org-columns-update key))))
16420 (defun org-edit-headline () ; FIXME: this is not columns specific
16421   "Edit the current headline, the part without TODO keyword, TAGS."
16422   (org-back-to-heading)
16423   (when (looking-at org-todo-line-regexp)
16424     (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16425           (txt (match-string 3))
16426           (post "")
16427           txt2)
16428       (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16429           (setq post (match-string 0 txt)
16430                 txt (substring txt 0 (match-beginning 0))))
16431       (setq txt2 (read-string "Edit: " txt))
16432       (when (not (equal txt txt2))
16433         (beginning-of-line 1)
16434         (insert pre txt2 post)
16435         (delete-region (point) (point-at-eol))
16436         (org-set-tags nil t)))))
16438 (defun org-columns-edit-allowed ()
16439   "Edit the list of allowed values for the current property."
16440   (interactive)
16441   (let* ((key (get-char-property (point) 'org-columns-key))
16442          (key1 (concat key "_ALL"))
16443          (allowed (org-entry-get (point) key1 t))
16444          nval)
16445     ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16446     (setq nval (read-string "Allowed: " allowed))
16447     (org-entry-put
16448      (cond ((marker-position org-entry-property-inherited-from)
16449             org-entry-property-inherited-from)
16450            ((marker-position org-columns-top-level-marker)
16451             org-columns-top-level-marker))
16452      key1 nval)))
16454 (defmacro org-no-warnings (&rest body)
16455   (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16457 (defun org-columns-eval (form)
16458   (let (hidep)
16459     (save-excursion
16460       (beginning-of-line 1)
16461       ;; `next-line' is needed here, because it skips invisible line.
16462       (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16463       (setq hidep (org-on-heading-p 1)))
16464     (eval form)
16465     (and hidep (hide-entry))))
16467 (defun org-columns-previous-allowed-value ()
16468   "Switch to the previous allowed value for this column."
16469   (interactive)
16470   (org-columns-next-allowed-value t))
16472 (defun org-columns-next-allowed-value (&optional previous)
16473   "Switch to the next allowed value for this column."
16474   (interactive)
16475   (org-columns-check-computed)
16476   (let* ((col (current-column))
16477          (key (get-char-property (point) 'org-columns-key))
16478          (value (get-char-property (point) 'org-columns-value))
16479          (bol (point-at-bol)) (eol (point-at-eol))
16480          (pom (or (get-text-property bol 'org-hd-marker)
16481                   (point))) ; keep despite of compiler waring
16482          (line-overlays
16483           (delq nil (mapcar (lambda (x)
16484                               (and (eq (overlay-buffer x) (current-buffer))
16485                                    (>= (overlay-start x) bol)
16486                                    (<= (overlay-start x) eol)
16487                                    x))
16488                             org-columns-overlays)))
16489          (allowed (or (org-property-get-allowed-values pom key)
16490                       (and (equal
16491                             (nth 4 (assoc key org-columns-current-fmt-compiled))
16492                             'checkbox) '("[ ]" "[X]"))))
16493          nval)
16494     (when (equal key "ITEM")
16495       (error "Cannot edit item headline from here"))
16496     (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16497       (error "Allowed values for this property have not been defined"))
16498     (if (member key '("SCHEDULED" "DEADLINE"))
16499         (setq nval (if previous 'earlier 'later))
16500       (if previous (setq allowed (reverse allowed)))
16501       (if (member value allowed)
16502           (setq nval (car (cdr (member value allowed)))))
16503       (setq nval (or nval (car allowed)))
16504       (if (equal nval value)
16505           (error "Only one allowed value for this property")))
16506     (let ((inhibit-read-only t))
16507       (remove-text-properties (1- bol) eol '(read-only t))
16508       (unwind-protect
16509           (progn
16510             (setq org-columns-overlays
16511                   (org-delete-all line-overlays org-columns-overlays))
16512             (mapc 'org-delete-overlay line-overlays)
16513             (org-columns-eval '(org-entry-put pom key nval)))
16514         (org-columns-display-here)))
16515     (move-to-column col)
16516     (if (nth 3 (assoc key org-columns-current-fmt-compiled))
16517         (org-columns-update key))))
16519 (defun org-verify-version (task)
16520   (cond
16521    ((eq task 'columns)
16522     (if (or (featurep 'xemacs)
16523             (< emacs-major-version 22))
16524         (error "Emacs 22 is required for the columns feature")))))
16526 (defun org-columns-open-link (&optional arg)
16527   (interactive "P")
16528   (let ((key (get-char-property (point) 'org-columns-key))
16529         (value (get-char-property (point) 'org-columns-value)))
16530     (org-open-link-from-string arg)))
16532 (defun org-open-link-from-string (s &optional arg)
16533   "Open a link in the string S, as if it was in Org-mode."
16534   (interactive)
16535   (with-temp-buffer
16536     (let ((org-inhibit-startup t))
16537       (org-mode)
16538       (insert s)
16539       (goto-char (point-min))
16540       (org-open-at-point arg))))
16542 (defun org-columns-get-format-and-top-level ()
16543   (let (fmt)
16544     (when (condition-case nil (org-back-to-heading) (error nil))
16545       (move-marker org-entry-property-inherited-from nil)
16546       (setq fmt (org-entry-get nil "COLUMNS" t)))
16547     (setq fmt (or fmt org-columns-default-format))
16548     (org-set-local 'org-columns-current-fmt fmt)
16549     (org-columns-compile-format fmt)
16550     (if (marker-position org-entry-property-inherited-from)
16551         (move-marker org-columns-top-level-marker
16552                      org-entry-property-inherited-from)
16553       (move-marker org-columns-top-level-marker (point)))
16554     fmt))
16556 (defun org-columns ()
16557   "Turn on column view on an org-mode file."
16558   (interactive)
16559   (org-verify-version 'columns)
16560   (org-columns-remove-overlays)
16561   (move-marker org-columns-begin-marker (point))
16562   (let (beg end fmt cache maxwidths)
16563     (setq fmt (org-columns-get-format-and-top-level))
16564     (save-excursion
16565       (goto-char org-columns-top-level-marker)
16566       (setq beg (point))
16567       (unless org-columns-inhibit-recalculation
16568         (org-columns-compute-all))
16569       (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16570                     (point-max)))
16571       (goto-char beg)
16572       ;; Get and cache the properties
16573       (while (re-search-forward (concat "^" outline-regexp) end t)
16574         (push (cons (org-current-line) (org-entry-properties)) cache))
16575       (when cache
16576         (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16577         (org-set-local 'org-columns-current-maxwidths maxwidths)
16578         (org-columns-display-here-title)
16579         (mapc (lambda (x)
16580                 (goto-line (car x))
16581                 (org-columns-display-here (cdr x)))
16582               cache)))))
16584 (defun org-columns-new (&optional prop title width op fmt)
16585   "Insert a new column, to the leeft o the current column."
16586   (interactive)
16587   (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16588         cell)
16589     (setq prop (completing-read
16590                 "Property: " (mapcar 'list (org-buffer-property-keys t))
16591                 nil nil prop))
16592     (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16593     (setq width (read-string "Column width: " (if width (number-to-string width))))
16594     (if (string-match "\\S-" width)
16595         (setq width (string-to-number width))
16596       (setq width nil))
16597     (setq fmt (completing-read "Summary [none]: "
16598                                '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox"))
16599                                nil t))
16600     (if (string-match "\\S-" fmt)
16601         (setq fmt (intern fmt))
16602       (setq fmt nil))
16603     (if (eq fmt 'none) (setq fmt nil))
16604     (if editp
16605         (progn
16606           (setcar editp prop)
16607           (setcdr editp (list title width nil fmt)))
16608       (setq cell (nthcdr (1- (current-column))
16609                          org-columns-current-fmt-compiled))
16610       (setcdr cell (cons (list prop title width nil fmt)
16611                          (cdr cell))))
16612     (org-columns-store-format)
16613     (org-columns-redo)))
16615 (defun org-columns-delete ()
16616   "Delete the column at point from columns view."
16617   (interactive)
16618   (let* ((n (current-column))
16619          (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16620     (when (y-or-n-p
16621            (format "Are you sure you want to remove column \"%s\"? " title))
16622       (setq org-columns-current-fmt-compiled
16623             (delq (nth n org-columns-current-fmt-compiled)
16624                   org-columns-current-fmt-compiled))
16625       (org-columns-store-format)
16626       (org-columns-redo)
16627       (if (>= (current-column) (length org-columns-current-fmt-compiled))
16628           (backward-char 1)))))
16630 (defun org-columns-edit-attributes ()
16631   "Edit the attributes of the current column."
16632   (interactive)
16633   (let* ((n (current-column))
16634          (info (nth n org-columns-current-fmt-compiled)))
16635     (apply 'org-columns-new info)))
16637 (defun org-columns-widen (arg)
16638   "Make the column wider by ARG characters."
16639   (interactive "p")
16640   (let* ((n (current-column))
16641          (entry (nth n org-columns-current-fmt-compiled))
16642          (width (or (nth 2 entry)
16643                     (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16644     (setq width (max 1 (+ width arg)))
16645     (setcar (nthcdr 2 entry) width)
16646     (org-columns-store-format)
16647     (org-columns-redo)))
16649 (defun org-columns-narrow (arg)
16650   "Make the column nrrower by ARG characters."
16651   (interactive "p")
16652   (org-columns-widen (- arg)))
16654 (defun org-columns-move-right ()
16655   "Swap this column with the one to the right."
16656   (interactive)
16657   (let* ((n (current-column))
16658          (cell (nthcdr n org-columns-current-fmt-compiled))
16659          e)
16660     (when (>= n (1- (length org-columns-current-fmt-compiled)))
16661       (error "Cannot shift this column further to the right"))
16662     (setq e (car cell))
16663     (setcar cell (car (cdr cell)))
16664     (setcdr cell (cons e (cdr (cdr cell))))
16665     (org-columns-store-format)
16666     (org-columns-redo)
16667     (forward-char 1)))
16669 (defun org-columns-move-left ()
16670   "Swap this column with the one to the left."
16671   (interactive)
16672   (let* ((n (current-column)))
16673     (when (= n 0)
16674       (error "Cannot shift this column further to the left"))
16675     (backward-char 1)
16676     (org-columns-move-right)
16677     (backward-char 1)))
16679 (defun org-columns-store-format ()
16680   "Store the text version of the current columns format in appropriate place.
16681 This is either in the COLUMNS property of the node starting the current column
16682 display, or in the #+COLUMNS line of the current buffer."
16683   (let (fmt (cnt 0))
16684     (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
16685     (org-set-local 'org-columns-current-fmt fmt)
16686     (if (marker-position org-columns-top-level-marker)
16687         (save-excursion
16688           (goto-char org-columns-top-level-marker)
16689           (if (and (org-at-heading-p)
16690                    (org-entry-get nil "COLUMNS"))
16691               (org-entry-put nil "COLUMNS" fmt)
16692             (goto-char (point-min))
16693             ;; Overwrite all #+COLUMNS lines....
16694             (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
16695               (setq cnt (1+ cnt))
16696               (replace-match (concat "#+COLUMNS: " fmt) t t))
16697             (unless (> cnt 0)
16698               (goto-char (point-min))
16699               (or (org-on-heading-p t) (outline-next-heading))
16700               (let ((inhibit-read-only t))
16701                 (insert-before-markers "#+COLUMNS: " fmt "\n")))
16702             (org-set-local 'org-columns-default-format fmt))))))
16704 (defvar org-overriding-columns-format nil
16705   "When set, overrides any other definition.")
16706 (defvar org-agenda-view-columns-initially nil
16707   "When set, switch to columns view immediately after creating the agenda.")
16709 (defun org-agenda-columns ()
16710   "Turn on column view in the agenda."
16711   (interactive)
16712   (org-verify-version 'columns)
16713   (org-columns-remove-overlays)
16714   (move-marker org-columns-begin-marker (point))
16715   (let (fmt cache maxwidths m)
16716     (cond
16717      ((and (local-variable-p 'org-overriding-columns-format)
16718            org-overriding-columns-format)
16719       (setq fmt org-overriding-columns-format))
16720      ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
16721       (setq fmt (org-entry-get m "COLUMNS" t)))
16722      ((and (boundp 'org-columns-current-fmt)
16723            (local-variable-p 'org-columns-current-fmt)
16724            org-columns-current-fmt)
16725       (setq fmt org-columns-current-fmt))
16726      ((setq m (next-single-property-change (point-min) 'org-hd-marker))
16727       (setq m (get-text-property m 'org-hd-marker))
16728       (setq fmt (org-entry-get m "COLUMNS" t))))
16729     (setq fmt (or fmt org-columns-default-format))
16730     (org-set-local 'org-columns-current-fmt fmt)
16731     (org-columns-compile-format fmt)
16732     (save-excursion
16733       ;; Get and cache the properties
16734       (goto-char (point-min))
16735       (while (not (eobp))
16736         (when (setq m (or (get-text-property (point) 'org-hd-marker)
16737                           (get-text-property (point) 'org-marker)))
16738           (push (cons (org-current-line) (org-entry-properties m)) cache))
16739         (beginning-of-line 2))
16740       (when cache
16741         (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16742         (org-set-local 'org-columns-current-maxwidths maxwidths)
16743         (org-columns-display-here-title)
16744         (mapc (lambda (x)
16745                 (goto-line (car x))
16746                 (org-columns-display-here (cdr x)))
16747               cache)))))
16749 (defun org-columns-get-autowidth-alist (s cache)
16750   "Derive the maximum column widths from the format and the cache."
16751   (let ((start 0) rtn)
16752     (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
16753       (push (cons (match-string 1 s) 1) rtn)
16754       (setq start (match-end 0)))
16755     (mapc (lambda (x)
16756             (setcdr x (apply 'max
16757                              (mapcar
16758                               (lambda (y)
16759                                 (length (or (cdr (assoc (car x) (cdr y))) " ")))
16760                               cache))))
16761           rtn)
16762     rtn))
16764 (defun org-columns-compute-all ()
16765   "Compute all columns that have operators defined."
16766   (org-unmodified
16767    (remove-text-properties (point-min) (point-max) '(org-summaries t)))
16768   (let ((columns org-columns-current-fmt-compiled) col)
16769     (while (setq col (pop columns))
16770       (when (nth 3 col)
16771         (save-excursion
16772           (org-columns-compute (car col)))))))
16774 (defun org-columns-update (property)
16775   "Recompute PROPERTY, and update the columns display for it."
16776   (org-columns-compute property)
16777   (let (fmt val pos)
16778     (save-excursion
16779       (mapc (lambda (ov)
16780               (when (equal (org-overlay-get ov 'org-columns-key) property)
16781                 (setq pos (org-overlay-start ov))
16782                 (goto-char pos)
16783                 (when (setq val (cdr (assoc property
16784                                             (get-text-property
16785                                              (point-at-bol) 'org-summaries))))
16786                   (setq fmt (org-overlay-get ov 'org-columns-format))
16787                   (org-overlay-put ov 'org-columns-value val)
16788                   (org-overlay-put ov 'display (format fmt val)))))
16789             org-columns-overlays))))
16791 (defun org-columns-compute (property)
16792   "Sum the values of property PROPERTY hierarchically, for the entire buffer."
16793   (interactive)
16794   (let* ((re (concat "^" outline-regexp))
16795          (lmax 30) ; Does anyone use deeper levels???
16796          (lsum (make-vector lmax 0))
16797          (lflag (make-vector lmax nil))
16798          (level 0)
16799          (ass (assoc property org-columns-current-fmt-compiled))
16800          (format (nth 4 ass))
16801          (printf (nth 5 ass))
16802          (beg org-columns-top-level-marker)
16803          last-level val valflag flag end sumpos sum-alist sum str str1 useval)
16804     (save-excursion
16805       ;; Find the region to compute
16806       (goto-char beg)
16807       (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
16808       (goto-char end)
16809       ;; Walk the tree from the back and do the computations
16810       (while (re-search-backward re beg t)
16811         (setq sumpos (match-beginning 0)
16812               last-level level
16813               level (org-outline-level)
16814               val (org-entry-get nil property)
16815               valflag (and val (string-match "\\S-" val)))
16816         (cond
16817          ((< level last-level)
16818           ;; put the sum of lower levels here as a property
16819           (setq sum (aref lsum last-level)   ; current sum
16820                 flag (aref lflag last-level) ; any valid entries from children?
16821                 str (org-column-number-to-string sum format printf)
16822                 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
16823                 useval (if flag str1 (if valflag val ""))
16824                 sum-alist (get-text-property sumpos 'org-summaries))
16825           (if (assoc property sum-alist)
16826               (setcdr (assoc property sum-alist) useval)
16827             (push (cons property useval) sum-alist)
16828             (org-unmodified
16829              (add-text-properties sumpos (1+ sumpos)
16830                                   (list 'org-summaries sum-alist))))
16831           (when val
16832             (org-entry-put nil property (if flag str val)))
16833           ;; add current to current  level accumulator
16834           (when (or flag valflag)
16835             (aset lsum level (+ (aref lsum level)
16836                                 (if flag sum (org-column-string-to-number
16837                                               (if flag str val) format))))
16838             (aset lflag level t))
16839           ;; clear accumulators for deeper levels
16840           (loop for l from (1+ level) to (1- lmax) do
16841                 (aset lsum l 0)
16842                 (aset lflag l nil)))
16843          ((>= level last-level)
16844           ;; add what we have here to the accumulator for this level
16845           (aset lsum level (+ (aref lsum level)
16846                               (org-column-string-to-number (or val "0") format)))
16847           (and valflag (aset lflag level t)))
16848          (t (error "This should not happen")))))))
16850 (defun org-columns-redo ()
16851   "Construct the column display again."
16852   (interactive)
16853   (message "Recomputing columns...")
16854   (save-excursion
16855     (if (marker-position org-columns-begin-marker)
16856         (goto-char org-columns-begin-marker))
16857     (org-columns-remove-overlays)
16858     (if (org-mode-p)
16859         (call-interactively 'org-columns)
16860       (call-interactively 'org-agenda-columns)))
16861   (message "Recomputing columns...done"))
16863 (defun org-columns-not-in-agenda ()
16864   (if (eq major-mode 'org-agenda-mode)
16865       (error "This command is only allowed in Org-mode buffers")))
16868 (defun org-string-to-number (s)
16869   "Convert string to number, and interpret hh:mm:ss."
16870   (if (not (string-match ":" s))
16871       (string-to-number s)
16872     (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16873       (while l
16874         (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16875       sum)))
16877 (defun org-column-number-to-string (n fmt printf)
16878   "Convert a computed column number to a string value, according to FMT."
16879   (cond
16880    ((eq fmt 'add_times)
16881     (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
16882       (format "%d:%02d" h m)))
16883    ((eq fmt 'checkbox)
16884     (cond ((= n (floor n)) "[X]")
16885           ((> n 1.) "[-]")
16886           (t "[ ]")))
16887    (printf (format printf n))
16888    ((eq fmt 'currency)
16889     (format "%.2f" n))
16890    (t (number-to-string n))))
16892 (defun org-column-string-to-number (s fmt)
16893   "Convert a column value to a number that can be used for column computing."
16894   (cond
16895    ((string-match ":" s)
16896     (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16897       (while l
16898         (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16899       sum))
16900    ((eq fmt 'checkbox)
16901     (if (equal s "[X]") 1. 0.000001))
16902    (t (string-to-number s))))
16904 (defun org-columns-uncompile-format (cfmt)
16905   "Turn the compiled columns format back into a string representation."
16906   (let ((rtn "") e s prop title op width fmt printf)
16907     (while (setq e (pop cfmt))
16908       (setq prop (car e)
16909             title (nth 1 e)
16910             width (nth 2 e)
16911             op (nth 3 e)
16912             fmt (nth 4 e)
16913             printf (nth 5 e))
16914       (cond
16915        ((eq fmt 'add_times) (setq op ":"))
16916        ((eq fmt 'checkbox) (setq op "X"))
16917        ((eq fmt 'add_numbers) (setq op "+"))
16918        ((eq fmt 'currency) (setq op "$")))
16919       (if (and op printf) (setq op (concat op ";" printf)))
16920       (if (equal title prop) (setq title nil))
16921       (setq s (concat "%" (if width (number-to-string width))
16922                       prop
16923                       (if title (concat "(" title ")"))
16924                       (if op (concat "{" op "}"))))
16925       (setq rtn (concat rtn " " s)))
16926     (org-trim rtn)))
16928 (defun org-columns-compile-format (fmt)
16929   "Turn a column format string into an alist of specifications.
16930 The alist has one entry for each column in the format.  The elements of
16931 that list are:
16932 property     the property
16933 title        the title field for the columns
16934 width        the column width in characters, can be nil for automatic
16935 operator     the operator if any
16936 format       the output format for computed results, derived from operator
16937 printf       a printf format for computed values"
16938   (let ((start 0) width prop title op f printf)
16939     (setq org-columns-current-fmt-compiled nil)
16940     (while (string-match
16941             (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
16942             fmt start)
16943       (setq start (match-end 0)
16944             width (match-string 1 fmt)
16945             prop (match-string 2 fmt)
16946             title (or (match-string 3 fmt) prop)
16947             op (match-string 4 fmt)
16948             f nil
16949             printf nil)
16950       (if width (setq width (string-to-number width)))
16951       (when (and op (string-match ";" op))
16952         (setq printf (substring op (match-end 0))
16953               op (substring op 0 (match-beginning 0))))
16954       (cond
16955        ((equal op "+") (setq f 'add_numbers))
16956        ((equal op "$") (setq f 'currency))
16957        ((equal op ":") (setq f 'add_times))
16958        ((equal op "X") (setq f 'checkbox)))
16959       (push (list prop title width op f printf) org-columns-current-fmt-compiled))
16960     (setq org-columns-current-fmt-compiled
16961           (nreverse org-columns-current-fmt-compiled))))
16964 ;;; Dynamic block for Column view
16966 (defun org-columns-capture-view ()
16967   "Get the column view of the current buffer and return it as a list.
16968 The list will contains the title row and all other rows.  Each row is
16969 a list of fields."
16970   (save-excursion
16971     (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
16972            (n (length title)) row tbl)
16973       (goto-char (point-min))
16974       (while (re-search-forward "^\\*+ " nil t)
16975         (when (get-char-property (match-beginning 0) 'org-columns-key)
16976           (setq row nil)
16977           (loop for i from 0 to (1- n) do
16978                 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
16979                           (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
16980                           "")
16981                       row))
16982           (setq row (nreverse row))
16983           (push row tbl)))
16984       (append (list title 'hline) (nreverse tbl)))))
16986 (defun org-dblock-write:columnview (params)
16987   "Write the column view table.
16988 PARAMS is a property list of parameters:
16990 :width    enforce same column widths with <N> specifiers.
16991 :id       the :ID: property of the entry where the columns view
16992           should be built, as a string.  When `local', call locally.
16993           When `global' call column view with the cursor at the beginning
16994           of the buffer (usually this means that the whole buffer switches
16995           to column view).
16996 :hlines   When t, insert a hline before each item.  When a number, insert
16997           a hline before each level <= that number.
16998 :vlines   When t, make each column a colgroup to enforce vertical lines."
16999   (let ((pos (move-marker (make-marker) (point)))
17000         (hlines (plist-get params :hlines))
17001         (vlines (plist-get params :vlines))
17002         tbl id idpos nfields tmp)
17003     (save-excursion
17004       (save-restriction
17005         (when (setq id (plist-get params :id))
17006           (cond ((not id) nil)
17007                 ((eq id 'global) (goto-char (point-min)))
17008                 ((eq id 'local)  nil)
17009                 ((setq idpos (org-find-entry-with-id id))
17010                  (goto-char idpos))
17011                 (t (error "Cannot find entry with :ID: %s" id))))
17012         (org-columns)
17013         (setq tbl (org-columns-capture-view))
17014         (setq nfields (length (car tbl)))
17015         (org-columns-quit)))
17016     (goto-char pos)
17017     (move-marker pos nil)
17018     (when tbl
17019       (when (plist-get params :hlines)
17020         (setq tmp nil)
17021         (while tbl
17022           (if (eq (car tbl) 'hline)
17023               (push (pop tbl) tmp)
17024             (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17025                 (if (and (not (eq (car tmp) 'hline))
17026                          (or (eq hlines t)
17027                              (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17028                     (push 'hline tmp)))
17029             (push (pop tbl) tmp)))
17030         (setq tbl (nreverse tmp)))
17031       (when vlines
17032         (setq tbl (mapcar (lambda (x)
17033                             (if (eq 'hline x) x (cons "" x)))
17034                           tbl))
17035         (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17036       (setq pos (point))
17037       (insert (org-listtable-to-string tbl))
17038       (when (plist-get params :width)
17039         (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17040                                  org-columns-current-widths "|")))
17041       (goto-char pos)
17042       (org-table-align))))
17044 (defun org-listtable-to-string (tbl)
17045   "Convert a listtable TBL to a string that contains the Org-mode table.
17046 The table still need to be alligned.  The resulting string has no leading
17047 and tailing newline characters."
17048   (mapconcat
17049    (lambda (x)
17050      (cond
17051       ((listp x)
17052        (concat "|" (mapconcat 'identity x "|") "|"))
17053       ((eq x 'hline) "|-|")
17054       (t (error "Garbage in listtable: %s" x))))
17055    tbl "\n"))
17057 (defun org-insert-columns-dblock ()
17058   "Create a dynamic block capturing a column view table."
17059   (interactive)
17060   (let ((defaults '(:name "columnview" :hlines 1))
17061         (id (completing-read
17062              "Capture columns (local, global, entry with :ID: property) [local]: "
17063              (append '(("global") ("local"))
17064                      (mapcar 'list (org-property-values "ID"))))))
17065     (if (equal id "") (setq id 'local))
17066     (if (equal id "global") (setq id 'global))
17067     (setq defaults (append defaults (list :id id)))
17068     (org-create-dblock defaults)
17069     (org-update-dblock)))
17071 ;;;; Timestamps
17073 (defvar org-last-changed-timestamp nil)
17074 (defvar org-time-was-given) ; dynamically scoped parameter
17075 (defvar org-end-time-was-given) ; dynamically scoped parameter
17076 (defvar org-ts-what) ; dynamically scoped parameter
17078 (defun org-time-stamp (arg)
17079   "Prompt for a date/time and insert a time stamp.
17080 If the user specifies a time like HH:MM, or if this command is called
17081 with a prefix argument, the time stamp will contain date and time.
17082 Otherwise, only the date will be included.  All parts of a date not
17083 specified by the user will be filled in from the current date/time.
17084 So if you press just return without typing anything, the time stamp
17085 will represent the current date/time.  If there is already a timestamp
17086 at the cursor, it will be modified."
17087   (interactive "P")
17088   (let* ((ts nil)
17089          (default-time
17090            ;; Default time is either today, or, when entering a range,
17091            ;; the range start.
17092            (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17093                    (save-excursion
17094                      (re-search-backward
17095                       (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17096                       (- (point) 20) t)))
17097                (apply 'encode-time (org-parse-time-string (match-string 1)))
17098              (current-time)))
17099          (default-input (and ts (org-get-compact-tod ts)))
17100          org-time-was-given org-end-time-was-given time)
17101     (cond
17102      ((and (org-at-timestamp-p)
17103            (eq last-command 'org-time-stamp)
17104            (eq this-command 'org-time-stamp))
17105       (insert "--")
17106       (setq time (let ((this-command this-command))
17107                   (org-read-date arg 'totime nil nil default-time default-input)))
17108       (org-insert-time-stamp time (or org-time-was-given arg)))
17109      ((org-at-timestamp-p)
17110       (setq time (let ((this-command this-command))
17111                    (org-read-date arg 'totime nil nil default-time default-input)))
17112       (when (org-at-timestamp-p) ; just to get the match data
17113         (replace-match "")
17114         (setq org-last-changed-timestamp
17115               (org-insert-time-stamp
17116                time (or org-time-was-given arg)
17117                nil nil nil (list org-end-time-was-given))))
17118       (message "Timestamp updated"))
17119      (t
17120       (setq time (let ((this-command this-command))
17121                    (org-read-date arg 'totime nil nil default-time default-input)))
17122       (org-insert-time-stamp time (or org-time-was-given arg)
17123                              nil nil nil (list org-end-time-was-given))))))
17125 ;; FIXME: can we use this for something else????
17126 ;; like computing time differences?????
17127 (defun org-get-compact-tod (s)
17128   (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17129     (let* ((t1 (match-string 1 s))
17130            (h1 (string-to-number (match-string 2 s)))
17131            (m1 (string-to-number (match-string 3 s)))
17132            (t2 (and (match-end 4) (match-string 5 s)))
17133            (h2 (and t2 (string-to-number (match-string 6 s))))
17134            (m2 (and t2 (string-to-number (match-string 7 s))))
17135            dh dm)
17136       (if (not t2)
17137           t1
17138         (setq dh (- h2 h1) dm (- m2 m1))
17139         (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17140         (concat t1 "+" (number-to-string dh)
17141                 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17143 (defun org-time-stamp-inactive (&optional arg)
17144   "Insert an inactive time stamp.
17145 An inactive time stamp is enclosed in square brackets instead of angle
17146 brackets.  It is inactive in the sense that it does not trigger agenda entries,
17147 does not link to the calendar and cannot be changed with the S-cursor keys.
17148 So these are more for recording a certain time/date."
17149   (interactive "P")
17150   (let (org-time-was-given org-end-time-was-given time)
17151     (setq time (org-read-date arg 'totime))
17152     (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17153                            nil nil (list org-end-time-was-given))))
17155 (defvar org-date-ovl (org-make-overlay 1 1))
17156 (org-overlay-put org-date-ovl 'face 'org-warning)
17157 (org-detach-overlay org-date-ovl)
17159 (defvar org-ans1) ; dynamically scoped parameter
17160 (defvar org-ans2) ; dynamically scoped parameter
17162 (defvar org-plain-time-of-day-regexp) ; defined below
17164 (defvar org-read-date-overlay nil)
17165 (defvar org-dcst nil) ; dynamically scoped
17167 (defun org-read-date (&optional with-time to-time from-string prompt
17168                                 default-time default-input)
17169   "Read a date, possibly a time, and make things smooth for the user.
17170 The prompt will suggest to enter an ISO date, but you can also enter anything
17171 which will at least partially be understood by `parse-time-string'.
17172 Unrecognized parts of the date will default to the current day, month, year,
17173 hour and minute.  If this command is called to replace a timestamp at point,
17174 of to enter the second timestamp of a range, the default time is taken from the
17175 existing stamp.  For example,
17176   3-2-5         --> 2003-02-05
17177   feb 15        --> currentyear-02-15
17178   sep 12 9      --> 2009-09-12
17179   12:45         --> today 12:45
17180   22 sept 0:34  --> currentyear-09-22 0:34
17181   12            --> currentyear-currentmonth-12
17182   Fri           --> nearest Friday (today or later)
17183   etc.
17185 Furthermore you can specify a relative date by giving, as the *first* thing
17186 in the input:  a plus/minus sign, a number and a letter [dwmy] to indicate
17187 change in days weeks, months, years.
17188 With a single plus or minus, the date is relative to today.  With a double
17189 plus or minus, it is relative to the date in DEFAULT-TIME.  E.g.
17190   +4d           --> four days from today
17191   +4            --> same as above
17192   +2w           --> two weeks from today
17193   ++5           --> five days from default date
17195 The function understands only English month and weekday abbreviations,
17196 but this can be configured with the variables `parse-time-months' and
17197 `parse-time-weekdays'.
17199 While prompting, a calendar is popped up - you can also select the
17200 date with the mouse (button 1).  The calendar shows a period of three
17201 months.  To scroll it to other months, use the keys `>' and `<'.
17202 If you don't like the calendar, turn it off with
17203        \(setq org-read-date-popup-calendar nil)
17205 With optional argument TO-TIME, the date will immediately be converted
17206 to an internal time.
17207 With an optional argument WITH-TIME, the prompt will suggest to also
17208 insert a time.  Note that when WITH-TIME is not set, you can still
17209 enter a time, and this function will inform the calling routine about
17210 this change.  The calling routine may then choose to change the format
17211 used to insert the time stamp into the buffer to include the time.
17212 With optional argument FROM-STRING, read from this string instead from
17213 the user.  PROMPT can overwrite the default prompt.  DEFAULT-TIME is
17214 the time/date that is used for everything that is not specified by the
17215 user."
17216   (require 'parse-time)
17217   (let* ((org-time-stamp-rounding-minutes
17218           (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17219          (org-dcst org-display-custom-times)
17220          (ct (org-current-time))
17221          (def (or default-time ct))
17222          (defdecode (decode-time def))
17223          (dummy (progn
17224                   (when (< (nth 2 defdecode) org-extend-today-until)
17225                     (setcar (nthcdr 2 defdecode) -1)
17226                     (setcar (nthcdr 1 defdecode) 59)
17227                     (setq def (apply 'encode-time defdecode)
17228                           defdecode (decode-time def)))))
17229          (calendar-move-hook nil)
17230          (view-diary-entries-initially nil)
17231          (view-calendar-holidays-initially nil)
17232          (timestr (format-time-string
17233                    (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17234          (prompt (concat (if prompt (concat prompt " ") "")
17235                          (format "Date+time [%s]: " timestr)))
17236          ans (org-ans0 "") org-ans1 org-ans2 final)
17238     (cond
17239      (from-string (setq ans from-string))
17240      (org-read-date-popup-calendar
17241       (save-excursion
17242         (save-window-excursion
17243           (calendar)
17244           (calendar-forward-day (- (time-to-days def)
17245                                    (calendar-absolute-from-gregorian
17246                                     (calendar-current-date))))
17247           (org-eval-in-calendar nil t)
17248           (let* ((old-map (current-local-map))
17249                  (map (copy-keymap calendar-mode-map))
17250                  (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17251             (org-defkey map (kbd "RET") 'org-calendar-select)
17252             (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17253               'org-calendar-select-mouse)
17254             (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17255               'org-calendar-select-mouse)
17256             (org-defkey minibuffer-local-map [(meta shift left)]
17257               (lambda () (interactive)
17258                 (org-eval-in-calendar '(calendar-backward-month 1))))
17259             (org-defkey minibuffer-local-map [(meta shift right)]
17260               (lambda () (interactive)
17261                 (org-eval-in-calendar '(calendar-forward-month 1))))
17262             (org-defkey minibuffer-local-map [(meta shift up)]
17263               (lambda () (interactive)
17264                 (org-eval-in-calendar '(calendar-backward-year 1))))
17265             (org-defkey minibuffer-local-map [(meta shift down)]
17266               (lambda () (interactive)
17267                 (org-eval-in-calendar '(calendar-forward-year 1))))
17268             (org-defkey minibuffer-local-map [(shift up)]
17269               (lambda () (interactive)
17270                 (org-eval-in-calendar '(calendar-backward-week 1))))
17271             (org-defkey minibuffer-local-map [(shift down)]
17272               (lambda () (interactive)
17273                 (org-eval-in-calendar '(calendar-forward-week 1))))
17274             (org-defkey minibuffer-local-map [(shift left)]
17275               (lambda () (interactive)
17276                 (org-eval-in-calendar '(calendar-backward-day 1))))
17277             (org-defkey minibuffer-local-map [(shift right)]
17278               (lambda () (interactive)
17279                 (org-eval-in-calendar '(calendar-forward-day 1))))
17280             (org-defkey minibuffer-local-map ">"
17281               (lambda () (interactive)
17282                 (org-eval-in-calendar '(scroll-calendar-left 1))))
17283             (org-defkey minibuffer-local-map "<"
17284               (lambda () (interactive)
17285                 (org-eval-in-calendar '(scroll-calendar-right 1))))
17286             (unwind-protect
17287                 (progn
17288                   (use-local-map map)
17289                   (add-hook 'post-command-hook 'org-read-date-display)
17290                   (setq org-ans0 (read-string prompt default-input nil nil))
17291                   ;; org-ans0: from prompt
17292                   ;; org-ans1: from mouse click
17293                   ;; org-ans2: from calendar motion
17294                   (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17295               (remove-hook 'post-command-hook 'org-read-date-display)
17296               (use-local-map old-map)
17297               (when org-read-date-overlay
17298                 (org-delete-overlay org-read-date-overlay)
17299                 (setq org-read-date-overlay nil)))))))
17301      (t ; Naked prompt only
17302       (unwind-protect
17303           (setq ans (read-string prompt default-input nil timestr))
17304         (when org-read-date-overlay
17305           (org-delete-overlay org-read-date-overlay)
17306           (setq org-read-date-overlay nil)))))
17308     (setq final (org-read-date-analyze ans def defdecode))
17310     (if to-time
17311         (apply 'encode-time final)
17312       (if (and (boundp 'org-time-was-given) org-time-was-given)
17313           (format "%04d-%02d-%02d %02d:%02d"
17314                   (nth 5 final) (nth 4 final) (nth 3 final)
17315                   (nth 2 final) (nth 1 final))
17316         (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17317 (defvar def)
17318 (defvar defdecode)
17319 (defvar with-time)
17320 (defun org-read-date-display ()
17321   "Display the currrent date prompt interpretation in the minibuffer."
17322   (when org-read-date-display-live
17323     (when org-read-date-overlay
17324       (org-delete-overlay org-read-date-overlay))
17325     (let ((p (point)))
17326       (end-of-line 1)
17327       (while (not (equal (buffer-substring
17328                           (max (point-min) (- (point) 4)) (point))
17329                          "    "))
17330         (insert " "))
17331       (goto-char p))
17332     (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17333                         " " (or org-ans1 org-ans2)))
17334            (org-end-time-was-given nil)
17335            (f (org-read-date-analyze ans def defdecode))
17336            (fmts (if org-dcst
17337                      org-time-stamp-custom-formats
17338                    org-time-stamp-formats))
17339            (fmt (if (or with-time
17340                         (and (boundp 'org-time-was-given) org-time-was-given))
17341                     (cdr fmts)
17342                   (car fmts)))
17343            (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17344       (when (and org-end-time-was-given
17345                  (string-match org-plain-time-of-day-regexp txt))
17346         (setq txt (concat (substring txt 0 (match-end 0)) "-"
17347                           org-end-time-was-given
17348                           (substring txt (match-end 0)))))
17349       (setq org-read-date-overlay
17350             (make-overlay (1- (point-at-eol)) (point-at-eol)))
17351       (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17353 (defun org-read-date-analyze (ans def defdecode)
17354   "Analyze the combined answer of the date prompt."
17355   ;; FIXME: cleanup and comment
17356   (let (delta deltan deltaw deltadef year month day
17357               hour minute second wday pm h2 m2 tl wday1)
17359     (when (setq delta (org-read-date-get-relative ans (current-time) def))
17360       (setq ans (replace-match "" t t ans)
17361             deltan (car delta)
17362             deltaw (nth 1 delta)
17363             deltadef (nth 2 delta)))
17365     ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17366     (when (string-match
17367            "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17368       (setq year (if (match-end 2)
17369                      (string-to-number (match-string 2 ans))
17370                    (string-to-number (format-time-string "%Y")))
17371             month (string-to-number (match-string 3 ans))
17372             day (string-to-number (match-string 4 ans)))
17373       (if (< year 100) (setq year (+ 2000 year)))
17374       (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17375                                t nil ans)))
17376     ;; Help matching am/pm times, because `parse-time-string' does not do that.
17377     ;; If there is a time with am/pm, and *no* time without it, we convert
17378     ;; so that matching will be successful.
17379     (loop for i from 1 to 2 do ; twice, for end time as well
17380           (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17381                      (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17382             (setq hour (string-to-number (match-string 1 ans))
17383                   minute (if (match-end 3)
17384                              (string-to-number (match-string 3 ans))
17385                            0)
17386                   pm (equal ?p
17387                             (string-to-char (downcase (match-string 4 ans)))))
17388             (if (and (= hour 12) (not pm))
17389                 (setq hour 0)
17390               (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17391             (setq ans (replace-match (format "%02d:%02d" hour minute)
17392                                      t t ans))))
17394     ;; Check if a time range is given as a duration
17395     (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17396       (setq hour (string-to-number (match-string 1 ans))
17397             h2 (+ hour (string-to-number (match-string 3 ans)))
17398             minute (string-to-number (match-string 2 ans))
17399             m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17400       (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17401       (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17403     ;; Check if there is a time range
17404     (when (boundp 'org-end-time-was-given)
17405       (setq org-time-was-given nil)
17406       (when (and (string-match org-plain-time-of-day-regexp ans)
17407                  (match-end 8))
17408         (setq org-end-time-was-given (match-string 8 ans))
17409         (setq ans (concat (substring ans 0 (match-beginning 7))
17410                           (substring ans (match-end 7))))))
17412     (setq tl (parse-time-string ans)
17413           day (or (nth 3 tl) (nth 3 defdecode))
17414           month (or (nth 4 tl)
17415                     (if (and org-read-date-prefer-future
17416                              (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17417                         (1+ (nth 4 defdecode))
17418                       (nth 4 defdecode)))
17419           year (or (nth 5 tl)
17420                    (if (and org-read-date-prefer-future
17421                             (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17422                        (1+ (nth 5 defdecode))
17423                      (nth 5 defdecode)))
17424           hour (or (nth 2 tl) (nth 2 defdecode))
17425           minute (or (nth 1 tl) (nth 1 defdecode))
17426           second (or (nth 0 tl) 0)
17427           wday (nth 6 tl))
17428     (when deltan
17429       (unless deltadef
17430         (let ((now (decode-time (current-time))))
17431           (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17432       (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17433             ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17434             ((equal deltaw "m") (setq month (+ month deltan)))
17435             ((equal deltaw "y") (setq year (+ year deltan)))))
17436     (when (and wday (not (nth 3 tl)))
17437       ;; Weekday was given, but no day, so pick that day in the week
17438       ;; on or after the derived date.
17439       (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17440       (unless (equal wday wday1)
17441         (setq day (+ day (% (- wday wday1 -7) 7)))))
17442     (if (and (boundp 'org-time-was-given)
17443              (nth 2 tl))
17444         (setq org-time-was-given t))
17445     (if (< year 100) (setq year (+ 2000 year)))
17446     (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17447     (list second minute hour day month year)))
17449 (defvar parse-time-weekdays)
17451 (defun org-read-date-get-relative (s today default)
17452   "Check string S for special relative date string.
17453 TODAY and DEFAULT are internal times, for today and for a default.
17454 Return shift list (N what def-flag)
17455 WHAT       is \"d\", \"w\", \"m\", or \"y\" for day. week, month, year.
17456 N          is the number if WHATs to shift
17457 DEF-FLAG   is t when a double ++ or -- indicates shift relative to
17458            the DEFAULT date rather than TODAY."
17459   (when (string-match
17460          (concat
17461           "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17462           "\\([0-9]+\\)?"
17463           "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17464           "\\([ \t]\\|$\\)") s)
17465     (let* ((dir (if (match-end 1)
17466                     (string-to-char (substring (match-string 1 s) -1))
17467                   ?+))
17468            (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17469            (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17470            (what (if (match-end 3) (match-string 3 s) "d"))
17471            (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17472            (date (if rel default today))
17473            (wday (nth 6 (decode-time date)))
17474            delta)
17475       (if wday1
17476           (progn
17477             (setq delta (mod (+ 7 (- wday1 wday)) 7))
17478             (if (= dir ?-) (setq delta (- delta 7)))
17479             (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17480             (list delta "d" rel))
17481         (list (* n (if (= dir ?-) -1 1)) what rel)))))
17483 (defun org-eval-in-calendar (form &optional keepdate)
17484   "Eval FORM in the calendar window and return to current window.
17485 Also, store the cursor date in variable org-ans2."
17486   (let ((sw (selected-window)))
17487     (select-window (get-buffer-window "*Calendar*"))
17488     (eval form)
17489     (when (and (not keepdate) (calendar-cursor-to-date))
17490       (let* ((date (calendar-cursor-to-date))
17491              (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17492         (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17493     (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17494     (select-window sw)))
17496 ;    ;; Update the prompt to show new default date
17497 ;    (save-excursion
17498 ;      (goto-char (point-min))
17499 ;      (when (and org-ans2
17500 ;                (re-search-forward "\\[[-0-9]+\\]" nil t)
17501 ;                (get-text-property (match-end 0) 'field))
17502 ;       (let ((inhibit-read-only t))
17503 ;         (replace-match (concat "[" org-ans2 "]") t t)
17504 ;         (add-text-properties (point-min) (1+ (match-end 0))
17505 ;                              (text-properties-at (1+ (point-min)))))))))
17507 (defun org-calendar-select ()
17508   "Return to `org-read-date' with the date currently selected.
17509 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17510   (interactive)
17511   (when (calendar-cursor-to-date)
17512     (let* ((date (calendar-cursor-to-date))
17513            (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17514       (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17515     (if (active-minibuffer-window) (exit-minibuffer))))
17517 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17518   "Insert a date stamp for the date given by the internal TIME.
17519 WITH-HM means, use the stamp format that includes the time of the day.
17520 INACTIVE means use square brackets instead of angular ones, so that the
17521 stamp will not contribute to the agenda.
17522 PRE and POST are optional strings to be inserted before and after the
17523 stamp.
17524 The command returns the inserted time stamp."
17525   (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17526         stamp)
17527     (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17528     (insert-before-markers (or pre ""))
17529     (insert-before-markers (setq stamp (format-time-string fmt time)))
17530     (when (listp extra)
17531       (setq extra (car extra))
17532       (if (and (stringp extra)
17533                (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17534           (setq extra (format "-%02d:%02d"
17535                               (string-to-number (match-string 1 extra))
17536                               (string-to-number (match-string 2 extra))))
17537         (setq extra nil)))
17538     (when extra
17539       (backward-char 1)
17540       (insert-before-markers extra)
17541       (forward-char 1))
17542     (insert-before-markers (or post ""))
17543     stamp))
17545 (defun org-toggle-time-stamp-overlays ()
17546   "Toggle the use of custom time stamp formats."
17547   (interactive)
17548   (setq org-display-custom-times (not org-display-custom-times))
17549   (unless org-display-custom-times
17550     (let ((p (point-min)) (bmp (buffer-modified-p)))
17551       (while (setq p (next-single-property-change p 'display))
17552         (if (and (get-text-property p 'display)
17553                  (eq (get-text-property p 'face) 'org-date))
17554             (remove-text-properties
17555              p (setq p (next-single-property-change p 'display))
17556              '(display t))))
17557       (set-buffer-modified-p bmp)))
17558   (if (featurep 'xemacs)
17559       (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17560   (org-restart-font-lock)
17561   (setq org-table-may-need-update t)
17562   (if org-display-custom-times
17563       (message "Time stamps are overlayed with custom format")
17564     (message "Time stamp overlays removed")))
17566 (defun org-display-custom-time (beg end)
17567   "Overlay modified time stamp format over timestamp between BED and END."
17568   (let* ((ts (buffer-substring beg end))
17569          t1 w1 with-hm tf time str w2 (off 0))
17570     (save-match-data
17571       (setq t1 (org-parse-time-string ts t))
17572       (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
17573           (setq off (- (match-end 0) (match-beginning 0)))))
17574     (setq end (- end off))
17575     (setq w1 (- end beg)
17576           with-hm (and (nth 1 t1) (nth 2 t1))
17577           tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17578           time (org-fix-decoded-time t1)
17579           str (org-add-props
17580                   (format-time-string
17581                    (substring tf 1 -1) (apply 'encode-time time))
17582                   nil 'mouse-face 'highlight)
17583           w2 (length str))
17584     (if (not (= w2 w1))
17585         (add-text-properties (1+ beg) (+ 2 beg)
17586                              (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17587     (if (featurep 'xemacs)
17588         (progn
17589           (put-text-property beg end 'invisible t)
17590           (put-text-property beg end 'end-glyph (make-glyph str)))
17591       (put-text-property beg end 'display str))))
17593 (defun org-translate-time (string)
17594   "Translate all timestamps in STRING to custom format.
17595 But do this only if the variable `org-display-custom-times' is set."
17596   (when org-display-custom-times
17597     (save-match-data
17598       (let* ((start 0)
17599              (re org-ts-regexp-both)
17600              t1 with-hm inactive tf time str beg end)
17601         (while (setq start (string-match re string start))
17602           (setq beg (match-beginning 0)
17603                 end (match-end 0)
17604                 t1 (save-match-data
17605                      (org-parse-time-string (substring string beg end) t))
17606                 with-hm (and (nth 1 t1) (nth 2 t1))
17607                 inactive (equal (substring string beg (1+ beg)) "[")
17608                 tf (funcall (if with-hm 'cdr 'car)
17609                             org-time-stamp-custom-formats)
17610                 time (org-fix-decoded-time t1)
17611                 str (format-time-string
17612                      (concat
17613                       (if inactive "[" "<") (substring tf 1 -1)
17614                       (if inactive "]" ">"))
17615                      (apply 'encode-time time))
17616                 string (replace-match str t t string)
17617                 start (+ start (length str)))))))
17618   string)
17620 (defun org-fix-decoded-time (time)
17621   "Set 0 instead of nil for the first 6 elements of time.
17622 Don't touch the rest."
17623   (let ((n 0))
17624     (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17626 (defun org-days-to-time (timestamp-string)
17627   "Difference between TIMESTAMP-STRING and now in days."
17628   (- (time-to-days (org-time-string-to-time timestamp-string))
17629      (time-to-days (current-time))))
17631 (defun org-deadline-close (timestamp-string &optional ndays)
17632   "Is the time in TIMESTAMP-STRING close to the current date?"
17633   (setq ndays (or ndays (org-get-wdays timestamp-string)))
17634   (and (< (org-days-to-time timestamp-string) ndays)
17635        (not (org-entry-is-done-p))))
17637 (defun org-get-wdays (ts)
17638   "Get the deadline lead time appropriate for timestring TS."
17639   (cond
17640    ((<= org-deadline-warning-days 0)
17641     ;; 0 or negative, enforce this value no matter what
17642     (- org-deadline-warning-days))
17643    ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
17644     ;; lead time is specified.
17645     (floor (* (string-to-number (match-string 1 ts))
17646               (cdr (assoc (match-string 2 ts)
17647                           '(("d" . 1)    ("w" . 7)
17648                             ("m" . 30.4) ("y" . 365.25)))))))
17649    ;; go for the default.
17650    (t org-deadline-warning-days)))
17652 (defun org-calendar-select-mouse (ev)
17653   "Return to `org-read-date' with the date currently selected.
17654 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17655   (interactive "e")
17656   (mouse-set-point ev)
17657   (when (calendar-cursor-to-date)
17658     (let* ((date (calendar-cursor-to-date))
17659            (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17660       (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17661     (if (active-minibuffer-window) (exit-minibuffer))))
17663 (defun org-check-deadlines (ndays)
17664   "Check if there are any deadlines due or past due.
17665 A deadline is considered due if it happens within `org-deadline-warning-days'
17666 days from today's date.  If the deadline appears in an entry marked DONE,
17667 it is not shown.  The prefix arg NDAYS can be used to test that many
17668 days.  If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17669   (interactive "P")
17670   (let* ((org-warn-days
17671           (cond
17672            ((equal ndays '(4)) 100000)
17673            (ndays (prefix-numeric-value ndays))
17674            (t (abs org-deadline-warning-days))))
17675          (case-fold-search nil)
17676          (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17677          (callback
17678           (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17680     (message "%d deadlines past-due or due within %d days"
17681              (org-occur regexp nil callback)
17682              org-warn-days)))
17684 (defun org-check-before-date (date)
17685   "Check if there are deadlines or scheduled entries before DATE."
17686   (interactive (list (org-read-date)))
17687   (let ((case-fold-search nil)
17688         (regexp (concat "\\<\\(" org-deadline-string
17689                         "\\|" org-scheduled-string
17690                         "\\) *<\\([^>]+\\)>"))
17691         (callback
17692          (lambda () (time-less-p
17693                      (org-time-string-to-time (match-string 2))
17694                      (org-time-string-to-time date)))))
17695     (message "%d entries before %s"
17696              (org-occur regexp nil callback) date)))
17698 (defun org-evaluate-time-range (&optional to-buffer)
17699   "Evaluate a time range by computing the difference between start and end.
17700 Normally the result is just printed in the echo area, but with prefix arg
17701 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17702 If the time range is actually in a table, the result is inserted into the
17703 next column.
17704 For time difference computation, a year is assumed to be exactly 365
17705 days in order to avoid rounding problems."
17706   (interactive "P")
17707   (or
17708    (org-clock-update-time-maybe)
17709    (save-excursion
17710      (unless (org-at-date-range-p t)
17711        (goto-char (point-at-bol))
17712        (re-search-forward org-tr-regexp-both (point-at-eol) t))
17713      (if (not (org-at-date-range-p t))
17714          (error "Not at a time-stamp range, and none found in current line")))
17715    (let* ((ts1 (match-string 1))
17716           (ts2 (match-string 2))
17717           (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17718           (match-end (match-end 0))
17719           (time1 (org-time-string-to-time ts1))
17720           (time2 (org-time-string-to-time ts2))
17721           (t1 (time-to-seconds time1))
17722           (t2 (time-to-seconds time2))
17723           (diff (abs (- t2 t1)))
17724           (negative (< (- t2 t1) 0))
17725           ;; (ys (floor (* 365 24 60 60)))
17726           (ds (* 24 60 60))
17727           (hs (* 60 60))
17728           (fy "%dy %dd %02d:%02d")
17729           (fy1 "%dy %dd")
17730           (fd "%dd %02d:%02d")
17731           (fd1 "%dd")
17732           (fh "%02d:%02d")
17733           y d h m align)
17734      (if havetime
17735          (setq ; y (floor (/ diff ys))  diff (mod diff ys)
17736           y 0
17737           d (floor (/ diff ds))  diff (mod diff ds)
17738           h (floor (/ diff hs))  diff (mod diff hs)
17739           m (floor (/ diff 60)))
17740        (setq ; y (floor (/ diff ys))  diff (mod diff ys)
17741         y 0
17742         d (floor (+ (/ diff ds) 0.5))
17743         h 0 m 0))
17744      (if (not to-buffer)
17745          (message "%s" (org-make-tdiff-string y d h m))
17746        (if (org-at-table-p)
17747            (progn
17748              (goto-char match-end)
17749              (setq align t)
17750              (and (looking-at " *|") (goto-char (match-end 0))))
17751          (goto-char match-end))
17752        (if (looking-at
17753             "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17754            (replace-match ""))
17755        (if negative (insert " -"))
17756        (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17757          (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17758            (insert " " (format fh h m))))
17759        (if align (org-table-align))
17760        (message "Time difference inserted")))))
17762 (defun org-make-tdiff-string (y d h m)
17763   (let ((fmt "")
17764         (l nil))
17765     (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17766                       l (push y l)))
17767     (if (> d 0) (setq fmt (concat fmt "%d day"  (if (> d 1) "s" "") " ")
17768                       l (push d l)))
17769     (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17770                       l (push h l)))
17771     (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17772                       l (push m l)))
17773     (apply 'format fmt (nreverse l))))
17775 (defun org-time-string-to-time (s)
17776   (apply 'encode-time (org-parse-time-string s)))
17778 (defun org-time-string-to-absolute (s &optional daynr)
17779   "Convert a time stamp to an absolute day number.
17780 If there is a specifyer for a cyclic time stamp, get the closest date to
17781 DAYNR."
17782   (cond
17783    ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17784     (if (org-diary-sexp-entry (match-string 1 s) "" date)
17785         daynr
17786       (+ daynr 1000)))
17787    ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
17788     (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17789                           (time-to-days (current-time))) (match-string 0 s)))
17790    (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
17792 (defun org-time-from-absolute (d)
17793   "Return the time corresponding to date D.
17794 D may be an absolute day number, or a calendar-type list (month day year)."
17795   (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17796   (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17798 (defun org-calendar-holiday ()
17799   "List of holidays, for Diary display in Org-mode."
17800   (require 'holidays)
17801   (let ((hl (funcall
17802              (if (fboundp 'calendar-check-holidays)
17803                  'calendar-check-holidays 'check-calendar-holidays) date)))
17804     (if hl (mapconcat 'identity hl "; "))))
17806 (defun org-diary-sexp-entry (sexp entry date)
17807   "Process a SEXP diary ENTRY for DATE."
17808   (require 'diary-lib)
17809   (let ((result (if calendar-debug-sexp
17810                     (let ((stack-trace-on-error t))
17811                       (eval (car (read-from-string sexp))))
17812                   (condition-case nil
17813                       (eval (car (read-from-string sexp)))
17814                     (error
17815                      (beep)
17816                      (message "Bad sexp at line %d in %s: %s"
17817                               (org-current-line)
17818                               (buffer-file-name) sexp)
17819                      (sleep-for 2))))))
17820     (cond ((stringp result) result)
17821           ((and (consp result)
17822                 (stringp (cdr result))) (cdr result))
17823           (result entry)
17824           (t nil))))
17826 (defun org-diary-to-ical-string (frombuf)
17827   "Get iCalendar entries from diary entries in buffer FROMBUF.
17828 This uses the icalendar.el library."
17829   (let* ((tmpdir (if (featurep 'xemacs)
17830                      (temp-directory)
17831                    temporary-file-directory))
17832          (tmpfile (make-temp-name
17833                    (expand-file-name "orgics" tmpdir)))
17834          buf rtn b e)
17835     (save-excursion
17836       (set-buffer frombuf)
17837       (icalendar-export-region (point-min) (point-max) tmpfile)
17838       (setq buf (find-buffer-visiting tmpfile))
17839       (set-buffer buf)
17840       (goto-char (point-min))
17841       (if (re-search-forward "^BEGIN:VEVENT" nil t)
17842           (setq b (match-beginning 0)))
17843       (goto-char (point-max))
17844       (if (re-search-backward "^END:VEVENT" nil t)
17845           (setq e (match-end 0)))
17846       (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17847     (kill-buffer buf)
17848     (kill-buffer frombuf)
17849     (delete-file tmpfile)
17850     rtn))
17852 (defun org-closest-date (start current change)
17853   "Find the date closest to CURRENT that is consistent with START and CHANGE."
17854   ;; Make the proper lists from the dates
17855   (catch 'exit
17856     (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
17857           dn dw sday cday n1 n2
17858           d m y y1 y2 date1 date2 nmonths nm ny m2)
17860       (setq start (org-date-to-gregorian start)
17861             current (org-date-to-gregorian
17862                      (if org-agenda-repeating-timestamp-show-all
17863                          current
17864                        (time-to-days (current-time))))
17865             sday (calendar-absolute-from-gregorian start)
17866             cday  (calendar-absolute-from-gregorian current))
17868       (if (<= cday sday) (throw 'exit sday))
17870       (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
17871           (setq dn (string-to-number (match-string 1 change))
17872                 dw (cdr (assoc (match-string 2 change) a1)))
17873         (error "Invalid change specifyer: %s" change))
17874       (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17875       (cond
17876        ((eq dw 'day)
17877         (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17878               n2 (+ n1 dn)))
17879        ((eq dw 'year)
17880         (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17881         (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17882         (setq date1 (list m d y1)
17883               n1 (calendar-absolute-from-gregorian date1)
17884               date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17885               n2 (calendar-absolute-from-gregorian date2)))
17886        ((eq dw 'month)
17887         ;; approx number of month between the tow dates
17888         (setq nmonths (floor (/ (- cday sday) 30.436875)))
17889         ;; How often does dn fit in there?
17890         (setq d (nth 1 start) m (car start) y (nth 2 start)
17891               nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17892               m (+ m nm)
17893               ny (floor (/ m 12))
17894               y (+ y ny)
17895               m (- m (* ny 12)))
17896         (while (> m 12) (setq m (- m 12) y (1+ y)))
17897         (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17898         (setq m2 (+ m dn) y2 y)
17899         (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17900         (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17901         (while (< n2 cday)
17902           (setq n1 n2 m m2 y y2)
17903           (setq m2 (+ m dn) y2 y)
17904           (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17905           (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17907       (if org-agenda-repeating-timestamp-show-all
17908           (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)
17909         (if (= cday n1) n1 n2)))))
17911 (defun org-date-to-gregorian (date)
17912   "Turn any specification of DATE into a gregorian date for the calendar."
17913   (cond ((integerp date) (calendar-gregorian-from-absolute date))
17914         ((and (listp date) (= (length date) 3)) date)
17915         ((stringp date)
17916          (setq date (org-parse-time-string date))
17917          (list (nth 4 date) (nth 3 date) (nth 5 date)))
17918         ((listp date)
17919          (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17921 (defun org-parse-time-string (s &optional nodefault)
17922   "Parse the standard Org-mode time string.
17923 This should be a lot faster than the normal `parse-time-string'.
17924 If time is not given, defaults to 0:00.  However, with optional NODEFAULT,
17925 hour and minute fields will be nil if not given."
17926   (if (string-match org-ts-regexp0 s)
17927       (list 0
17928             (if (or (match-beginning 8) (not nodefault))
17929                 (string-to-number (or (match-string 8 s) "0")))
17930             (if (or (match-beginning 7) (not nodefault))
17931                 (string-to-number (or (match-string 7 s) "0")))
17932             (string-to-number (match-string 4 s))
17933             (string-to-number (match-string 3 s))
17934             (string-to-number (match-string 2 s))
17935             nil nil nil)
17936     (make-list 9 0)))
17938 (defun org-timestamp-up (&optional arg)
17939   "Increase the date item at the cursor by one.
17940 If the cursor is on the year, change the year.  If it is on the month or
17941 the day, change that.
17942 With prefix ARG, change by that many units."
17943   (interactive "p")
17944   (org-timestamp-change (prefix-numeric-value arg)))
17946 (defun org-timestamp-down (&optional arg)
17947   "Decrease the date item at the cursor by one.
17948 If the cursor is on the year, change the year.  If it is on the month or
17949 the day, change that.
17950 With prefix ARG, change by that many units."
17951   (interactive "p")
17952   (org-timestamp-change (- (prefix-numeric-value arg))))
17954 (defun org-timestamp-up-day (&optional arg)
17955   "Increase the date in the time stamp by one day.
17956 With prefix ARG, change that many days."
17957   (interactive "p")
17958   (if (and (not (org-at-timestamp-p t))
17959            (org-on-heading-p))
17960       (org-todo 'up)
17961     (org-timestamp-change (prefix-numeric-value arg) 'day)))
17963 (defun org-timestamp-down-day (&optional arg)
17964   "Decrease the date in the time stamp by one day.
17965 With prefix ARG, change that many days."
17966   (interactive "p")
17967   (if (and (not (org-at-timestamp-p t))
17968            (org-on-heading-p))
17969       (org-todo 'down)
17970     (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
17972 (defsubst org-pos-in-match-range (pos n)
17973   (and (match-beginning n)
17974        (<= (match-beginning n) pos)
17975        (>= (match-end n) pos)))
17977 (defun org-at-timestamp-p (&optional inactive-ok)
17978   "Determine if the cursor is in or at a timestamp."
17979   (interactive)
17980   (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17981          (pos (point))
17982          (ans (or (looking-at tsr)
17983                   (save-excursion
17984                     (skip-chars-backward "^[<\n\r\t")
17985                     (if (> (point) (point-min)) (backward-char 1))
17986                     (and (looking-at tsr)
17987                          (> (- (match-end 0) pos) -1))))))
17988     (and ans
17989          (boundp 'org-ts-what)
17990          (setq org-ts-what
17991               (cond
17992                ((= pos (match-beginning 0))         'bracket)
17993                ((= pos (1- (match-end 0)))          'bracket)
17994                ((org-pos-in-match-range pos 2)      'year)
17995                ((org-pos-in-match-range pos 3)      'month)
17996                ((org-pos-in-match-range pos 7)      'hour)
17997                ((org-pos-in-match-range pos 8)      'minute)
17998                ((or (org-pos-in-match-range pos 4)
17999                     (org-pos-in-match-range pos 5)) 'day)
18000                ((and (> pos (or (match-end 8) (match-end 5)))
18001                      (< pos (match-end 0)))
18002                 (- pos (or (match-end 8) (match-end 5))))
18003                (t 'day))))
18004     ans))
18006 (defun org-toggle-timestamp-type ()
18007   ""
18008   (interactive)
18009   (when (org-at-timestamp-p t)
18010     (save-excursion
18011       (goto-char (match-beginning 0))
18012       (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18013       (goto-char (1- (match-end 0)))
18014       (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18015     (message "Timestamp is now %sactive"
18016              (if (equal (char-before) ?>) "in" ""))))
18018 (defun org-timestamp-change (n &optional what)
18019   "Change the date in the time stamp at point.
18020 The date will be changed by N times WHAT.  WHAT can be `day', `month',
18021 `year', `minute', `second'.  If WHAT is not given, the cursor position
18022 in the timestamp determines what will be changed."
18023   (let ((pos (point))
18024         with-hm inactive
18025         org-ts-what
18026         extra
18027         ts time time0)
18028     (if (not (org-at-timestamp-p t))
18029         (error "Not at a timestamp"))
18030     (if (and (not what) (eq org-ts-what 'bracket))
18031         (org-toggle-timestamp-type)
18032       (if (and (not what) (not (eq org-ts-what 'day))
18033                org-display-custom-times
18034                (get-text-property (point) 'display)
18035                (not (get-text-property (1- (point)) 'display)))
18036           (setq org-ts-what 'day))
18037       (setq org-ts-what (or what org-ts-what)
18038             inactive (= (char-after (match-beginning 0)) ?\[)
18039             ts (match-string 0))
18040       (replace-match "")
18041       (if (string-match
18042            "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18043            ts)
18044           (setq extra (match-string 1 ts)))
18045       (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18046           (setq with-hm t))
18047       (setq time0 (org-parse-time-string ts))
18048       (setq time
18049             (encode-time (or (car time0) 0)
18050                          (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18051                          (+ (if (eq org-ts-what 'hour) n 0)   (nth 2 time0))
18052                          (+ (if (eq org-ts-what 'day) n 0)    (nth 3 time0))
18053                          (+ (if (eq org-ts-what 'month) n 0)  (nth 4 time0))
18054                          (+ (if (eq org-ts-what 'year) n 0)   (nth 5 time0))
18055                          (nthcdr 6 time0)))
18056       (when (integerp org-ts-what)
18057         (setq extra (org-modify-ts-extra extra org-ts-what n)))
18058       (if (eq what 'calendar)
18059           (let ((cal-date (org-get-date-from-calendar)))
18060             (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18061             (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18062             (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18063             (setcar time0 (or (car time0) 0))
18064             (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18065             (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18066             (setq time (apply 'encode-time time0))))
18067       (setq org-last-changed-timestamp
18068             (org-insert-time-stamp time with-hm inactive nil nil extra))
18069       (org-clock-update-time-maybe)
18070       (goto-char pos)
18071       ;; Try to recenter the calendar window, if any
18072       (if (and org-calendar-follow-timestamp-change
18073                (get-buffer-window "*Calendar*" t)
18074                (memq org-ts-what '(day month year)))
18075           (org-recenter-calendar (time-to-days time))))))
18077 ;; FIXME: does not yet work for lead times
18078 (defun org-modify-ts-extra (s pos n)
18079   "Change the different parts of the lead-time and repeat fields in timestamp."
18080   (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18081         ng h m new)
18082     (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18083       (cond
18084        ((or (org-pos-in-match-range pos 2)
18085             (org-pos-in-match-range pos 3))
18086         (setq m (string-to-number (match-string 3 s))
18087               h (string-to-number (match-string 2 s)))
18088         (if (org-pos-in-match-range pos 2)
18089             (setq h (+ h n))
18090           (setq m (+ m n)))
18091         (if (< m 0) (setq m (+ m 60) h (1- h)))
18092         (if (> m 59) (setq m (- m 60) h (1+ h)))
18093         (setq h (min 24 (max 0 h)))
18094         (setq ng 1 new (format "-%02d:%02d" h m)))
18095        ((org-pos-in-match-range pos 6)
18096         (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18097        ((org-pos-in-match-range pos 5)
18098         (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18100       (when ng
18101         (setq s (concat
18102                  (substring s 0 (match-beginning ng))
18103                  new
18104                  (substring s (match-end ng))))))
18105     s))
18107 (defun org-recenter-calendar (date)
18108   "If the calendar is visible, recenter it to DATE."
18109   (let* ((win (selected-window))
18110          (cwin (get-buffer-window "*Calendar*" t))
18111          (calendar-move-hook nil))
18112     (when cwin
18113       (select-window cwin)
18114       (calendar-goto-date (if (listp date) date
18115                             (calendar-gregorian-from-absolute date)))
18116       (select-window win))))
18118 (defun org-goto-calendar (&optional arg)
18119   "Go to the Emacs calendar at the current date.
18120 If there is a time stamp in the current line, go to that date.
18121 A prefix ARG can be used to force the current date."
18122   (interactive "P")
18123   (let ((tsr org-ts-regexp) diff
18124         (calendar-move-hook nil)
18125         (view-calendar-holidays-initially nil)
18126         (view-diary-entries-initially nil))
18127     (if (or (org-at-timestamp-p)
18128             (save-excursion
18129               (beginning-of-line 1)
18130               (looking-at (concat ".*" tsr))))
18131         (let ((d1 (time-to-days (current-time)))
18132               (d2 (time-to-days
18133                    (org-time-string-to-time (match-string 1)))))
18134           (setq diff (- d2 d1))))
18135     (calendar)
18136     (calendar-goto-today)
18137     (if (and diff (not arg)) (calendar-forward-day diff))))
18139 (defun org-get-date-from-calendar ()
18140   "Return a list (month day year) of date at point in calendar."
18141   (with-current-buffer "*Calendar*"
18142     (save-match-data
18143       (calendar-cursor-to-date))))
18145 (defun org-date-from-calendar ()
18146   "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18147 If there is already a time stamp at the cursor position, update it."
18148   (interactive)
18149   (if (org-at-timestamp-p t)
18150       (org-timestamp-change 0 'calendar)
18151     (let ((cal-date (org-get-date-from-calendar)))
18152       (org-insert-time-stamp
18153        (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18155 ;; Make appt aware of appointments from the agenda
18156 ;;;###autoload
18157 (defun org-agenda-to-appt (&optional filter)
18158   "Activate appointments found in `org-agenda-files'.
18159 When prefixed, prompt for a regular expression and use it as a
18160 filter: only add entries if they match this regular expression.
18162 FILTER can be a string. In this case, use this string as a
18163 regular expression to filter results.
18165 FILTER can also be an alist, with the car of each cell being
18166 either 'headline or 'category.  For example:
18168   '((headline \"IMPORTANT\")
18169     (category \"Work\"))
18171 will only add headlines containing IMPORTANT or headlines
18172 belonging to the category \"Work\"."
18173   (interactive "P")
18174   (require 'calendar)
18175   (if (equal filter '(4))
18176       (setq filter (read-from-minibuffer "Regexp filter: ")))
18177   (let* ((cnt 0) ; count added events
18178          (org-agenda-new-buffers nil)
18179          (today (org-date-to-gregorian
18180                  (time-to-days (current-time))))
18181          (files (org-agenda-files)) entries file)
18182     ;; Get all entries which may contain an appt
18183     (while (setq file (pop files))
18184       (setq entries
18185             (append entries
18186                     (org-agenda-get-day-entries
18187                      file today
18188                      :timestamp :scheduled :deadline))))
18189     (setq entries (delq nil entries))
18190     ;; Map thru entries and find if they pass thru the filter
18191     (mapc
18192      (lambda(x)
18193        (let* ((evt (org-trim (get-text-property 1 'txt x)))
18194               (cat (get-text-property 1 'org-category x))
18195               (tod (get-text-property 1 'time-of-day x))
18196               (ok (or (null filter)
18197                       (and (stringp filter) (string-match filter evt))
18198                       (and (listp filter)
18199                            (or (string-match
18200                                 (cadr (assoc 'category filter)) cat)
18201                                (string-match
18202                                 (cadr (assoc 'headline filter)) evt))))))
18203          ;; FIXME: Shall we remove text-properties for the appt text?
18204          ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18205          (when (and ok tod)
18206            (setq tod (number-to-string tod)
18207                  tod (when (string-match
18208                             "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18209                        (concat (match-string 1 tod) ":"
18210                                (match-string 2 tod))))
18211            (appt-add tod evt)
18212            (setq cnt (1+ cnt))))) entries)
18213     (org-release-buffers org-agenda-new-buffers)
18214     (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
18216 ;;; The clock for measuring work time.
18218 (defvar org-mode-line-string "")
18219 (put 'org-mode-line-string 'risky-local-variable t)
18221 (defvar org-mode-line-timer nil)
18222 (defvar org-clock-heading "")
18223 (defvar org-clock-start-time "")
18225 (defun org-update-mode-line ()
18226   (let* ((delta (- (time-to-seconds (current-time))
18227                    (time-to-seconds org-clock-start-time)))
18228          (h (floor delta 3600))
18229          (m (floor (- delta (* 3600 h)) 60)))
18230     (setq org-mode-line-string
18231           (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18232                       'help-echo "Org-mode clock is running"))
18233     (force-mode-line-update)))
18235 (defvar org-clock-marker (make-marker)
18236   "Marker recording the last clock-in.")
18237 (defvar org-clock-mode-line-entry nil
18238   "Information for the modeline about the running clock.")
18240 (defun org-clock-in ()
18241   "Start the clock on the current item.
18242 If necessary, clock-out of the currently active clock."
18243   (interactive)
18244   (org-clock-out t)
18245   (let (ts)
18246     (save-excursion
18247       (org-back-to-heading t)
18248       (when (and org-clock-in-switch-to-state
18249                  (not (looking-at (concat outline-regexp "[ \t]*"
18250                                           org-clock-in-switch-to-state
18251                                           "\\>"))))
18252         (org-todo org-clock-in-switch-to-state))
18253       (if (and org-clock-heading-function
18254                (functionp org-clock-heading-function))
18255           (setq org-clock-heading (funcall org-clock-heading-function))
18256         (if (looking-at org-complex-heading-regexp)
18257             (setq org-clock-heading (match-string 4))
18258           (setq org-clock-heading "???")))
18259       (setq org-clock-heading (propertize org-clock-heading 'face nil))
18260       (org-clock-find-position)
18262       (insert "\n") (backward-char 1)
18263       (indent-relative)
18264       (insert org-clock-string " ")
18265       (setq org-clock-start-time (current-time))
18266       (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18267       (move-marker org-clock-marker (point) (buffer-base-buffer))
18268       (or global-mode-string (setq global-mode-string '("")))
18269       (or (memq 'org-mode-line-string global-mode-string)
18270           (setq global-mode-string
18271                 (append global-mode-string '(org-mode-line-string))))
18272       (org-update-mode-line)
18273       (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18274       (message "Clock started at %s" ts))))
18276 (defun org-clock-find-position ()
18277   "Find the location where the next clock line should be inserted."
18278   (org-back-to-heading t)
18279   (catch 'exit
18280     (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18281           (re (concat "^[ \t]*" org-clock-string))
18282           (cnt 0)
18283           first last)
18284       (goto-char beg)
18285       (when (eobp) (newline) (setq end (max (point) end)))
18286       (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18287         ;; we seem to have a CLOCK drawer, so go there.
18288         (beginning-of-line 2)
18289         (throw 'exit t))
18290       ;; Lets count the CLOCK lines
18291       (goto-char beg)
18292       (while (re-search-forward re end t)
18293         (setq first (or first (match-beginning 0))
18294               last (match-beginning 0)
18295               cnt (1+ cnt)))
18296       (when (and (integerp org-clock-into-drawer)
18297                  (>= (1+ cnt) org-clock-into-drawer))
18298         ;; Wrap current entries into a new drawer
18299         (goto-char last)
18300         (beginning-of-line 2)
18301         (if (org-at-item-p) (org-end-of-item))
18302         (insert ":END:\n")
18303         (beginning-of-line 0)
18304         (org-indent-line-function)
18305         (goto-char first)
18306         (insert ":CLOCK:\n")
18307         (beginning-of-line 0)
18308         (org-indent-line-function)
18309         (org-flag-drawer t)
18310         (beginning-of-line 2)
18311         (throw 'exit nil))
18313       (goto-char beg)
18314       (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18315                   (not (equal (match-string 1) org-clock-string)))
18316         ;; Planning info, skip to after it
18317         (beginning-of-line 2)
18318         (or (bolp) (newline)))
18319       (when (eq t org-clock-into-drawer)
18320         (insert ":CLOCK:\n:END:\n")
18321         (beginning-of-line -1)
18322         (org-indent-line-function)
18323         (org-flag-drawer t)
18324         (beginning-of-line 2)
18325         (org-indent-line-function)))))
18327 (defun org-clock-out (&optional fail-quietly)
18328   "Stop the currently running clock.
18329 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18330   (interactive)
18331   (catch 'exit
18332   (if (not (marker-buffer org-clock-marker))
18333       (if fail-quietly (throw 'exit t) (error "No active clock")))
18334   (let (ts te s h m)
18335     (save-excursion
18336       (set-buffer (marker-buffer org-clock-marker))
18337       (goto-char org-clock-marker)
18338       (beginning-of-line 1)
18339       (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18340                (equal (match-string 1) org-clock-string))
18341           (setq ts (match-string 2))
18342         (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18343       (goto-char (match-end 0))
18344       (delete-region (point) (point-at-eol))
18345       (insert "--")
18346       (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18347       (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18348                  (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18349             h (floor (/ s 3600))
18350             s (- s (* 3600 h))
18351             m (floor (/ s 60))
18352             s (- s (* 60 s)))
18353       (insert " => " (format "%2d:%02d" h m))
18354       (move-marker org-clock-marker nil)
18355       (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
18356              (org-log-done (org-parse-local-options logging 'org-log-done))
18357              (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
18358         (org-add-log-maybe 'clock-out))
18359       (when org-mode-line-timer
18360         (cancel-timer org-mode-line-timer)
18361         (setq org-mode-line-timer nil))
18362       (setq global-mode-string
18363             (delq 'org-mode-line-string global-mode-string))
18364       (force-mode-line-update)
18365       (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18367 (defun org-clock-cancel ()
18368   "Cancel the running clock be removing the start timestamp."
18369   (interactive)
18370   (if (not (marker-buffer org-clock-marker))
18371       (error "No active clock"))
18372   (save-excursion
18373     (set-buffer (marker-buffer org-clock-marker))
18374     (goto-char org-clock-marker)
18375     (delete-region (1- (point-at-bol)) (point-at-eol)))
18376   (setq global-mode-string
18377         (delq 'org-mode-line-string global-mode-string))
18378   (force-mode-line-update)
18379   (message "Clock canceled"))
18381 (defun org-clock-goto (&optional delete-windows)
18382   "Go to the currently clocked-in entry."
18383   (interactive "P")
18384   (if (not (marker-buffer org-clock-marker))
18385       (error "No active clock"))
18386   (switch-to-buffer-other-window
18387    (marker-buffer org-clock-marker))
18388   (if delete-windows (delete-other-windows))
18389   (goto-char org-clock-marker)
18390   (org-show-entry)
18391   (org-back-to-heading)
18392   (recenter))
18394 (defvar org-clock-file-total-minutes nil
18395   "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18396   (make-variable-buffer-local 'org-clock-file-total-minutes)
18398 (defun org-clock-sum (&optional tstart tend)
18399   "Sum the times for each subtree.
18400 Puts the resulting times in minutes as a text property on each headline."
18401   (interactive)
18402   (let* ((bmp (buffer-modified-p))
18403          (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18404                      org-clock-string
18405                      "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18406          (lmax 30)
18407          (ltimes (make-vector lmax 0))
18408          (t1 0)
18409          (level 0)
18410          ts te dt
18411          time)
18412     (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18413     (save-excursion
18414       (goto-char (point-max))
18415       (while (re-search-backward re nil t)
18416         (cond
18417          ((match-end 2)
18418           ;; Two time stamps
18419           (setq ts (match-string 2)
18420                 te (match-string 3)
18421                 ts (time-to-seconds
18422                     (apply 'encode-time (org-parse-time-string ts)))
18423                 te (time-to-seconds
18424                     (apply 'encode-time (org-parse-time-string te)))
18425                 ts (if tstart (max ts tstart) ts)
18426                 te (if tend (min te tend) te)
18427                 dt (- te ts)
18428                 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18429          ((match-end 4)
18430           ;; A naket time
18431           (setq t1 (+ t1 (string-to-number (match-string 5))
18432                       (* 60 (string-to-number (match-string 4))))))
18433          (t ;; A headline
18434           (setq level (- (match-end 1) (match-beginning 1)))
18435           (when (or (> t1 0) (> (aref ltimes level) 0))
18436             (loop for l from 0 to level do
18437                   (aset ltimes l (+ (aref ltimes l) t1)))
18438             (setq t1 0 time (aref ltimes level))
18439             (loop for l from level to (1- lmax) do
18440                   (aset ltimes l 0))
18441             (goto-char (match-beginning 0))
18442             (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18443       (setq org-clock-file-total-minutes (aref ltimes 0)))
18444     (set-buffer-modified-p bmp)))
18446 (defun org-clock-display (&optional total-only)
18447   "Show subtree times in the entire buffer.
18448 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18449 in the echo area."
18450   (interactive)
18451   (org-remove-clock-overlays)
18452   (let (time h m p)
18453     (org-clock-sum)
18454     (unless total-only
18455       (save-excursion
18456         (goto-char (point-min))
18457         (while (or (and (equal (setq p (point)) (point-min))
18458                         (get-text-property p :org-clock-minutes))
18459                    (setq p (next-single-property-change
18460                             (point) :org-clock-minutes)))
18461           (goto-char p)
18462           (when (setq time (get-text-property p :org-clock-minutes))
18463             (org-put-clock-overlay time (funcall outline-level))))
18464         (setq h (/ org-clock-file-total-minutes 60)
18465               m (- org-clock-file-total-minutes (* 60 h)))
18466         ;; Arrange to remove the overlays upon next change.
18467         (when org-remove-highlights-with-change
18468           (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18469                         nil 'local))))
18470     (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18472 (defvar org-clock-overlays nil)
18473 (make-variable-buffer-local 'org-clock-overlays)
18475 (defun org-put-clock-overlay (time &optional level)
18476   "Put an overlays on the current line, displaying TIME.
18477 If LEVEL is given, prefix time with a corresponding number of stars.
18478 This creates a new overlay and stores it in `org-clock-overlays', so that it
18479 will be easy to remove."
18480   (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18481          (l (if level (org-get-legal-level level 0) 0))
18482          (off 0)
18483          ov tx)
18484     (move-to-column c)
18485     (unless (eolp) (skip-chars-backward "^ \t"))
18486     (skip-chars-backward " \t")
18487     (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18488           tx (concat (buffer-substring (1- (point)) (point))
18489                      (make-string (+ off (max 0 (- c (current-column)))) ?.)
18490                      (org-add-props (format "%s %2d:%02d%s"
18491                                             (make-string l ?*) h m
18492                                             (make-string (- 10 l) ?\ ))
18493                          '(face secondary-selection))
18494                      ""))
18495     (if (not (featurep 'xemacs))
18496         (org-overlay-put ov 'display tx)
18497       (org-overlay-put ov 'invisible t)
18498       (org-overlay-put ov 'end-glyph (make-glyph tx)))
18499     (push ov org-clock-overlays)))
18501 (defun org-remove-clock-overlays (&optional beg end noremove)
18502   "Remove the occur highlights from the buffer.
18503 BEG and END are ignored.  If NOREMOVE is nil, remove this function
18504 from the `before-change-functions' in the current buffer."
18505   (interactive)
18506   (unless org-inhibit-highlight-removal
18507     (mapc 'org-delete-overlay org-clock-overlays)
18508     (setq org-clock-overlays nil)
18509     (unless noremove
18510       (remove-hook 'before-change-functions
18511                    'org-remove-clock-overlays 'local))))
18513 (defun org-clock-out-if-current ()
18514   "Clock out if the current entry contains the running clock.
18515 This is used to stop the clock after a TODO entry is marked DONE,
18516 and is only done if the variable `org-clock-out-when-done' is not nil."
18517   (when (and org-clock-out-when-done
18518              (member state org-done-keywords)
18519              (equal (marker-buffer org-clock-marker) (current-buffer))
18520              (< (point) org-clock-marker)
18521              (> (save-excursion (outline-next-heading) (point))
18522                 org-clock-marker))
18523     ;; Clock out, but don't accept a logging message for this.
18524     (let ((org-log-done (if (and (listp org-log-done)
18525                                  (member 'clock-out org-log-done))
18526                             '(done)
18527                           org-log-done)))
18528       (org-clock-out))))
18530 (add-hook 'org-after-todo-state-change-hook
18531           'org-clock-out-if-current)
18533 (defun org-check-running-clock ()
18534   "Check if the current buffer contains the running clock.
18535 If yes, offer to stop it and to save the buffer with the changes."
18536   (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18537              (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18538                                (buffer-name))))
18539     (org-clock-out)
18540     (when (y-or-n-p "Save changed buffer?")
18541       (save-buffer))))
18543 (defun org-clock-report (&optional arg)
18544   "Create a table containing a report about clocked time.
18545 If the cursor is inside an existing clocktable block, then the table
18546 will be updated.  If not, a new clocktable will be inserted.
18547 When called with a prefix argument, move to the first clock table in the
18548 buffer and update it."
18549   (interactive "P")
18550   (org-remove-clock-overlays)
18551   (when arg (org-find-dblock "clocktable"))
18552   (if (org-in-clocktable-p)
18553       (goto-char (org-in-clocktable-p))
18554     (org-create-dblock (list :name "clocktable"
18555                              :maxlevel 2 :scope 'file)))
18556   (org-update-dblock))
18558 (defun org-in-clocktable-p ()
18559   "Check if the cursor is in a clocktable."
18560   (let ((pos (point)) start)
18561     (save-excursion
18562       (end-of-line 1)
18563       (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
18564            (setq start (match-beginning 0))
18565            (re-search-forward "^#\\+END:.*" nil t)
18566            (>= (match-end 0) pos)
18567            start))))
18569 (defun org-clock-update-time-maybe ()
18570   "If this is a CLOCK line, update it and return t.
18571 Otherwise, return nil."
18572   (interactive)
18573   (save-excursion
18574     (beginning-of-line 1)
18575     (skip-chars-forward " \t")
18576     (when (looking-at org-clock-string)
18577       (let ((re (concat "[ \t]*" org-clock-string
18578                         " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
18579                         "\\([ \t]*=>.*\\)?"))
18580             ts te h m s)
18581         (if (not (looking-at re))
18582             nil
18583           (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18584           (end-of-line 1)
18585           (setq ts (match-string 1)
18586                 te (match-string 2))
18587           (setq s (- (time-to-seconds
18588                       (apply 'encode-time (org-parse-time-string te)))
18589                      (time-to-seconds
18590                       (apply 'encode-time (org-parse-time-string ts))))
18591                 h (floor (/ s 3600))
18592                 s (- s (* 3600 h))
18593                 m (floor (/ s 60))
18594                 s (- s (* 60 s)))
18595           (insert " => " (format "%2d:%02d" h m))
18596           t)))))
18598 (defun org-clock-special-range (key &optional time as-strings)
18599   "Return two times bordering a special time range.
18600 Key is a symbol specifying the range and can be one of `today', `yesterday',
18601 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18602 A week starts Monday 0:00 and ends Sunday 24:00.
18603 The range is determined relative to TIME.  TIME defaults to the current time.
18604 The return value is a cons cell with two internal times like the ones
18605 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18606 the returned times will be formatted strings."
18607   (let* ((tm (decode-time (or time (current-time))))
18608          (s 0) (m (nth 1 tm)) (h (nth 2 tm))
18609          (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
18610          (dow (nth 6 tm))
18611          s1 m1 h1 d1 month1 y1 diff ts te fm)
18612     (cond
18613      ((eq key 'today)
18614       (setq h 0 m 0 h1 24 m1 0))
18615      ((eq key 'yesterday)
18616       (setq d (1- d) h 0 m 0 h1 24 m1 0))
18617      ((eq key 'thisweek)
18618       (setq diff (if (= dow 0) 6 (1- dow))
18619             m 0 h 0 d (- d diff) d1 (+ 7 d)))
18620      ((eq key 'lastweek)
18621       (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
18622             m 0 h 0 d (- d diff) d1 (+ 7 d)))
18623      ((eq key 'thismonth)
18624       (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
18625      ((eq key 'lastmonth)
18626       (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
18627      ((eq key 'thisyear)
18628       (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
18629      ((eq key 'lastyear)
18630       (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
18631      (t (error "No such time block %s" key)))
18632     (setq ts (encode-time s m h d month y)
18633           te (encode-time (or s1 s) (or m1 m) (or h1 h)
18634                           (or d1 d) (or month1 month) (or y1 y)))
18635     (setq fm (cdr org-time-stamp-formats))
18636     (if as-strings
18637         (cons (format-time-string fm ts) (format-time-string fm te))
18638       (cons ts te))))
18640 (defun org-dblock-write:clocktable (params)
18641   "Write the standard clocktable."
18642   (let ((hlchars '((1 . "*") (2 . "/")))
18643         (emph nil)
18644         (ins (make-marker))
18645         (total-time nil)
18646         ipos time h m p level hlc hdl maxlevel
18647         ts te cc block beg end pos scope tbl tostring multifile)
18648     (setq scope (plist-get params :scope)
18649           tostring (plist-get  params :tostring)
18650           multifile (plist-get  params :multifile)
18651           maxlevel (or (plist-get params :maxlevel) 3)
18652           emph (plist-get params :emphasize)
18653           ts (plist-get params :tstart)
18654           te (plist-get params :tend)
18655           block (plist-get params :block))
18656     (when block
18657       (setq cc (org-clock-special-range block nil t)
18658             ts (car cc) te (cdr cc)))
18659     (if ts (setq ts (time-to-seconds
18660                      (apply 'encode-time (org-parse-time-string ts)))))
18661     (if te (setq te (time-to-seconds
18662                      (apply 'encode-time (org-parse-time-string te)))))
18663     (move-marker ins (point))
18664     (setq ipos (point))
18666     ;; Get the right scope
18667     (setq pos (point))
18668     (save-restriction
18669       (cond
18670        ((not scope))
18671        ((eq scope 'file) (widen))
18672        ((eq scope 'subtree) (org-narrow-to-subtree))
18673        ((eq scope 'tree)
18674         (while (org-up-heading-safe))
18675         (org-narrow-to-subtree))
18676        ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
18677                                            (symbol-name scope)))
18678         (setq level (string-to-number (match-string 1 (symbol-name scope))))
18679         (catch 'exit
18680           (while (org-up-heading-safe)
18681             (looking-at outline-regexp)
18682             (if (<= (org-reduced-level (funcall outline-level)) level)
18683                 (throw 'exit nil))))
18684         (org-narrow-to-subtree))
18685        ((or (listp scope) (eq scope 'agenda))
18686         (let* ((files (if (listp scope) scope (org-agenda-files)))
18687                (scope 'agenda)
18688                (p1 (copy-sequence params))
18689                file)
18690           (plist-put p1 :tostring t)
18691           (plist-put p1 :multifile t)
18692           (plist-put p1 :scope 'file)
18693           (org-prepare-agenda-buffers files)
18694           (while (setq file (pop files))
18695             (with-current-buffer (find-buffer-visiting file)
18696               (push (org-clocktable-add-file
18697                      file (org-dblock-write:clocktable p1)) tbl)
18698               (setq total-time (+ (or total-time 0)
18699                                   org-clock-file-total-minutes)))))))
18700       (goto-char pos)
18702       (unless (eq scope 'agenda)
18703         (org-clock-sum ts te)
18704         (goto-char (point-min))
18705         (while (setq p (next-single-property-change (point) :org-clock-minutes))
18706           (goto-char p)
18707           (when (setq time (get-text-property p :org-clock-minutes))
18708             (save-excursion
18709               (beginning-of-line 1)
18710               (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
18711                          (setq level (org-reduced-level
18712                                       (- (match-end 1) (match-beginning 1))))
18713                          (<= level maxlevel))
18714                 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
18715                       hdl (match-string 2)
18716                       h (/ time 60)
18717                       m (- time (* 60 h)))
18718                 (if (and (not multifile) (= level 1)) (push "|-" tbl))
18719                 (push (concat
18720                        "| " (int-to-string level) "|" hlc hdl hlc " |"
18721                        (make-string (1- level) ?|)
18722                        hlc (format "%d:%02d" h m) hlc
18723                        " |") tbl))))))
18724       (setq tbl (nreverse tbl))
18725       (if tostring
18726           (if tbl (mapconcat 'identity tbl "\n") nil)
18727         (goto-char ins)
18728         (insert-before-markers
18729          "Clock summary at ["
18730          (substring
18731           (format-time-string (cdr org-time-stamp-formats))
18732           1 -1)
18733          "]."
18734          (if block
18735              (format "  Considered range is /%s/." block)
18736            "")
18737          "\n\n"
18738          (if (eq scope 'agenda) "|File" "")
18739          "|L|Headline|Time|\n")
18740         (setq total-time (or total-time org-clock-file-total-minutes)
18741               h (/ total-time 60)
18742               m (- total-time (* 60 h)))
18743         (insert-before-markers
18744          "|-\n|"
18745          (if (eq scope 'agenda) "|" "")
18746          "|"
18747          "*Total time*| "
18748          (format "*%d:%02d*" h m)
18749          "|\n|-\n")
18750         (setq tbl (delq nil tbl))
18751         (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
18752                  (equal (substring (car tbl) 0 2) "|-"))
18753             (pop tbl))
18754         (insert-before-markers (mapconcat
18755                                 'identity (delq nil tbl)
18756                                 (if (eq scope 'agenda) "\n|-\n" "\n")))
18757         (backward-delete-char 1)
18758         (goto-char ipos)
18759         (skip-chars-forward "^|")
18760         (org-table-align)))))
18762 (defun org-clocktable-add-file (file table)
18763   (if table
18764       (let ((lines (org-split-string table "\n"))
18765             (ff (file-name-nondirectory file)))
18766         (mapconcat 'identity
18767                    (mapcar (lambda (x)
18768                              (if (string-match org-table-dataline-regexp x)
18769                                  (concat "|" ff x)
18770                                x))
18771                            lines)
18772                    "\n"))))
18774 ;; FIXME: I don't think anybody uses this, ask David
18775 (defun org-collect-clock-time-entries ()
18776   "Return an internal list with clocking information.
18777 This list has one entry for each CLOCK interval.
18778 FIXME: describe the elements."
18779   (interactive)
18780   (let ((re (concat "^[ \t]*" org-clock-string
18781                     " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
18782         rtn beg end next cont level title total closedp leafp
18783         clockpos titlepos h m donep)
18784     (save-excursion
18785       (org-clock-sum)
18786       (goto-char (point-min))
18787       (while (re-search-forward re nil t)
18788         (setq clockpos (match-beginning 0)
18789               beg (match-string 1) end (match-string 2)
18790               cont (match-end 0))
18791         (setq beg (apply 'encode-time (org-parse-time-string beg))
18792               end (apply 'encode-time (org-parse-time-string end)))
18793         (org-back-to-heading t)
18794         (setq donep (org-entry-is-done-p))
18795         (setq titlepos (point)
18796               total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
18797               h (/ total 60) m (- total (* 60 h))
18798               total (cons h m))
18799         (looking-at "\\(\\*+\\) +\\(.*\\)")
18800         (setq level (- (match-end 1) (match-beginning 1))
18801               title (org-match-string-no-properties 2))
18802         (save-excursion (outline-next-heading) (setq next (point)))
18803         (setq closedp (re-search-forward org-closed-time-regexp next t))
18804         (goto-char next)
18805         (setq leafp (and (looking-at "^\\*+ ")
18806                          (<= (- (match-end 0) (point)) level)))
18807         (push (list beg end clockpos closedp donep
18808                     total title titlepos level leafp)
18809               rtn)
18810         (goto-char cont)))
18811     (nreverse rtn)))
18813 ;;;; Agenda, and Diary Integration
18815 ;;; Define the Org-agenda-mode
18817 (defvar org-agenda-mode-map (make-sparse-keymap)
18818   "Keymap for `org-agenda-mode'.")
18820 (defvar org-agenda-menu) ; defined later in this file.
18821 (defvar org-agenda-follow-mode nil)
18822 (defvar org-agenda-show-log nil)
18823 (defvar org-agenda-redo-command nil)
18824 (defvar org-agenda-mode-hook nil)
18825 (defvar org-agenda-type nil)
18826 (defvar org-agenda-force-single-file nil)
18828 (defun org-agenda-mode ()
18829   "Mode for time-sorted view on action items in Org-mode files.
18831 The following commands are available:
18833 \\{org-agenda-mode-map}"
18834   (interactive)
18835   (kill-all-local-variables)
18836   (setq org-agenda-undo-list nil
18837         org-agenda-pending-undo-list nil)
18838   (setq major-mode 'org-agenda-mode)
18839   ;; Keep global-font-lock-mode from turning on font-lock-mode
18840   (org-set-local 'font-lock-global-modes (list 'not major-mode))
18841   (setq mode-name "Org-Agenda")
18842   (use-local-map org-agenda-mode-map)
18843   (easy-menu-add org-agenda-menu)
18844   (if org-startup-truncated (setq truncate-lines t))
18845   (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
18846   (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
18847   ;; Make sure properties are removed when copying text
18848   (when (boundp 'buffer-substring-filters)
18849     (org-set-local 'buffer-substring-filters
18850                    (cons (lambda (x)
18851                            (set-text-properties 0 (length x) nil x) x)
18852                          buffer-substring-filters)))
18853   (unless org-agenda-keep-modes
18854     (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
18855           org-agenda-show-log nil))
18856   (easy-menu-change
18857    '("Agenda") "Agenda Files"
18858    (append
18859     (list
18860      (vector
18861       (if (get 'org-agenda-files 'org-restrict)
18862           "Restricted to single file"
18863         "Edit File List")
18864       '(org-edit-agenda-file-list)
18865       (not (get 'org-agenda-files 'org-restrict)))
18866      "--")
18867     (mapcar 'org-file-menu-entry (org-agenda-files))))
18868   (org-agenda-set-mode-name)
18869   (apply
18870    (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
18871    (list 'org-agenda-mode-hook)))
18873 (substitute-key-definition 'undo 'org-agenda-undo
18874                            org-agenda-mode-map global-map)
18875 (org-defkey org-agenda-mode-map "\C-i"     'org-agenda-goto)
18876 (org-defkey org-agenda-mode-map [(tab)]    'org-agenda-goto)
18877 (org-defkey org-agenda-mode-map "\C-m"     'org-agenda-switch-to)
18878 (org-defkey org-agenda-mode-map "\C-k"     'org-agenda-kill)
18879 (org-defkey org-agenda-mode-map "\C-c$"    'org-agenda-archive)
18880 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
18881 (org-defkey org-agenda-mode-map "$"        'org-agenda-archive)
18882 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
18883 (org-defkey org-agenda-mode-map " "        'org-agenda-show)
18884 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
18885 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
18886 (org-defkey org-agenda-mode-map [(control shift left)]  'org-agenda-todo-previousset)
18887 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
18888 (org-defkey org-agenda-mode-map "b"        'org-agenda-tree-to-indirect-buffer)
18889 (org-defkey org-agenda-mode-map "o"        'delete-other-windows)
18890 (org-defkey org-agenda-mode-map "L"        'org-agenda-recenter)
18891 (org-defkey org-agenda-mode-map "t"        'org-agenda-todo)
18892 (org-defkey org-agenda-mode-map "a"        'org-agenda-toggle-archive-tag)
18893 (org-defkey org-agenda-mode-map ":"        'org-agenda-set-tags)
18894 (org-defkey org-agenda-mode-map "."        'org-agenda-goto-today)
18895 (org-defkey org-agenda-mode-map "j"        'org-agenda-goto-date)
18896 (org-defkey org-agenda-mode-map "d"        'org-agenda-day-view)
18897 (org-defkey org-agenda-mode-map "w"        'org-agenda-week-view)
18898 (org-defkey org-agenda-mode-map "m"        'org-agenda-month-view)
18899 (org-defkey org-agenda-mode-map "y"        'org-agenda-year-view)
18900 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
18901 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
18902 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
18903 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
18905 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
18906 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
18907 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
18908 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
18909   (while l (org-defkey org-agenda-mode-map
18910              (int-to-string (pop l)) 'digit-argument)))
18912 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
18913 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
18914 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
18915 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
18916 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
18917 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
18918 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
18919 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
18920 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
18921 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
18922 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
18923 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
18924 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
18925 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
18926 (org-defkey org-agenda-mode-map "n" 'next-line)
18927 (org-defkey org-agenda-mode-map "p" 'previous-line)
18928 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
18929 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
18930 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
18931 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
18932 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
18933 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
18934 (eval-after-load "calendar"
18935   '(org-defkey calendar-mode-map org-calendar-to-agenda-key
18936      'org-calendar-goto-agenda))
18937 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
18938 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
18939 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
18940 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
18941 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
18942 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
18943 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
18944 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
18945 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
18946 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
18947 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
18948 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18949 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
18950 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
18951 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
18952 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
18953 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
18954 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
18955 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
18956 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
18957 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
18958 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
18960 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
18961   "Local keymap for agenda entries from Org-mode.")
18963 (org-defkey org-agenda-keymap
18964   (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
18965 (org-defkey org-agenda-keymap
18966   (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
18967 (when org-agenda-mouse-1-follows-link
18968   (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
18969 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
18970   '("Agenda"
18971     ("Agenda Files")
18972     "--"
18973     ["Show" org-agenda-show t]
18974     ["Go To (other window)" org-agenda-goto t]
18975     ["Go To (this window)" org-agenda-switch-to t]
18976     ["Follow Mode" org-agenda-follow-mode
18977      :style toggle :selected org-agenda-follow-mode :active t]
18978     ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
18979     "--"
18980     ["Cycle TODO" org-agenda-todo t]
18981     ["Archive subtree" org-agenda-archive t]
18982     ["Delete subtree" org-agenda-kill t]
18983     "--"
18984     ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
18985     ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
18986     ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
18987     ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
18988     "--"
18989     ("Tags and Properties"
18990      ["Show all Tags" org-agenda-show-tags t]
18991      ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
18992      ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
18993      "--"
18994      ["Column View" org-columns t])
18995     ("Date/Schedule"
18996      ["Schedule" org-agenda-schedule t]
18997      ["Set Deadline" org-agenda-deadline t]
18998      "--"
18999      ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19000      ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19001      ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19002     ("Clock"
19003      ["Clock in" org-agenda-clock-in t]
19004      ["Clock out" org-agenda-clock-out t]
19005      ["Clock cancel" org-agenda-clock-cancel t]
19006      ["Goto running clock" org-clock-goto t])
19007     ("Priority"
19008      ["Set Priority" org-agenda-priority t]
19009      ["Increase Priority" org-agenda-priority-up t]
19010      ["Decrease Priority" org-agenda-priority-down t]
19011      ["Show Priority" org-agenda-show-priority t])
19012     ("Calendar/Diary"
19013      ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19014      ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19015      ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19016      ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19017      ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19018      ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19019      "--"
19020      ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19021     "--"
19022     ("View"
19023      ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19024       :style radio :selected (equal org-agenda-ndays 1)]
19025      ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19026       :style radio :selected (equal org-agenda-ndays 7)]
19027      ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19028       :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19029      ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19030       :style radio :selected (member org-agenda-ndays '(365 366))]
19031      "--"
19032      ["Show Logbook entries" org-agenda-log-mode
19033       :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19034      ["Include Diary" org-agenda-toggle-diary
19035       :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19036      ["Use Time Grid" org-agenda-toggle-time-grid
19037       :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19038     ["Write view to file" org-write-agenda t]
19039     ["Rebuild buffer" org-agenda-redo t]
19040     ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19041     "--"
19042     ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19043     "--"
19044     ["Quit" org-agenda-quit t]
19045     ["Exit and Release Buffers" org-agenda-exit t]
19046     ))
19048 ;;; Agenda undo
19050 (defvar org-agenda-allow-remote-undo t
19051   "Non-nil means, allow remote undo from the agenda buffer.")
19052 (defvar org-agenda-undo-list nil
19053   "List of undoable operations in the agenda since last refresh.")
19054 (defvar org-agenda-undo-has-started-in nil
19055   "Buffers that have already seen `undo-start' in the current undo sequence.")
19056 (defvar org-agenda-pending-undo-list nil
19057   "In a series of undo commands, this is the list of remaning undo items.")
19059 (defmacro org-if-unprotected (&rest body)
19060   "Execute BODY if there is no `org-protected' text property at point."
19061   (declare (debug t))
19062   `(unless (get-text-property (point) 'org-protected)
19063      ,@body))
19065 (defmacro org-with-remote-undo (_buffer &rest _body)
19066   "Execute BODY while recording undo information in two buffers."
19067   (declare (indent 1) (debug t))
19068   `(let ((_cline (org-current-line))
19069          (_cmd this-command)
19070          (_buf1 (current-buffer))
19071          (_buf2 ,_buffer)
19072          (_undo1 buffer-undo-list)
19073          (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19074          _c1 _c2)
19075      ,@_body
19076      (when org-agenda-allow-remote-undo
19077        (setq _c1 (org-verify-change-for-undo
19078                   _undo1 (with-current-buffer _buf1 buffer-undo-list))
19079              _c2 (org-verify-change-for-undo
19080                   _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19081        (when (or _c1 _c2)
19082          ;; make sure there are undo boundaries
19083          (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19084          (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19085          ;; remember which buffer to undo
19086          (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19087                org-agenda-undo-list)))))
19089 (defun org-agenda-undo ()
19090   "Undo a remote editing step in the agenda.
19091 This undoes changes both in the agenda buffer and in the remote buffer
19092 that have been changed along."
19093   (interactive)
19094   (or org-agenda-allow-remote-undo
19095       (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19096   (if (not (eq this-command last-command))
19097       (setq org-agenda-undo-has-started-in nil
19098             org-agenda-pending-undo-list org-agenda-undo-list))
19099   (if (not org-agenda-pending-undo-list)
19100       (error "No further undo information"))
19101   (let* ((entry (pop org-agenda-pending-undo-list))
19102          buf line cmd rembuf)
19103     (setq cmd (pop entry) line (pop entry))
19104     (setq rembuf (nth 2 entry))
19105     (org-with-remote-undo rembuf
19106       (while (bufferp (setq buf (pop entry)))
19107         (if (pop entry)
19108             (with-current-buffer buf
19109               (let ((last-undo-buffer buf)
19110                     (inhibit-read-only t))
19111                 (unless (memq buf org-agenda-undo-has-started-in)
19112                   (push buf org-agenda-undo-has-started-in)
19113                   (make-local-variable 'pending-undo-list)
19114                   (undo-start))
19115                 (while (and pending-undo-list
19116                             (listp pending-undo-list)
19117                             (not (car pending-undo-list)))
19118                   (pop pending-undo-list))
19119                 (undo-more 1))))))
19120     (goto-line line)
19121     (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19123 (defun org-verify-change-for-undo (l1 l2)
19124   "Verify that a real change occurred between the undo lists L1 and L2."
19125   (while (and l1 (listp l1) (null (car l1))) (pop l1))
19126   (while (and l2 (listp l2) (null (car l2))) (pop l2))
19127   (not (eq l1 l2)))
19129 ;;; Agenda dispatch
19131 (defvar org-agenda-restrict nil)
19132 (defvar org-agenda-restrict-begin (make-marker))
19133 (defvar org-agenda-restrict-end (make-marker))
19134 (defvar org-agenda-last-dispatch-buffer nil)
19135 (defvar org-agenda-overriding-restriction nil)
19137 ;;;###autoload
19138 (defun org-agenda (arg &optional keys restriction)
19139   "Dispatch agenda commands to collect entries to the agenda buffer.
19140 Prompts for a command to execute.  Any prefix arg will be passed
19141 on to the selected command.  The default selections are:
19143 a     Call `org-agenda-list' to display the agenda for current day or week.
19144 t     Call `org-todo-list' to display the global todo list.
19145 T     Call `org-todo-list' to display the global todo list, select only
19146       entries with a specific TODO keyword (the user gets a prompt).
19147 m     Call `org-tags-view' to display headlines with tags matching
19148       a condition  (the user is prompted for the condition).
19149 M     Like `m', but select only TODO entries, no ordinary headlines.
19150 L     Create a timeline for the current buffer.
19151 e     Export views to associated files.
19153 More commands can be added by configuring the variable
19154 `org-agenda-custom-commands'.  In particular, specific tags and TODO keyword
19155 searches can be pre-defined in this way.
19157 If the current buffer is in Org-mode and visiting a file, you can also
19158 first press `<' once to indicate that the agenda should be temporarily
19159 \(until the next use of \\[org-agenda]) restricted to the current file.
19160 Pressing `<' twice means to restrict to the current subtree or region
19161 \(if active)."
19162   (interactive "P")
19163   (catch 'exit
19164     (let* ((prefix-descriptions nil)
19165            (org-agenda-custom-commands-orig org-agenda-custom-commands)
19166            (org-agenda-custom-commands
19167             ;; normalize different versions
19168             (delq nil
19169                   (mapcar
19170                    (lambda (x)
19171                      (cond ((stringp (cdr x))
19172                             (push x prefix-descriptions)
19173                             nil)
19174                            ((stringp (nth 1 x)) x)
19175                            ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19176                            (t (cons (car x) (cons "" (cdr x))))))
19177                    org-agenda-custom-commands)))
19178            (buf (current-buffer))
19179            (bfn (buffer-file-name (buffer-base-buffer)))
19180            entry key type match lprops ans)
19181       ;; Turn off restriction unless there is an overriding one
19182       (unless org-agenda-overriding-restriction
19183         (put 'org-agenda-files 'org-restrict nil)
19184         (setq org-agenda-restrict nil)
19185         (move-marker org-agenda-restrict-begin nil)
19186         (move-marker org-agenda-restrict-end nil))
19187       ;; Delete old local properties
19188       (put 'org-agenda-redo-command 'org-lprops nil)
19189       ;; Remember where this call originated
19190       (setq org-agenda-last-dispatch-buffer (current-buffer))
19191       (unless keys
19192         (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19193               keys (car ans)
19194               restriction (cdr ans)))
19195       ;; Estabish the restriction, if any
19196       (when (and (not org-agenda-overriding-restriction) restriction)
19197         (put 'org-agenda-files 'org-restrict (list bfn))
19198         (cond
19199          ((eq restriction 'region)
19200           (setq org-agenda-restrict t)
19201           (move-marker org-agenda-restrict-begin (region-beginning))
19202           (move-marker org-agenda-restrict-end (region-end)))
19203          ((eq restriction 'subtree)
19204           (save-excursion
19205             (setq org-agenda-restrict t)
19206             (org-back-to-heading t)
19207             (move-marker org-agenda-restrict-begin (point))
19208             (move-marker org-agenda-restrict-end
19209                          (progn (org-end-of-subtree t)))))))
19211       (require 'calendar)  ; FIXME: can we avoid this for some commands?
19212       ;; For example the todo list should not need it (but does...)
19213       (cond
19214        ((setq entry (assoc keys org-agenda-custom-commands))
19215         (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19216             (progn
19217               (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19218               (put 'org-agenda-redo-command 'org-lprops lprops)
19219               (cond
19220                ((eq type 'agenda)
19221                 (org-let lprops '(org-agenda-list current-prefix-arg)))
19222                ((eq type 'alltodo)
19223                 (org-let lprops '(org-todo-list current-prefix-arg)))
19224                ((eq type 'stuck)
19225                 (org-let lprops '(org-agenda-list-stuck-projects
19226                                   current-prefix-arg)))
19227                ((eq type 'tags)
19228                 (org-let lprops '(org-tags-view current-prefix-arg match)))
19229                ((eq type 'tags-todo)
19230                 (org-let lprops '(org-tags-view '(4) match)))
19231                ((eq type 'todo)
19232                 (org-let lprops '(org-todo-list match)))
19233                ((eq type 'tags-tree)
19234                 (org-check-for-org-mode)
19235                 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19236                ((eq type 'todo-tree)
19237                 (org-check-for-org-mode)
19238                 (org-let lprops
19239                   '(org-occur (concat "^" outline-regexp "[ \t]*"
19240                                       (regexp-quote match) "\\>"))))
19241                ((eq type 'occur-tree)
19242                 (org-check-for-org-mode)
19243                 (org-let lprops '(org-occur match)))
19244                ((functionp type)
19245                 (org-let lprops '(funcall type match)))
19246                ((fboundp type)
19247                 (org-let lprops '(funcall type match)))
19248                (t (error "Invalid custom agenda command type %s" type))))
19249           (org-run-agenda-series (nth 1 entry) (cddr entry))))
19250        ((equal keys "C")
19251         (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19252         (customize-variable 'org-agenda-custom-commands))
19253        ((equal keys "a") (call-interactively 'org-agenda-list))
19254        ((equal keys "t") (call-interactively 'org-todo-list))
19255        ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19256        ((equal keys "m") (call-interactively 'org-tags-view))
19257        ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19258        ((equal keys "e") (call-interactively 'org-store-agenda-views))
19259        ((equal keys "L")
19260         (unless (org-mode-p)
19261           (error "This is not an Org-mode file"))
19262         (unless restriction
19263           (put 'org-agenda-files 'org-restrict (list bfn))
19264           (org-call-with-arg 'org-timeline arg)))
19265        ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19266        ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19267        ((equal keys "!") (customize-variable 'org-stuck-projects))
19268        (t (error "Invalid agenda key"))))))
19270 (defun org-agenda-normalize-custom-commands (cmds)
19271   (delq nil
19272         (mapcar
19273          (lambda (x)
19274            (cond ((stringp (cdr x)) nil)
19275                  ((stringp (nth 1 x)) x)
19276                  ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19277                  (t (cons (car x) (cons "" (cdr x))))))
19278          cmds)))
19280 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19281   "The user interface for selecting an agenda command."
19282   (catch 'exit
19283     (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19284            (restrict-ok (and bfn (org-mode-p)))
19285            (region-p (org-region-active-p))
19286            (custom org-agenda-custom-commands)
19287            (selstring "")
19288            restriction second-time
19289            c entry key type match prefixes rmheader header-end custom1 desc)
19290       (save-window-excursion
19291         (delete-other-windows)
19292         (org-switch-to-buffer-other-window " *Agenda Commands*")
19293         (erase-buffer)
19294         (insert (eval-when-compile
19295                   (let ((header
19297 Press key for an agenda command:        <   Buffer,subtree/region restriction
19298 --------------------------------        >   Remove restriction
19299 a   Agenda for current week or day      e   Export agenda views
19300 t   List of all TODO entries            T   Entries with special TODO kwd
19301 m   Match a TAGS query                  M   Like m, but only TODO entries
19302 L   Timeline for current buffer         #   List stuck projects (!=configure)
19303 /   Multi-occur                         C   Configure custom agenda commands
19305                         (start 0))
19306                     (while (string-match
19307                             "\\(^\\|   \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19308                             header start)
19309                       (setq start (match-end 0))
19310                       (add-text-properties (match-beginning 2) (match-end 2)
19311                                            '(face bold) header))
19312                     header)))
19313         (setq header-end (move-marker (make-marker) (point)))
19314         (while t
19315           (setq custom1 custom)
19316           (when (eq rmheader t)
19317             (goto-line 1)
19318             (re-search-forward ":" nil t)
19319             (delete-region (match-end 0) (point-at-eol))
19320             (forward-char 1)
19321             (looking-at "-+")
19322             (delete-region (match-end 0) (point-at-eol))
19323             (move-marker header-end (match-end 0)))
19324           (goto-char header-end)
19325           (delete-region (point) (point-max))
19326           (while (setq entry (pop custom1))
19327             (setq key (car entry) desc (nth 1 entry)
19328                   type (nth 2 entry) match (nth 3 entry))
19329             (if (> (length key) 1)
19330                 (add-to-list 'prefixes (string-to-char key))
19331               (insert
19332                (format
19333                 "\n%-4s%-14s: %s"
19334                 (org-add-props (copy-sequence key)
19335                     '(face bold))
19336                 (cond
19337                  ((string-match "\\S-" desc) desc)
19338                  ((eq type 'agenda) "Agenda for current week or day")
19339                  ((eq type 'alltodo) "List of all TODO entries")
19340                  ((eq type 'stuck) "List of stuck projects")
19341                  ((eq type 'todo) "TODO keyword")
19342                  ((eq type 'tags) "Tags query")
19343                  ((eq type 'tags-todo) "Tags (TODO)")
19344                  ((eq type 'tags-tree) "Tags tree")
19345                  ((eq type 'todo-tree) "TODO kwd tree")
19346                  ((eq type 'occur-tree) "Occur tree")
19347                  ((functionp type) (if (symbolp type)
19348                                        (symbol-name type)
19349                                      "Lambda expression"))
19350                  (t "???"))
19351                 (cond
19352                  ((stringp match)
19353                   (org-add-props match nil 'face 'org-warning))
19354                  (match
19355                   (format "set of %d commands" (length match)))
19356                  (t ""))))))
19357           (when prefixes
19358             (mapc (lambda (x)
19359                     (insert
19360                      (format "\n%s   %s"
19361                              (org-add-props (char-to-string x)
19362                                             nil 'face 'bold)
19363                              (or (cdr (assoc (concat selstring (char-to-string x))
19364                                              prefix-descriptions))
19365                                  "Prefix key"))))
19366                   prefixes))
19367           (goto-char (point-min))
19368           (when (fboundp 'fit-window-to-buffer)
19369             (if second-time
19370                 (if (not (pos-visible-in-window-p (point-max)))
19371                     (fit-window-to-buffer))
19372               (setq second-time t)
19373               (fit-window-to-buffer)))
19374           (message "Press key for agenda command%s:"
19375                    (if (or restrict-ok org-agenda-overriding-restriction)
19376                        (if org-agenda-overriding-restriction
19377                            " (restriction lock active)"
19378                          (if restriction
19379                              (format " (restricted to %s)" restriction)
19380                            " (unrestricted)"))
19381                      ""))
19382           (setq c (read-char-exclusive))
19383           (message "")
19384           (cond
19385            ((assoc (char-to-string c) custom)
19386             (setq selstring (concat selstring (char-to-string c)))
19387             (throw 'exit (cons selstring restriction)))
19388            ((memq c prefixes)
19389             (setq selstring (concat selstring (char-to-string c))
19390                   prefixes nil
19391                   rmheader (or rmheader t)
19392                   custom (delq nil (mapcar
19393                                     (lambda (x)
19394                                       (if (or (= (length (car x)) 1)
19395                                               (/= (string-to-char (car x)) c))
19396                                           nil
19397                                         (cons (substring (car x) 1) (cdr x))))
19398                                     custom))))
19399            ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19400             (message "Restriction is only possible in Org-mode buffers")
19401             (ding) (sit-for 1))
19402            ((eq c ?1)
19403             (org-agenda-remove-restriction-lock 'noupdate)
19404             (setq restriction 'buffer))
19405            ((eq c ?0)
19406             (org-agenda-remove-restriction-lock 'noupdate)
19407             (setq restriction (if region-p 'region 'subtree)))
19408            ((eq c ?<)
19409             (org-agenda-remove-restriction-lock 'noupdate)
19410             (setq restriction
19411                   (cond
19412                    ((eq restriction 'buffer)
19413                     (if region-p 'region 'subtree))
19414                    ((memq restriction '(subtree region))
19415                     nil)
19416                    (t 'buffer))))
19417            ((eq c ?>)
19418             (org-agenda-remove-restriction-lock 'noupdate)
19419             (setq restriction nil))
19420            ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19421             (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19422            ((and (> (length selstring) 0) (eq c ?\d))
19423             (delete-window)
19424             (org-agenda-get-restriction-and-command prefix-descriptions))
19425   
19426            ((equal c ?q) (error "Abort"))
19427            (t (error "Invalid key %c" c))))))))
19429 (defun org-run-agenda-series (name series)
19430   (org-prepare-agenda name)
19431   (let* ((org-agenda-multi t)
19432          (redo (list 'org-run-agenda-series name (list 'quote series)))
19433          (cmds (car series))
19434          (gprops (nth 1 series))
19435          match ;; The byte compiler incorrectly complains about this.  Keep it!
19436          cmd type lprops)
19437     (while (setq cmd (pop cmds))
19438       (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19439       (cond
19440        ((eq type 'agenda)
19441         (org-let2 gprops lprops
19442           '(call-interactively 'org-agenda-list)))
19443        ((eq type 'alltodo)
19444         (org-let2 gprops lprops
19445           '(call-interactively 'org-todo-list)))
19446        ((eq type 'stuck)
19447         (org-let2 gprops lprops
19448           '(call-interactively 'org-agenda-list-stuck-projects)))
19449        ((eq type 'tags)
19450         (org-let2 gprops lprops
19451                   '(org-tags-view current-prefix-arg match)))
19452        ((eq type 'tags-todo)
19453         (org-let2 gprops lprops
19454                   '(org-tags-view '(4) match)))
19455        ((eq type 'todo)
19456         (org-let2 gprops lprops
19457                   '(org-todo-list match)))
19458        ((fboundp type)
19459         (org-let2 gprops lprops
19460           '(funcall type match)))
19461        (t (error "Invalid type in command series"))))
19462     (widen)
19463     (setq org-agenda-redo-command redo)
19464     (goto-char (point-min)))
19465   (org-finalize-agenda))
19467 ;;;###autoload
19468 (defmacro org-batch-agenda (cmd-key &rest parameters)
19469   "Run an agenda command in batch mode and send the result to STDOUT.
19470 If CMD-KEY is a string of length 1, it is used as a key in
19471 `org-agenda-custom-commands' and triggers this command.  If it is a
19472 longer string is is used as a tags/todo match string.
19473 Paramters are alternating variable names and values that will be bound
19474 before running the agenda command."
19475   (let (pars)
19476     (while parameters
19477       (push (list (pop parameters) (if parameters (pop parameters))) pars))
19478     (if (> (length cmd-key) 2)
19479         (eval (list 'let (nreverse pars)
19480                     (list 'org-tags-view nil cmd-key)))
19481       (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19482     (set-buffer org-agenda-buffer-name)
19483     (princ (org-encode-for-stdout (buffer-string)))))
19485 (defun org-encode-for-stdout (string)
19486   (if (fboundp 'encode-coding-string)
19487       (encode-coding-string string buffer-file-coding-system)
19488     string))
19490 (defvar org-agenda-info nil)
19492 ;;;###autoload
19493 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19494   "Run an agenda command in batch mode and send the result to STDOUT.
19495 If CMD-KEY is a string of length 1, it is used as a key in
19496 `org-agenda-custom-commands' and triggers this command.  If it is a
19497 longer string is is used as a tags/todo match string.
19498 Paramters are alternating variable names and values that will be bound
19499 before running the agenda command.
19501 The output gives a line for each selected agenda item.  Each
19502 item is a list of comma-separated values, like this:
19504 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19506 category     The category of the item
19507 head         The headline, without TODO kwd, TAGS and PRIORITY
19508 type         The type of the agenda entry, can be
19509                 todo               selected in TODO match
19510                 tagsmatch          selected in tags match
19511                 diary              imported from diary
19512                 deadline           a deadline on given date
19513                 scheduled          scheduled on given date
19514                 timestamp          entry has timestamp on given date
19515                 closed             entry was closed on given date
19516                 upcoming-deadline  warning about deadline
19517                 past-scheduled     forwarded scheduled item
19518                 block              entry has date block including g. date
19519 todo         The todo keyword, if any
19520 tags         All tags including inherited ones, separated by colons
19521 date         The relevant date, like 2007-2-14
19522 time         The time, like 15:00-16:50
19523 extra        Sting with extra planning info
19524 priority-l   The priority letter if any was given
19525 priority-n   The computed numerical priority
19526 agenda-day   The day in the agenda where this is listed"
19528   (let (pars)
19529     (while parameters
19530       (push (list (pop parameters) (if parameters (pop parameters))) pars))
19531     (push (list 'org-agenda-remove-tags t) pars)
19532     (if (> (length cmd-key) 2)
19533         (eval (list 'let (nreverse pars)
19534                     (list 'org-tags-view nil cmd-key)))
19535       (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19536     (set-buffer org-agenda-buffer-name)
19537     (let* ((lines (org-split-string (buffer-string) "\n"))
19538            line)
19539       (while (setq line (pop lines))
19540         (catch 'next
19541           (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
19542           (setq org-agenda-info
19543                 (org-fix-agenda-info (text-properties-at 0 line)))
19544           (princ
19545            (org-encode-for-stdout
19546             (mapconcat 'org-agenda-export-csv-mapper
19547                        '(org-category txt type todo tags date time-of-day extra
19548                                       priority-letter priority agenda-day)
19549                       ",")))
19550           (princ "\n"))))))
19552 (defun org-fix-agenda-info (props)
19553   "Make sure all properties on an agenda item have a canonical form,
19554 so the the export commands caneasily use it."
19555   (let (tmp re)
19556     (when (setq tmp (plist-get props 'tags))
19557       (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
19558     (when (setq tmp (plist-get props 'date))
19559       (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19560       (let ((calendar-date-display-form '(year "-" month "-" day)))
19561         '((format "%4d, %9s %2s, %4s" dayname monthname day year))
19563         (setq tmp (calendar-date-string tmp)))
19564       (setq props (plist-put props 'date tmp)))
19565     (when (setq tmp (plist-get props 'day))
19566       (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19567       (let ((calendar-date-display-form '(year "-" month "-" day)))
19568         (setq tmp (calendar-date-string tmp)))
19569       (setq props (plist-put props 'day tmp))
19570       (setq props (plist-put props 'agenda-day tmp)))
19571     (when (setq tmp (plist-get props 'txt))
19572       (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
19573         (plist-put props 'priority-letter (match-string 1 tmp))
19574         (setq tmp (replace-match "" t t tmp)))
19575       (when (and (setq re (plist-get props 'org-todo-regexp))
19576                  (setq re (concat "\\`\\.*" re " ?"))
19577                  (string-match re tmp))
19578         (plist-put props 'todo (match-string 1 tmp))
19579         (setq tmp (replace-match "" t t tmp)))
19580       (plist-put props 'txt tmp)))
19581   props)
19583 (defun org-agenda-export-csv-mapper (prop)
19584   (let ((res (plist-get org-agenda-info prop)))
19585     (setq res
19586           (cond
19587            ((not res) "")
19588            ((stringp res) res)
19589            (t (prin1-to-string res))))
19590     (while (string-match "," res)
19591       (setq res (replace-match ";" t t res)))
19592     (org-trim res)))
19595 ;;;###autoload
19596 (defun org-store-agenda-views (&rest parameters)
19597   (interactive)
19598   (eval (list 'org-batch-store-agenda-views)))
19600 ;; FIXME, why is this a macro?????
19601 ;;;###autoload
19602 (defmacro org-batch-store-agenda-views (&rest parameters)
19603   "Run all custom agenda commands that have a file argument."
19604   (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
19605         (pop-up-frames nil)
19606         (dir default-directory)
19607         pars cmd thiscmdkey files opts)
19608     (while parameters
19609       (push (list (pop parameters) (if parameters (pop parameters))) pars))
19610     (setq pars (reverse pars))
19611     (save-window-excursion
19612       (while cmds
19613         (setq cmd (pop cmds)
19614               thiscmdkey (car cmd)
19615               opts (nth 4 cmd)
19616               files (nth 5 cmd))
19617         (if (stringp files) (setq files (list files)))
19618         (when files
19619           (eval (list 'let (append org-agenda-exporter-settings opts pars)
19620                       (list 'org-agenda nil thiscmdkey)))
19621           (set-buffer org-agenda-buffer-name)
19622           (while files
19623             (eval (list 'let (append org-agenda-exporter-settings opts pars)
19624                         (list 'org-write-agenda
19625                               (expand-file-name (pop files) dir) t))))
19626           (and (get-buffer org-agenda-buffer-name)
19627                (kill-buffer org-agenda-buffer-name)))))))
19629 (defun org-write-agenda (file &optional nosettings)
19630   "Write the current buffer (an agenda view) as a file.
19631 Depending on the extension of the file name, plain text (.txt),
19632 HTML (.html or .htm) or Postscript (.ps) is produced.
19633 If NOSETTINGS is given, do not scope the settings of
19634 `org-agenda-exporter-settings' into the export commands.  This is used when
19635 the settings have already been scoped and we do not wish to overrule other,
19636 higher priority settings."
19637   (interactive "FWrite agenda to file: ")
19638   (if (not (file-writable-p file))
19639       (error "Cannot write agenda to file %s" file))
19640   (cond
19641    ((string-match "\\.html?\\'" file) (require 'htmlize))
19642    ((string-match "\\.ps\\'" file) (require 'ps-print)))
19643   (org-let (if nosettings nil org-agenda-exporter-settings)
19644     '(save-excursion
19645        (save-window-excursion
19646          (cond
19647           ((string-match "\\.html?\\'" file)
19648            (set-buffer (htmlize-buffer (current-buffer)))
19650            (when (and org-agenda-export-html-style
19651                       (string-match "<style>" org-agenda-export-html-style))
19652              ;; replace <style> section with org-agenda-export-html-style
19653              (goto-char (point-min))
19654              (kill-region (- (search-forward "<style") 6)
19655                           (search-forward "</style>"))
19656              (insert org-agenda-export-html-style))
19657            (write-file file)
19658            (kill-buffer (current-buffer))
19659            (message "HTML written to %s" file))
19660           ((string-match "\\.ps\\'" file)
19661            (ps-print-buffer-with-faces file)
19662            (message "Postscript written to %s" file))
19663           (t
19664            (let ((bs (buffer-string)))
19665              (find-file file)
19666              (insert bs)
19667              (save-buffer 0)
19668              (kill-buffer (current-buffer))
19669              (message "Plain text written to %s" file))))))
19670     (set-buffer org-agenda-buffer-name)))
19672 (defmacro org-no-read-only (&rest body)
19673   "Inhibit read-only for BODY."
19674   `(let ((inhibit-read-only t)) ,@body))
19676 (defun org-check-for-org-mode ()
19677   "Make sure current buffer is in org-mode.  Error if not."
19678   (or (org-mode-p)
19679       (error "Cannot execute org-mode agenda command on buffer in %s."
19680              major-mode)))
19682 (defun org-fit-agenda-window ()
19683   "Fit the window to the buffer size."
19684   (and (memq org-agenda-window-setup '(reorganize-frame))
19685        (fboundp 'fit-window-to-buffer)
19686        (fit-window-to-buffer
19687         nil
19688         (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
19689         (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
19691 ;;; Agenda file list
19693 (defun org-agenda-files (&optional unrestricted)
19694   "Get the list of agenda files.
19695 Optional UNRESTRICTED means return the full list even if a restriction
19696 is currently in place."
19697   (let ((files
19698          (cond
19699           ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
19700           ((stringp org-agenda-files) (org-read-agenda-file-list))
19701           ((listp org-agenda-files) org-agenda-files)
19702           (t (error "Invalid value of `org-agenda-files'")))))
19703     (setq files (apply 'append
19704                        (mapcar (lambda (f)
19705                                  (if (file-directory-p f)
19706                                      (directory-files f t
19707                                                       org-agenda-file-regexp)
19708                                    (list f)))
19709                                files)))
19710     (if org-agenda-skip-unavailable-files
19711         (delq nil
19712               (mapcar (function
19713                        (lambda (file)
19714                          (and (file-readable-p file) file)))
19715                       files))
19716       files))) ; `org-check-agenda-file' will remove them from the list
19718 (defun org-edit-agenda-file-list ()
19719   "Edit the list of agenda files.
19720 Depending on setup, this either uses customize to edit the variable
19721 `org-agenda-files', or it visits the file that is holding the list.  In the
19722 latter case, the buffer is set up in a way that saving it automatically kills
19723 the buffer and restores the previous window configuration."
19724   (interactive)
19725   (if (stringp org-agenda-files)
19726       (let ((cw (current-window-configuration)))
19727         (find-file org-agenda-files)
19728         (org-set-local 'org-window-configuration cw)
19729         (org-add-hook 'after-save-hook
19730                       (lambda ()
19731                         (set-window-configuration
19732                          (prog1 org-window-configuration
19733                            (kill-buffer (current-buffer))))
19734                         (org-install-agenda-files-menu)
19735                         (message "New agenda file list installed"))
19736                       nil 'local)
19737         (message "%s" (substitute-command-keys
19738                        "Edit list and finish with \\[save-buffer]")))
19739     (customize-variable 'org-agenda-files)))
19741 (defun org-store-new-agenda-file-list (list)
19742   "Set new value for the agenda file list and save it correcly."
19743   (if (stringp org-agenda-files)
19744       (let ((f org-agenda-files) b)
19745         (while (setq b (find-buffer-visiting f)) (kill-buffer b))
19746         (with-temp-file f
19747           (insert (mapconcat 'identity list "\n") "\n")))
19748     (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
19749       (setq org-agenda-files list)
19750       (customize-save-variable 'org-agenda-files org-agenda-files))))
19752 (defun org-read-agenda-file-list ()
19753   "Read the list of agenda files from a file."
19754   (when (stringp org-agenda-files)
19755     (with-temp-buffer
19756       (insert-file-contents org-agenda-files)
19757       (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
19760 ;;;###autoload
19761 (defun org-cycle-agenda-files ()
19762   "Cycle through the files in `org-agenda-files'.
19763 If the current buffer visits an agenda file, find the next one in the list.
19764 If the current buffer does not, find the first agenda file."
19765   (interactive)
19766   (let* ((fs (org-agenda-files t))
19767          (files (append fs (list (car fs))))
19768          (tcf (if buffer-file-name (file-truename buffer-file-name)))
19769          file)
19770     (unless files (error "No agenda files"))
19771     (catch 'exit
19772       (while (setq file (pop files))
19773         (if (equal (file-truename file) tcf)
19774             (when (car files)
19775               (find-file (car files))
19776               (throw 'exit t))))
19777       (find-file (car fs)))
19778     (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
19780 (defun org-agenda-file-to-front (&optional to-end)
19781   "Move/add the current file to the top of the agenda file list.
19782 If the file is not present in the list, it is added to the front.  If it is
19783 present, it is moved there.  With optional argument TO-END, add/move to the
19784 end of the list."
19785   (interactive "P")
19786   (let ((org-agenda-skip-unavailable-files nil)
19787         (file-alist (mapcar (lambda (x)
19788                               (cons (file-truename x) x))
19789                             (org-agenda-files t)))
19790         (ctf (file-truename buffer-file-name))
19791         x had)
19792     (setq x (assoc ctf file-alist) had x)
19794     (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
19795     (if to-end
19796         (setq file-alist (append (delq x file-alist) (list x)))
19797       (setq file-alist (cons x (delq x file-alist))))
19798     (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
19799     (org-install-agenda-files-menu)
19800     (message "File %s to %s of agenda file list"
19801              (if had "moved" "added") (if to-end "end" "front"))))
19803 (defun org-remove-file (&optional file)
19804   "Remove current file from the list of files in variable `org-agenda-files'.
19805 These are the files which are being checked for agenda entries.
19806 Optional argument FILE means, use this file instead of the current."
19807   (interactive)
19808   (let* ((org-agenda-skip-unavailable-files nil)
19809          (file (or file buffer-file-name))
19810          (true-file (file-truename file))
19811          (afile (abbreviate-file-name file))
19812          (files (delq nil (mapcar
19813                            (lambda (x)
19814                              (if (equal true-file
19815                                         (file-truename x))
19816                                  nil x))
19817                            (org-agenda-files t)))))
19818     (if (not (= (length files) (length (org-agenda-files t))))
19819         (progn
19820           (org-store-new-agenda-file-list files)
19821           (org-install-agenda-files-menu)
19822           (message "Removed file: %s" afile))
19823       (message "File was not in list: %s (not removed)" afile))))
19825 (defun org-file-menu-entry (file)
19826   (vector file (list 'find-file file) t))
19828 (defun org-check-agenda-file (file)
19829   "Make sure FILE exists.  If not, ask user what to do."
19830   (when (not (file-exists-p file))
19831     (message "non-existent file %s. [R]emove from list or [A]bort?"
19832              (abbreviate-file-name file))
19833     (let ((r (downcase (read-char-exclusive))))
19834       (cond
19835        ((equal r ?r)
19836         (org-remove-file file)
19837         (throw 'nextfile t))
19838        (t (error "Abort"))))))
19840 ;;; Agenda prepare and finalize
19842 (defvar org-agenda-multi nil)  ; dynammically scoped
19843 (defvar org-agenda-buffer-name "*Org Agenda*")
19844 (defvar org-pre-agenda-window-conf nil)
19845 (defvar org-agenda-name nil)
19846 (defun org-prepare-agenda (&optional name)
19847   (setq org-todo-keywords-for-agenda nil)
19848   (setq org-done-keywords-for-agenda nil)
19849   (if org-agenda-multi
19850       (progn
19851         (setq buffer-read-only nil)
19852         (goto-char (point-max))
19853         (unless (or (bobp) org-agenda-compact-blocks)
19854           (insert "\n" (make-string (window-width) ?=) "\n"))
19855         (narrow-to-region (point) (point-max)))
19856     (org-agenda-maybe-reset-markers 'force)
19857     (org-prepare-agenda-buffers (org-agenda-files))
19858     (setq org-todo-keywords-for-agenda
19859           (org-uniquify org-todo-keywords-for-agenda))
19860     (setq org-done-keywords-for-agenda
19861           (org-uniquify org-done-keywords-for-agenda))
19862     (let* ((abuf (get-buffer-create org-agenda-buffer-name))
19863            (awin (get-buffer-window abuf)))
19864       (cond
19865        ((equal (current-buffer) abuf) nil)
19866        (awin (select-window awin))
19867        ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
19868        ((equal org-agenda-window-setup 'current-window)
19869         (switch-to-buffer abuf))
19870        ((equal org-agenda-window-setup 'other-window)
19871         (org-switch-to-buffer-other-window abuf))
19872        ((equal org-agenda-window-setup 'other-frame)
19873         (switch-to-buffer-other-frame abuf))
19874        ((equal org-agenda-window-setup 'reorganize-frame)
19875         (delete-other-windows)
19876         (org-switch-to-buffer-other-window abuf))))
19877     (setq buffer-read-only nil)
19878     (erase-buffer)
19879     (org-agenda-mode)
19880     (and name (not org-agenda-name)
19881          (org-set-local 'org-agenda-name name)))
19882   (setq buffer-read-only nil))
19884 (defun org-finalize-agenda ()
19885   "Finishing touch for the agenda buffer, called just before displaying it."
19886   (unless org-agenda-multi
19887     (save-excursion
19888       (let ((inhibit-read-only t))
19889         (goto-char (point-min))
19890         (while (org-activate-bracket-links (point-max))
19891           (add-text-properties (match-beginning 0) (match-end 0)
19892                                '(face org-link)))
19893         (org-agenda-align-tags)
19894         (unless org-agenda-with-colors
19895           (remove-text-properties (point-min) (point-max) '(face nil))))
19896       (if (and (boundp 'org-overriding-columns-format)
19897                org-overriding-columns-format)
19898           (org-set-local 'org-overriding-columns-format
19899                          org-overriding-columns-format))
19900       (if (and (boundp 'org-agenda-view-columns-initially)
19901                org-agenda-view-columns-initially)
19902           (org-agenda-columns))
19903       (when org-agenda-fontify-priorities
19904         (org-fontify-priorities))
19905       (run-hooks 'org-finalize-agenda-hook))))
19907 (defun org-fontify-priorities ()
19908   "Make highest priority lines bold, and lowest italic."
19909   (interactive)
19910   (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
19911                         (org-delete-overlay o)))
19912         (org-overlays-in (point-min) (point-max)))
19913   (save-excursion
19914     (let ((inhibit-read-only t)
19915           b e p ov h l)
19916       (goto-char (point-min))
19917       (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
19918         (setq h (or (get-char-property (point) 'org-highest-priority)
19919                     org-highest-priority)
19920               l (or (get-char-property (point) 'org-lowest-priority)
19921                     org-lowest-priority)
19922               p (string-to-char (match-string 1))
19923               b (match-beginning 0) e (point-at-eol)
19924               ov (org-make-overlay b e))
19925         (org-overlay-put
19926          ov 'face
19927          (cond ((listp org-agenda-fontify-priorities)
19928                 (cdr (assoc p org-agenda-fontify-priorities)))
19929                ((equal p l) 'italic)
19930                ((equal p h) 'bold)))
19931         (org-overlay-put ov 'org-type 'org-priority)))))
19933 (defun org-prepare-agenda-buffers (files)
19934   "Create buffers for all agenda files, protect archived trees and comments."
19935   (interactive)
19936   (let ((pa '(:org-archived t))
19937         (pc '(:org-comment t))
19938         (pall '(:org-archived t :org-comment t))
19939         (inhibit-read-only t)
19940         (rea (concat ":" org-archive-tag ":"))
19941              bmp file re)
19942     (save-excursion
19943       (save-restriction
19944         (while (setq file (pop files))
19945           (if (bufferp file)
19946               (set-buffer file)
19947             (org-check-agenda-file file)
19948             (set-buffer (org-get-agenda-file-buffer file)))
19949           (widen)
19950           (setq bmp (buffer-modified-p))
19951           (org-refresh-category-properties)
19952           (setq org-todo-keywords-for-agenda
19953                 (append org-todo-keywords-for-agenda org-todo-keywords-1))
19954           (setq org-done-keywords-for-agenda
19955                 (append org-done-keywords-for-agenda org-done-keywords))
19956           (save-excursion
19957             (remove-text-properties (point-min) (point-max) pall)
19958             (when org-agenda-skip-archived-trees
19959               (goto-char (point-min))
19960               (while (re-search-forward rea nil t)
19961                 (if (org-on-heading-p t)
19962                     (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
19963             (goto-char (point-min))
19964             (setq re (concat "^\\*+ +" org-comment-string "\\>"))
19965             (while (re-search-forward re nil t)
19966               (add-text-properties
19967                (match-beginning 0) (org-end-of-subtree t) pc)))
19968           (set-buffer-modified-p bmp))))))
19970 (defvar org-agenda-skip-function nil
19971   "Function to be called at each match during agenda construction.
19972 If this function returns nil, the current match should not be skipped.
19973 Otherwise, the function must return a position from where the search
19974 should be continued.
19975 This may also be a Lisp form, it will be evaluated.
19976 Never set this variable using `setq' or so, because then it will apply
19977 to all future agenda commands.  Instead, bind it with `let' to scope
19978 it dynamically into the agenda-constructing command.  A good way to set
19979 it is through options in org-agenda-custom-commands.")
19981 (defun org-agenda-skip ()
19982   "Throw to `:skip' in places that should be skipped.
19983 Also moves point to the end of the skipped region, so that search can
19984 continue from there."
19985   (let ((p (point-at-bol)) to fp)
19986     (and org-agenda-skip-archived-trees
19987          (get-text-property p :org-archived)
19988          (org-end-of-subtree t)
19989          (throw :skip t))
19990     (and (get-text-property p :org-comment)
19991          (org-end-of-subtree t)
19992          (throw :skip t))
19993     (if (equal (char-after p) ?#) (throw :skip t))
19994     (when (and (or (setq fp (functionp org-agenda-skip-function))
19995                    (consp org-agenda-skip-function))
19996                (setq to (save-excursion
19997                           (save-match-data
19998                             (if fp
19999                                 (funcall org-agenda-skip-function)
20000                               (eval org-agenda-skip-function))))))
20001       (goto-char to)
20002       (throw :skip t))))
20004 (defvar org-agenda-markers nil
20005   "List of all currently active markers created by `org-agenda'.")
20006 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20007   "Creation time of the last agenda marker.")
20009 (defun org-agenda-new-marker (&optional pos)
20010   "Return a new agenda marker.
20011 Org-mode keeps a list of these markers and resets them when they are
20012 no longer in use."
20013   (let ((m (copy-marker (or pos (point)))))
20014     (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20015     (push m org-agenda-markers)
20016     m))
20018 (defun org-agenda-maybe-reset-markers (&optional force)
20019   "Reset markers created by `org-agenda'.  But only if they are old enough."
20020   (if (or (and force (not org-agenda-multi))
20021           (> (- (time-to-seconds (current-time))
20022                 org-agenda-last-marker-time)
20023              5))
20024       (while org-agenda-markers
20025         (move-marker (pop org-agenda-markers) nil))))
20027 (defun org-get-agenda-file-buffer (file)
20028   "Get a buffer visiting FILE.  If the buffer needs to be created, add
20029 it to the list of buffers which might be released later."
20030   (let ((buf (org-find-base-buffer-visiting file)))
20031     (if buf
20032         buf ; just return it
20033       ;; Make a new buffer and remember it
20034       (setq buf (find-file-noselect file))
20035       (if buf (push buf org-agenda-new-buffers))
20036       buf)))
20038 (defun org-release-buffers (blist)
20039   "Release all buffers in list, asking the user for confirmation when needed.
20040 When a buffer is unmodified, it is just killed.  When modified, it is saved
20041 \(if the user agrees) and then killed."
20042   (let (buf file)
20043     (while (setq buf (pop blist))
20044       (setq file (buffer-file-name buf))
20045       (when (and (buffer-modified-p buf)
20046                  file
20047                  (y-or-n-p (format "Save file %s? " file)))
20048         (with-current-buffer buf (save-buffer)))
20049       (kill-buffer buf))))
20051 (defun org-get-category (&optional pos)
20052   "Get the category applying to position POS."
20053   (get-text-property (or pos (point)) 'org-category))
20055 ;;; Agenda timeline
20057 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20059 (defun org-timeline (&optional include-all)
20060   "Show a time-sorted view of the entries in the current org file.
20061 Only entries with a time stamp of today or later will be listed.  With
20062 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20063 under the current date.
20064 If the buffer contains an active region, only check the region for
20065 dates."
20066   (interactive "P")
20067   (require 'calendar)
20068   (org-compile-prefix-format 'timeline)
20069   (org-set-sorting-strategy 'timeline)
20070   (let* ((dopast t)
20071          (dotodo include-all)
20072          (doclosed org-agenda-show-log)
20073          (entry buffer-file-name)
20074          (date (calendar-current-date))
20075          (beg (if (org-region-active-p) (region-beginning) (point-min)))
20076          (end (if (org-region-active-p) (region-end) (point-max)))
20077          (day-numbers (org-get-all-dates beg end 'no-ranges
20078                                          t doclosed ; always include today
20079                                          org-timeline-show-empty-dates))
20080          (org-deadline-warning-days 0)
20081          (org-agenda-only-exact-dates t)
20082          (today (time-to-days (current-time)))
20083          (past t)
20084          args
20085          s e rtn d emptyp)
20086     (setq org-agenda-redo-command
20087           (list 'progn
20088                 (list 'org-switch-to-buffer-other-window (current-buffer))
20089                 (list 'org-timeline (list 'quote include-all))))
20090     (if (not dopast)
20091         ;; Remove past dates from the list of dates.
20092         (setq day-numbers (delq nil (mapcar (lambda(x)
20093                                               (if (>= x today) x nil))
20094                                             day-numbers))))
20095     (org-prepare-agenda (concat "Timeline "
20096                                 (file-name-nondirectory buffer-file-name)))
20097     (if doclosed (push :closed args))
20098     (push :timestamp args)
20099     (push :deadline args)
20100     (push :scheduled args)
20101     (push :sexp args)
20102     (if dotodo (push :todo args))
20103     (while (setq d (pop day-numbers))
20104       (if (and (listp d) (eq (car d) :omitted))
20105           (progn
20106             (setq s (point))
20107             (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20108             (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20109         (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20110         (if (and (>= d today)
20111                  dopast
20112                  past)
20113             (progn
20114               (setq past nil)
20115               (insert (make-string 79 ?-) "\n")))
20116         (setq date (calendar-gregorian-from-absolute d))
20117         (setq s (point))
20118         (setq rtn (and (not emptyp)
20119                        (apply 'org-agenda-get-day-entries entry
20120                               date args)))
20121         (if (or rtn (equal d today) org-timeline-show-empty-dates)
20122             (progn
20123               (insert
20124                (if (stringp org-agenda-format-date)
20125                    (format-time-string org-agenda-format-date
20126                                        (org-time-from-absolute date))
20127                  (funcall org-agenda-format-date date))
20128                "\n")
20129               (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20130               (put-text-property s (1- (point)) 'org-date-line t)
20131               (if (equal d today)
20132                   (put-text-property s (1- (point)) 'org-today t))
20133               (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20134               (put-text-property s (1- (point)) 'day d)))))
20135     (goto-char (point-min))
20136     (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20137                    (point-min)))
20138     (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20139     (org-finalize-agenda)
20140     (setq buffer-read-only t)))
20142 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
20143   "Return a list of all relevant day numbers from BEG to END buffer positions.
20144 If NO-RANGES is non-nil, include only the start and end dates of a range,
20145 not every single day in the range.  If FORCE-TODAY is non-nil, make
20146 sure that TODAY is included in the list.  If INACTIVE is non-nil, also
20147 inactive time stamps (those in square brackets) are included.
20148 When EMPTY is non-nil, also include days without any entries."
20149   (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
20150          dates dates1 date day day1 day2 ts1 ts2)
20151     (if force-today
20152         (setq dates (list (time-to-days (current-time)))))
20153     (save-excursion
20154       (goto-char beg)
20155       (while (re-search-forward re end t)
20156         (setq day (time-to-days (org-time-string-to-time
20157                                  (substring (match-string 1) 0 10))))
20158         (or (memq day dates) (push day dates)))
20159       (unless no-ranges
20160         (goto-char beg)
20161         (while (re-search-forward org-tr-regexp end t)
20162           (setq ts1 (substring (match-string 1) 0 10)
20163                 ts2 (substring (match-string 2) 0 10)
20164                 day1 (time-to-days (org-time-string-to-time ts1))
20165                 day2 (time-to-days (org-time-string-to-time ts2)))
20166           (while (< (setq day1 (1+ day1)) day2)
20167             (or (memq day1 dates) (push day1 dates)))))
20168       (setq dates (sort dates '<))
20169       (when empty
20170         (while (setq day (pop dates))
20171           (setq day2 (car dates))
20172           (push day dates1)
20173           (when (and day2 empty)
20174             (if (or (eq empty t)
20175                     (and (numberp empty) (<= (- day2 day) empty)))
20176                 (while (< (setq day (1+ day)) day2)
20177                   (push (list day) dates1))
20178               (push (cons :omitted (- day2 day)) dates1))))
20179         (setq dates (nreverse dates1)))
20180       dates)))
20182 ;;; Agenda Daily/Weekly
20184 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20185 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20186 (defvar org-agenda-last-arguments nil
20187   "The arguments of the previous call to org-agenda")
20188 (defvar org-starting-day nil) ; local variable in the agenda buffer
20189 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20190 (defvar org-include-all-loc nil) ; local variable
20191 (defvar org-agenda-remove-date nil) ; dynamically scoped
20193 ;;;###autoload
20194 (defun org-agenda-list (&optional include-all start-day ndays)
20195   "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20196 The view will be for the current day or week, but from the overview buffer
20197 you will be able to go to other days/weeks.
20199 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20200 all unfinished TODO items will also be shown, before the agenda.
20201 This feature is considered obsolete, please use the TODO list or a block
20202 agenda instead.
20204 With a numeric prefix argument in an interactive call, the agenda will
20205 span INCLUDE-ALL days.  Lisp programs should instead specify NDAYS to change
20206 the number of days.  NDAYS defaults to `org-agenda-ndays'.
20208 START-DAY defaults to TODAY, or to the most recent match for the weekday
20209 given in `org-agenda-start-on-weekday'."
20210   (interactive "P")
20211   (if (and (integerp include-all) (> include-all 0))
20212       (setq ndays include-all include-all nil))
20213   (setq ndays (or ndays org-agenda-ndays)
20214         start-day (or start-day org-agenda-start-day))
20215   (if org-agenda-overriding-arguments
20216       (setq include-all (car org-agenda-overriding-arguments)
20217             start-day (nth 1 org-agenda-overriding-arguments)
20218             ndays (nth 2 org-agenda-overriding-arguments)))
20219   (if (stringp start-day)
20220       ;; Convert to an absolute day number
20221       (setq start-day (time-to-days (org-read-date nil t start-day))))
20222   (setq org-agenda-last-arguments (list include-all start-day ndays))
20223   (org-compile-prefix-format 'agenda)
20224   (org-set-sorting-strategy 'agenda)
20225   (require 'calendar)
20226   (let* ((org-agenda-start-on-weekday
20227           (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20228               org-agenda-start-on-weekday nil))
20229          (thefiles (org-agenda-files))
20230          (files thefiles)
20231          (today (time-to-days
20232                  (time-subtract (current-time)
20233                                 (list 0 (* 3600 org-extend-today-until) 0))))
20234          (sd (or start-day today))
20235          (start (if (or (null org-agenda-start-on-weekday)
20236                         (< org-agenda-ndays 7))
20237                     sd
20238                   (let* ((nt (calendar-day-of-week
20239                               (calendar-gregorian-from-absolute sd)))
20240                          (n1 org-agenda-start-on-weekday)
20241                          (d (- nt n1)))
20242                     (- sd (+ (if (< d 0) 7 0) d)))))
20243          (day-numbers (list start))
20244          (day-cnt 0)
20245          (inhibit-redisplay (not debug-on-error))
20246          s e rtn rtnall file date d start-pos end-pos todayp nd)
20247     (setq org-agenda-redo-command
20248           (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20249     ;; Make the list of days
20250     (setq ndays (or ndays org-agenda-ndays)
20251           nd ndays)
20252     (while (> ndays 1)
20253       (push (1+ (car day-numbers)) day-numbers)
20254       (setq ndays (1- ndays)))
20255     (setq day-numbers (nreverse day-numbers))
20256     (org-prepare-agenda "Day/Week")
20257     (org-set-local 'org-starting-day (car day-numbers))
20258     (org-set-local 'org-include-all-loc include-all)
20259     (org-set-local 'org-agenda-span
20260                    (org-agenda-ndays-to-span nd))
20261     (when (and (or include-all org-agenda-include-all-todo)
20262                (member today day-numbers))
20263       (setq files thefiles
20264             rtnall nil)
20265       (while (setq file (pop files))
20266         (catch 'nextfile
20267           (org-check-agenda-file file)
20268           (setq date (calendar-gregorian-from-absolute today)
20269                 rtn (org-agenda-get-day-entries
20270                      file date :todo))
20271           (setq rtnall (append rtnall rtn))))
20272       (when rtnall
20273         (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20274         (add-text-properties (point-min) (1- (point))
20275                              (list 'face 'org-agenda-structure))
20276         (insert (org-finalize-agenda-entries rtnall) "\n")))
20277     (unless org-agenda-compact-blocks
20278       (setq s (point))
20279       (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20280               "-agenda:\n")
20281       (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20282                                                 'org-date-line t)))
20283     (while (setq d (pop day-numbers))
20284       (setq date (calendar-gregorian-from-absolute d)
20285             s (point))
20286       (if (or (setq todayp (= d today))
20287               (and (not start-pos) (= d sd)))
20288           (setq start-pos (point))
20289         (if (and start-pos (not end-pos))
20290             (setq end-pos (point))))
20291       (setq files thefiles
20292             rtnall nil)
20293       (while (setq file (pop files))
20294         (catch 'nextfile
20295           (org-check-agenda-file file)
20296           (if org-agenda-show-log
20297               (setq rtn (org-agenda-get-day-entries
20298                          file date
20299                          :deadline :scheduled :timestamp :sexp :closed))
20300             (setq rtn (org-agenda-get-day-entries
20301                        file date
20302                        :deadline :scheduled :sexp :timestamp)))
20303           (setq rtnall (append rtnall rtn))))
20304       (if org-agenda-include-diary
20305           (progn
20306             (require 'diary-lib)
20307             (setq rtn (org-get-entries-from-diary date))
20308             (setq rtnall (append rtnall rtn))))
20309       (if (or rtnall org-agenda-show-all-dates)
20310           (progn
20311             (setq day-cnt (1+ day-cnt))
20312             (insert
20313              (if (stringp org-agenda-format-date)
20314                  (format-time-string org-agenda-format-date
20315                                      (org-time-from-absolute date))
20316                (funcall org-agenda-format-date date))
20317              "\n")
20318             (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20319             (put-text-property s (1- (point)) 'org-date-line t)
20320             (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20321             (if todayp (put-text-property s (1- (point)) 'org-today t))
20322             (if rtnall (insert
20323                         (org-finalize-agenda-entries
20324                          (org-agenda-add-time-grid-maybe
20325                           rtnall nd todayp))
20326                         "\n"))
20327             (put-text-property s (1- (point)) 'day d)
20328             (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20329     (goto-char (point-min))
20330     (org-fit-agenda-window)
20331     (unless (and (pos-visible-in-window-p (point-min))
20332                  (pos-visible-in-window-p (point-max)))
20333       (goto-char (1- (point-max)))
20334       (recenter -1)
20335       (if (not (pos-visible-in-window-p (or start-pos 1)))
20336           (progn
20337             (goto-char (or start-pos 1))
20338             (recenter 1))))
20339     (goto-char (or start-pos 1))
20340     (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20341     (org-finalize-agenda)
20342     (setq buffer-read-only t)
20343     (message "")))
20345 (defun org-agenda-ndays-to-span (n)
20346   (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20348 ;;; Agenda TODO list
20350 (defvar org-select-this-todo-keyword nil)
20351 (defvar org-last-arg nil)
20353 ;;;###autoload
20354 (defun org-todo-list (arg)
20355   "Show all TODO entries from all agenda file in a single list.
20356 The prefix arg can be used to select a specific TODO keyword and limit
20357 the list to these.  When using \\[universal-argument], you will be prompted
20358 for a keyword.  A numeric prefix directly selects the Nth keyword in
20359 `org-todo-keywords-1'."
20360   (interactive "P")
20361   (require 'calendar)
20362   (org-compile-prefix-format 'todo)
20363   (org-set-sorting-strategy 'todo)
20364   (org-prepare-agenda "TODO")
20365   (let* ((today (time-to-days (current-time)))
20366          (date (calendar-gregorian-from-absolute today))
20367          (kwds org-todo-keywords-for-agenda)
20368          (completion-ignore-case t)
20369          (org-select-this-todo-keyword
20370           (if (stringp arg) arg
20371             (and arg (integerp arg) (> arg 0)
20372                  (nth (1- arg) kwds))))
20373          rtn rtnall files file pos)
20374     (when (equal arg '(4))
20375       (setq org-select-this-todo-keyword
20376             (completing-read "Keyword (or KWD1|K2D2|...): "
20377                              (mapcar 'list kwds) nil nil)))
20378     (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
20379     (org-set-local 'org-last-arg arg)
20380     (setq org-agenda-redo-command
20381           '(org-todo-list (or current-prefix-arg org-last-arg)))
20382     (setq files (org-agenda-files)
20383           rtnall nil)
20384     (while (setq file (pop files))
20385       (catch 'nextfile
20386         (org-check-agenda-file file)
20387         (setq rtn (org-agenda-get-day-entries file date :todo))
20388         (setq rtnall (append rtnall rtn))))
20389     (if org-agenda-overriding-header
20390         (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20391                     nil 'face 'org-agenda-structure) "\n")
20392       (insert "Global list of TODO items of type: ")
20393       (add-text-properties (point-min) (1- (point))
20394                            (list 'face 'org-agenda-structure))
20395       (setq pos (point))
20396       (insert (or org-select-this-todo-keyword "ALL") "\n")
20397       (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20398       (setq pos (point))
20399       (unless org-agenda-multi
20400         (insert "Available with `N r': (0)ALL")
20401         (let ((n 0) s)
20402           (mapc (lambda (x)
20403                   (setq s (format "(%d)%s" (setq n (1+ n)) x))
20404                   (if (> (+ (current-column) (string-width s) 1) (frame-width))
20405                       (insert "\n                     "))
20406                   (insert " " s))
20407                 kwds))
20408         (insert "\n"))
20409       (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20410     (when rtnall
20411       (insert (org-finalize-agenda-entries rtnall) "\n"))
20412     (goto-char (point-min))
20413     (org-fit-agenda-window)
20414     (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
20415     (org-finalize-agenda)
20416     (setq buffer-read-only t)))
20418 ;;; Agenda tags match
20420 ;;;###autoload
20421 (defun org-tags-view (&optional todo-only match)
20422   "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
20423 The prefix arg TODO-ONLY limits the search to TODO entries."
20424   (interactive "P")
20425   (org-compile-prefix-format 'tags)
20426   (org-set-sorting-strategy 'tags)
20427   (let* ((org-tags-match-list-sublevels
20428           (if todo-only t org-tags-match-list-sublevels))
20429          (completion-ignore-case t)
20430          rtn rtnall files file pos matcher
20431          buffer)
20432     (setq matcher (org-make-tags-matcher match)
20433           match (car matcher) matcher (cdr matcher))
20434     (org-prepare-agenda (concat "TAGS " match))
20435     (setq org-agenda-redo-command
20436           (list 'org-tags-view (list 'quote todo-only)
20437                 (list 'if 'current-prefix-arg nil match)))
20438     (setq files (org-agenda-files)
20439           rtnall nil)
20440     (while (setq file (pop files))
20441       (catch 'nextfile
20442         (org-check-agenda-file file)
20443         (setq buffer (if (file-exists-p file)
20444                          (org-get-agenda-file-buffer file)
20445                        (error "No such file %s" file)))
20446         (if (not buffer)
20447             ;; If file does not exist, merror message to agenda
20448             (setq rtn (list
20449                        (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20450                   rtnall (append rtnall rtn))
20451           (with-current-buffer buffer
20452             (unless (org-mode-p)
20453               (error "Agenda file %s is not in `org-mode'" file))
20454             (save-excursion
20455               (save-restriction
20456                 (if org-agenda-restrict
20457                     (narrow-to-region org-agenda-restrict-begin
20458                                       org-agenda-restrict-end)
20459                   (widen))
20460                 (setq rtn (org-scan-tags 'agenda matcher todo-only))
20461                 (setq rtnall (append rtnall rtn))))))))
20462     (if org-agenda-overriding-header
20463         (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20464                     nil 'face 'org-agenda-structure) "\n")
20465       (insert "Headlines with TAGS match: ")
20466       (add-text-properties (point-min) (1- (point))
20467                            (list 'face 'org-agenda-structure))
20468       (setq pos (point))
20469       (insert match "\n")
20470       (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20471       (setq pos (point))
20472       (unless org-agenda-multi
20473         (insert "Press `C-u r' to search again with new search string\n"))
20474       (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20475     (when rtnall
20476       (insert (org-finalize-agenda-entries rtnall) "\n"))
20477     (goto-char (point-min))
20478     (org-fit-agenda-window)
20479     (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
20480     (org-finalize-agenda)
20481     (setq buffer-read-only t)))
20483 ;;; Agenda Finding stuck projects
20485 (defvar org-agenda-skip-regexp nil
20486   "Regular expression used in skipping subtrees for the agenda.
20487 This is basically a temporary global variable that can be set and then
20488 used by user-defined selections using `org-agenda-skip-function'.")
20490 (defvar org-agenda-overriding-header nil
20491   "When this is set during todo and tags searches, will replace header.")
20493 (defun org-agenda-skip-subtree-when-regexp-matches ()
20494   "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
20495 If yes, it returns the end position of this tree, causing agenda commands
20496 to skip this subtree.  This is a function that can be put into
20497 `org-agenda-skip-function' for the duration of a command."
20498   (let ((end (save-excursion (org-end-of-subtree t)))
20499         skip)
20500     (save-excursion
20501       (setq skip (re-search-forward org-agenda-skip-regexp end t)))
20502     (and skip end)))
20504 (defun org-agenda-skip-entry-if (&rest conditions)
20505   "Skip entry if any of CONDITIONS is true.
20506 See `org-agenda-skip-if' for details."
20507   (org-agenda-skip-if nil conditions))
20509 (defun org-agenda-skip-subtree-if (&rest conditions)
20510   "Skip entry if any of CONDITIONS is true.
20511 See `org-agenda-skip-if' for details."
20512   (org-agenda-skip-if t conditions))
20514 (defun org-agenda-skip-if (subtree conditions)
20515   "Checks current entity for CONDITIONS.
20516 If SUBTREE is non-nil, the entire subtree is checked.  Otherwise, only
20517 the entry, i.e. the text before the next heading is checked.
20519 CONDITIONS is a list of symbols, boolean OR is used to combine the results
20520 from different tests.  Valid conditions are:
20522 scheduled     Check if there is a scheduled cookie
20523 notscheduled  Check if there is no scheduled cookie
20524 deadline      Check if there is a deadline
20525 notdeadline   Check if there is no deadline
20526 regexp        Check if regexp matches
20527 notregexp     Check if regexp does not match.
20529 The regexp is taken from the conditions list, it must come right after
20530 the `regexp' or `notregexp' element.
20532 If any of these conditions is met, this function returns the end point of
20533 the entity, causing the search to continue from there.  This is a function
20534 that can be put into `org-agenda-skip-function' for the duration of a command."
20535   (let (beg end m)
20536     (org-back-to-heading t)
20537     (setq beg (point)
20538           end (if subtree
20539                   (progn (org-end-of-subtree t) (point))
20540                 (progn (outline-next-heading) (1- (point)))))
20541     (goto-char beg)
20542     (and
20543      (or
20544       (and (memq 'scheduled conditions)
20545            (re-search-forward org-scheduled-time-regexp end t))
20546       (and (memq 'notscheduled conditions)
20547            (not (re-search-forward org-scheduled-time-regexp end t)))
20548       (and (memq 'deadline conditions)
20549            (re-search-forward org-deadline-time-regexp end t))
20550       (and (memq 'notdeadline conditions)
20551            (not (re-search-forward org-deadline-time-regexp end t)))
20552       (and (setq m (memq 'regexp conditions))
20553            (stringp (nth 1 m))
20554            (re-search-forward (nth 1 m) end t))
20555       (and (setq m (memq 'notregexp conditions))
20556            (stringp (nth 1 m))
20557            (not (re-search-forward (nth 1 m) end t))))
20558      end)))
20560 ;;;###autoload
20561 (defun org-agenda-list-stuck-projects (&rest ignore)
20562   "Create agenda view for projects that are stuck.
20563 Stuck projects are project that have no next actions.  For the definitions
20564 of what a project is and how to check if it stuck, customize the variable
20565 `org-stuck-projects'.
20566 MATCH is being ignored."
20567   (interactive)
20568   (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
20569          ;; FIXME: we could have used org-agenda-skip-if here.
20570          (org-agenda-overriding-header "List of stuck projects: ")
20571          (matcher (nth 0 org-stuck-projects))
20572          (todo (nth 1 org-stuck-projects))
20573          (todo-wds (if (member "*" todo)
20574                        (progn
20575                          (org-prepare-agenda-buffers (org-agenda-files))
20576                          (org-delete-all
20577                           org-done-keywords-for-agenda
20578                           (copy-sequence org-todo-keywords-for-agenda)))
20579                      todo))
20580          (todo-re (concat "^\\*+[ \t]+\\("
20581                           (mapconcat 'identity todo-wds "\\|")
20582                           "\\)\\>"))
20583          (tags (nth 2 org-stuck-projects))
20584          (tags-re (if (member "*" tags)
20585                       (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
20586                     (concat "^\\*+ .*:\\("
20587                             (mapconcat 'identity tags "\\|")
20588                             (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
20589          (gen-re (nth 3 org-stuck-projects))
20590          (re-list
20591           (delq nil
20592                 (list
20593                  (if todo todo-re)
20594                  (if tags tags-re)
20595                  (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
20596                       gen-re)))))
20597     (setq org-agenda-skip-regexp
20598           (if re-list
20599               (mapconcat 'identity re-list "\\|")
20600             (error "No information how to identify unstuck projects")))
20601     (org-tags-view nil matcher)
20602     (with-current-buffer org-agenda-buffer-name
20603       (setq org-agenda-redo-command
20604             '(org-agenda-list-stuck-projects
20605               (or current-prefix-arg org-last-arg))))))
20607 ;;; Diary integration
20609 (defvar org-disable-agenda-to-diary nil)          ;Dynamically-scoped param.
20611 (defun org-get-entries-from-diary (date)
20612   "Get the (Emacs Calendar) diary entries for DATE."
20613   (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
20614          (diary-display-hook '(fancy-diary-display))
20615          (pop-up-frames nil)
20616          (list-diary-entries-hook
20617           (cons 'org-diary-default-entry list-diary-entries-hook))
20618          (diary-file-name-prefix-function nil) ; turn this feature off
20619          (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
20620          entries
20621          (org-disable-agenda-to-diary t))
20622     (save-excursion
20623       (save-window-excursion
20624         (funcall (if (fboundp 'diary-list-entries)
20625                      'diary-list-entries 'list-diary-entries)
20626                  date 1)))
20627     (if (not (get-buffer fancy-diary-buffer))
20628         (setq entries nil)
20629       (with-current-buffer fancy-diary-buffer
20630         (setq buffer-read-only nil)
20631         (if (zerop (buffer-size))
20632             ;; No entries
20633             (setq entries nil)
20634           ;; Omit the date and other unnecessary stuff
20635           (org-agenda-cleanup-fancy-diary)
20636           ;; Add prefix to each line and extend the text properties
20637           (if (zerop (buffer-size))
20638               (setq entries nil)
20639             (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
20640         (set-buffer-modified-p nil)
20641         (kill-buffer fancy-diary-buffer)))
20642     (when entries
20643       (setq entries (org-split-string entries "\n"))
20644       (setq entries
20645             (mapcar
20646              (lambda (x)
20647                (setq x (org-format-agenda-item "" x "Diary" nil 'time))
20648                ;; Extend the text properties to the beginning of the line
20649                (org-add-props x (text-properties-at (1- (length x)) x)
20650                  'type "diary" 'date date))
20651              entries)))))
20653 (defun org-agenda-cleanup-fancy-diary ()
20654   "Remove unwanted stuff in buffer created by `fancy-diary-display'.
20655 This gets rid of the date, the underline under the date, and
20656 the dummy entry installed by `org-mode' to ensure non-empty diary for each
20657 date.  It also removes lines that contain only whitespace."
20658   (goto-char (point-min))
20659   (if (looking-at ".*?:[ \t]*")
20660       (progn
20661         (replace-match "")
20662         (re-search-forward "\n=+$" nil t)
20663         (replace-match "")
20664         (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
20665     (re-search-forward "\n=+$" nil t)
20666     (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
20667   (goto-char (point-min))
20668   (while (re-search-forward "^ +\n" nil t)
20669     (replace-match ""))
20670   (goto-char (point-min))
20671   (if (re-search-forward "^Org-mode dummy\n?" nil t)
20672       (replace-match "")))
20674 ;; Make sure entries from the diary have the right text properties.
20675 (eval-after-load "diary-lib"
20676   '(if (boundp 'diary-modify-entry-list-string-function)
20677        ;; We can rely on the hook, nothing to do
20678        nil
20679      ;; Hook not avaiable, must use advice to make this work
20680      (defadvice add-to-diary-list (before org-mark-diary-entry activate)
20681        "Make the position visible."
20682        (if (and org-disable-agenda-to-diary  ;; called from org-agenda
20683                 (stringp string)
20684                 buffer-file-name)
20685            (setq string (org-modify-diary-entry-string string))))))
20687 (defun org-modify-diary-entry-string (string)
20688   "Add text properties to string, allowing org-mode to act on it."
20689   (org-add-props string nil
20690     'mouse-face 'highlight
20691     'keymap org-agenda-keymap
20692     'help-echo (if buffer-file-name
20693                    (format "mouse-2 or RET jump to diary file %s"
20694                            (abbreviate-file-name buffer-file-name))
20695                  "")
20696     'org-agenda-diary-link t
20697     'org-marker (org-agenda-new-marker (point-at-bol))))
20699 (defun org-diary-default-entry ()
20700   "Add a dummy entry to the diary.
20701 Needed to avoid empty dates which mess up holiday display."
20702   ;; Catch the error if dealing with the new add-to-diary-alist
20703   (when org-disable-agenda-to-diary
20704     (condition-case nil
20705         (add-to-diary-list original-date "Org-mode dummy" "")
20706       (error
20707        (add-to-diary-list original-date  "Org-mode dummy" "" nil)))))
20709 ;;;###autoload
20710 (defun org-diary (&rest args)
20711   "Return diary information from org-files.
20712 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
20713 It accesses org files and extracts information from those files to be
20714 listed in the diary.  The function accepts arguments specifying what
20715 items should be listed.  The following arguments are allowed:
20717    :timestamp    List the headlines of items containing a date stamp or
20718                  date range matching the selected date.  Deadlines will
20719                  also be listed, on the expiration day.
20721    :sexp         List entries resulting from diary-like sexps.
20723    :deadline     List any deadlines past due, or due within
20724                  `org-deadline-warning-days'.  The listing occurs only
20725                  in the diary for *today*, not at any other date.  If
20726                  an entry is marked DONE, it is no longer listed.
20728    :scheduled    List all items which are scheduled for the given date.
20729                  The diary for *today* also contains items which were
20730                  scheduled earlier and are not yet marked DONE.
20732    :todo         List all TODO items from the org-file.  This may be a
20733                  long list - so this is not turned on by default.
20734                  Like deadlines, these entries only show up in the
20735                  diary for *today*, not at any other date.
20737 The call in the diary file should look like this:
20739    &%%(org-diary) ~/path/to/some/orgfile.org
20741 Use a separate line for each org file to check.  Or, if you omit the file name,
20742 all files listed in `org-agenda-files' will be checked automatically:
20744    &%%(org-diary)
20746 If you don't give any arguments (as in the example above), the default
20747 arguments (:deadline :scheduled :timestamp :sexp) are used.
20748 So the example above may also be written as
20750    &%%(org-diary :deadline :timestamp :sexp :scheduled)
20752 The function expects the lisp variables `entry' and `date' to be provided
20753 by the caller, because this is how the calendar works.  Don't use this
20754 function from a program - use `org-agenda-get-day-entries' instead."
20755   (org-agenda-maybe-reset-markers)
20756   (org-compile-prefix-format 'agenda)
20757   (org-set-sorting-strategy 'agenda)
20758   (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
20759   (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
20760                     (list entry)
20761                   (org-agenda-files t)))
20762          file rtn results)
20763     (org-prepare-agenda-buffers files)
20764     ;; If this is called during org-agenda, don't return any entries to
20765     ;; the calendar.  Org Agenda will list these entries itself.
20766     (if org-disable-agenda-to-diary (setq files nil))
20767     (while (setq file (pop files))
20768       (setq rtn (apply 'org-agenda-get-day-entries file date args))
20769       (setq results (append results rtn)))
20770     (if results
20771         (concat (org-finalize-agenda-entries results) "\n"))))
20773 ;;; Agenda entry finders
20775 (defun org-agenda-get-day-entries (file date &rest args)
20776   "Does the work for `org-diary' and `org-agenda'.
20777 FILE is the path to a file to be checked for entries.  DATE is date like
20778 the one returned by `calendar-current-date'.  ARGS are symbols indicating
20779 which kind of entries should be extracted.  For details about these, see
20780 the documentation of `org-diary'."
20781   (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
20782   (let* ((org-startup-folded nil)
20783          (org-startup-align-all-tables nil)
20784          (buffer (if (file-exists-p file)
20785                      (org-get-agenda-file-buffer file)
20786                    (error "No such file %s" file)))
20787          arg results rtn)
20788     (if (not buffer)
20789         ;; If file does not exist, make sure an error message ends up in diary
20790         (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20791       (with-current-buffer buffer
20792         (unless (org-mode-p)
20793           (error "Agenda file %s is not in `org-mode'" file))
20794         (let ((case-fold-search nil))
20795           (save-excursion
20796             (save-restriction
20797               (if org-agenda-restrict
20798                   (narrow-to-region org-agenda-restrict-begin
20799                                     org-agenda-restrict-end)
20800                 (widen))
20801               ;; The way we repeatedly append to `results' makes it O(n^2) :-(
20802               (while (setq arg (pop args))
20803                 (cond
20804                  ((and (eq arg :todo)
20805                        (equal date (calendar-current-date)))
20806                   (setq rtn (org-agenda-get-todos))
20807                   (setq results (append results rtn)))
20808                  ((eq arg :timestamp)
20809                   (setq rtn (org-agenda-get-blocks))
20810                   (setq results (append results rtn))
20811                   (setq rtn (org-agenda-get-timestamps))
20812                   (setq results (append results rtn)))
20813                  ((eq arg :sexp)
20814                   (setq rtn (org-agenda-get-sexps))
20815                   (setq results (append results rtn)))
20816                  ((eq arg :scheduled)
20817                   (setq rtn (org-agenda-get-scheduled))
20818                   (setq results (append results rtn)))
20819                  ((eq arg :closed)
20820                   (setq rtn (org-agenda-get-closed))
20821                   (setq results (append results rtn)))
20822                  ((eq arg :deadline)
20823                   (setq rtn (org-agenda-get-deadlines))
20824                   (setq results (append results rtn))))))))
20825         results))))
20827 (defun org-entry-is-todo-p ()
20828   (member (org-get-todo-state) org-not-done-keywords))
20830 (defun org-entry-is-done-p ()
20831   (member (org-get-todo-state) org-done-keywords))
20833 (defun org-get-todo-state ()
20834   (save-excursion
20835     (org-back-to-heading t)
20836     (and (looking-at org-todo-line-regexp)
20837          (match-end 2)
20838          (match-string 2))))
20840 (defun org-at-date-range-p (&optional inactive-ok)
20841   "Is the cursor inside a date range?"
20842   (interactive)
20843   (save-excursion
20844     (catch 'exit
20845       (let ((pos (point)))
20846         (skip-chars-backward "^[<\r\n")
20847         (skip-chars-backward "<[")
20848         (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
20849              (>= (match-end 0) pos)
20850              (throw 'exit t))
20851         (skip-chars-backward "^<[\r\n")
20852         (skip-chars-backward "<[")
20853         (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
20854              (>= (match-end 0) pos)
20855              (throw 'exit t)))
20856       nil)))
20858 (defun org-agenda-get-todos ()
20859   "Return the TODO information for agenda display."
20860   (let* ((props (list 'face nil
20861                       'done-face 'org-done
20862                       'org-not-done-regexp org-not-done-regexp
20863                       'org-todo-regexp org-todo-regexp
20864                       'mouse-face 'highlight
20865                       'keymap org-agenda-keymap
20866                       'help-echo
20867                       (format "mouse-2 or RET jump to org file %s"
20868                               (abbreviate-file-name buffer-file-name))))
20869          ;; FIXME: get rid of the \n at some point  but watch out
20870          (regexp (concat "^\\*+[ \t]+\\("
20871                          (if org-select-this-todo-keyword
20872                              (if (equal org-select-this-todo-keyword "*")
20873                                  org-todo-regexp
20874                                (concat "\\<\\("
20875                                        (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
20876                                      "\\)\\>"))
20877                            org-not-done-regexp)
20878                          "[^\n\r]*\\)"))
20879          marker priority category tags
20880          ee txt beg end)
20881     (goto-char (point-min))
20882     (while (re-search-forward regexp nil t)
20883       (catch :skip
20884         (save-match-data
20885           (beginning-of-line)
20886           (setq beg (point) end (progn (outline-next-heading) (point)))
20887           (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
20888                          (re-search-forward org-ts-regexp end t))
20889                     (and org-agenda-todo-ignore-scheduled (goto-char beg)
20890                          (re-search-forward org-scheduled-time-regexp end t))
20891                     (and org-agenda-todo-ignore-deadlines (goto-char beg)
20892                          (re-search-forward org-deadline-time-regexp end t)
20893                          (org-deadline-close (match-string 1))))
20894             (goto-char (1+ beg))
20895             (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
20896             (throw :skip nil)))
20897         (goto-char beg)
20898         (org-agenda-skip)
20899         (goto-char (match-beginning 1))
20900         (setq marker (org-agenda-new-marker (match-beginning 0))
20901               category (org-get-category)
20902               tags (org-get-tags-at (point))
20903               txt (org-format-agenda-item "" (match-string 1) category tags)
20904               priority (1+ (org-get-priority txt)))
20905         (org-add-props txt props
20906           'org-marker marker 'org-hd-marker marker
20907           'priority priority 'org-category category
20908           'type "todo")
20909         (push txt ee)
20910         (if org-agenda-todo-list-sublevels
20911             (goto-char (match-end 1))
20912           (org-end-of-subtree 'invisible))))
20913     (nreverse ee)))
20915 (defconst org-agenda-no-heading-message
20916   "No heading for this item in buffer or region.")
20918 (defun org-agenda-get-timestamps ()
20919   "Return the date stamp information for agenda display."
20920   (let* ((props (list 'face nil
20921                       'org-not-done-regexp org-not-done-regexp
20922                       'org-todo-regexp org-todo-regexp
20923                       'mouse-face 'highlight
20924                       'keymap org-agenda-keymap
20925                       'help-echo
20926                       (format "mouse-2 or RET jump to org file %s"
20927                               (abbreviate-file-name buffer-file-name))))
20928          (d1 (calendar-absolute-from-gregorian date))
20929          (remove-re
20930           (concat
20931            (regexp-quote
20932             (format-time-string
20933              "<%Y-%m-%d"
20934              (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20935            ".*?>"))
20936          (regexp
20937           (concat
20938            (regexp-quote
20939             (substring
20940              (format-time-string
20941               (car org-time-stamp-formats)
20942               (apply 'encode-time  ; DATE bound by calendar
20943                      (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
20944              0 11))
20945            "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
20946            "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
20947          marker hdmarker deadlinep scheduledp donep tmp priority category
20948          ee txt timestr tags b0 b3 e3 head)
20949     (goto-char (point-min))
20950     (while (re-search-forward regexp nil t)
20951       (setq b0 (match-beginning 0)
20952             b3 (match-beginning 3) e3 (match-end 3))
20953       (catch :skip
20954         (and (org-at-date-range-p) (throw :skip nil))
20955         (org-agenda-skip)
20956         (if (and (match-end 1)
20957                  (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
20958             (throw :skip nil))
20959         (if (and e3
20960                  (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
20961             (throw :skip nil))
20962         (setq marker (org-agenda-new-marker b0)
20963               category (org-get-category b0)
20964               tmp (buffer-substring (max (point-min)
20965                                          (- b0 org-ds-keyword-length))
20966                                     b0)
20967               timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
20968               deadlinep (string-match org-deadline-regexp tmp)
20969               scheduledp (string-match org-scheduled-regexp tmp)
20970               donep (org-entry-is-done-p))
20971         (if (or scheduledp deadlinep) (throw :skip t))
20972         (if (string-match ">" timestr)
20973             ;; substring should only run to end of time stamp
20974             (setq timestr (substring timestr 0 (match-end 0))))
20975         (save-excursion
20976           (if (re-search-backward "^\\*+ " nil t)
20977               (progn
20978                 (goto-char (match-beginning 0))
20979                 (setq hdmarker (org-agenda-new-marker)
20980                       tags (org-get-tags-at))
20981                 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20982                 (setq head (match-string 1))
20983                 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
20984                 (setq txt (org-format-agenda-item
20985                            nil head category tags timestr nil
20986                            remove-re)))
20987             (setq txt org-agenda-no-heading-message))
20988           (setq priority (org-get-priority txt))
20989           (org-add-props txt props
20990             'org-marker marker 'org-hd-marker hdmarker)
20991           (org-add-props txt nil 'priority priority
20992                          'org-category category 'date date
20993                          'type "timestamp")
20994           (push txt ee))
20995         (outline-next-heading)))
20996     (nreverse ee)))
20998 (defun org-agenda-get-sexps ()
20999   "Return the sexp information for agenda display."
21000   (require 'diary-lib)
21001   (let* ((props (list 'face nil
21002                       'mouse-face 'highlight
21003                       'keymap org-agenda-keymap
21004                       'help-echo
21005                       (format "mouse-2 or RET jump to org file %s"
21006                               (abbreviate-file-name buffer-file-name))))
21007          (regexp "^&?%%(")
21008          marker category ee txt tags entry result beg b sexp sexp-entry)
21009     (goto-char (point-min))
21010     (while (re-search-forward regexp nil t)
21011       (catch :skip
21012         (org-agenda-skip)
21013         (setq beg (match-beginning 0))
21014         (goto-char (1- (match-end 0)))
21015         (setq b (point))
21016         (forward-sexp 1)
21017         (setq sexp (buffer-substring b (point)))
21018         (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21019                              (org-trim (match-string 1))
21020                            ""))
21021         (setq result (org-diary-sexp-entry sexp sexp-entry date))
21022         (when result
21023           (setq marker (org-agenda-new-marker beg)
21024                 category (org-get-category beg))
21026           (if (string-match "\\S-" result)
21027               (setq txt result)
21028             (setq txt "SEXP entry returned empty string"))
21030           (setq txt (org-format-agenda-item
21031                      "" txt category tags 'time))
21032           (org-add-props txt props 'org-marker marker)
21033           (org-add-props txt nil
21034             'org-category category 'date date
21035             'type "sexp")
21036           (push txt ee))))
21037     (nreverse ee)))
21039 (defun org-agenda-get-closed ()
21040   "Return the logged TODO entries for agenda display."
21041   (let* ((props (list 'mouse-face 'highlight
21042                       'org-not-done-regexp org-not-done-regexp
21043                       'org-todo-regexp org-todo-regexp
21044                       'keymap org-agenda-keymap
21045                       'help-echo
21046                       (format "mouse-2 or RET jump to org file %s"
21047                               (abbreviate-file-name buffer-file-name))))
21048          (regexp (concat
21049                   "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21050                   (regexp-quote
21051                    (substring
21052                     (format-time-string
21053                      (car org-time-stamp-formats)
21054                      (apply 'encode-time  ; DATE bound by calendar
21055                             (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21056                     1 11))))
21057          marker hdmarker priority category tags closedp
21058          ee txt timestr)
21059     (goto-char (point-min))
21060     (while (re-search-forward regexp nil t)
21061       (catch :skip
21062         (org-agenda-skip)
21063         (setq marker (org-agenda-new-marker (match-beginning 0))
21064               closedp (equal (match-string 1) org-closed-string)
21065               category (org-get-category (match-beginning 0))
21066               timestr (buffer-substring (match-beginning 0) (point-at-eol))
21067               ;; donep (org-entry-is-done-p)
21068               )
21069         (if (string-match "\\]" timestr)
21070             ;; substring should only run to end of time stamp
21071             (setq timestr (substring timestr 0 (match-end 0))))
21072         (save-excursion
21073           (if (re-search-backward "^\\*+ " nil t)
21074               (progn
21075                 (goto-char (match-beginning 0))
21076                 (setq hdmarker (org-agenda-new-marker)
21077                       tags (org-get-tags-at))
21078                 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21079                 (setq txt (org-format-agenda-item
21080                            (if closedp "Closed:    " "Clocked:   ")
21081                            (match-string 1) category tags timestr)))
21082             (setq txt org-agenda-no-heading-message))
21083           (setq priority 100000)
21084           (org-add-props txt props
21085             'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21086             'priority priority 'org-category category
21087             'type "closed" 'date date
21088             'undone-face 'org-warning 'done-face 'org-done)
21089           (push txt ee))
21090         (outline-next-heading)))
21091     (nreverse ee)))
21093 (defun org-agenda-get-deadlines ()
21094   "Return the deadline information for agenda display."
21095   (let* ((props (list 'mouse-face 'highlight
21096                       'org-not-done-regexp org-not-done-regexp
21097                       'org-todo-regexp org-todo-regexp
21098                       'keymap org-agenda-keymap
21099                       'help-echo
21100                       (format "mouse-2 or RET jump to org file %s"
21101                               (abbreviate-file-name buffer-file-name))))
21102          (regexp org-deadline-time-regexp)
21103          (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21104          (d1 (calendar-absolute-from-gregorian date))  ; DATE bound by calendar
21105          d2 diff dfrac wdays pos pos1 category tags
21106          ee txt head face s upcomingp donep timestr)
21107     (goto-char (point-min))
21108     (while (re-search-forward regexp nil t)
21109       (catch :skip
21110         (org-agenda-skip)
21111         (setq s (match-string 1)
21112               pos (1- (match-beginning 1))
21113               d2 (org-time-string-to-absolute (match-string 1) d1)
21114               diff (- d2 d1)
21115               wdays (org-get-wdays s)
21116               dfrac (/ (* 1.0 (- wdays diff)) wdays)
21117               upcomingp (and todayp (> diff 0)))
21118         ;; When to show a deadline in the calendar:
21119         ;; If the expiration is within wdays warning time.
21120         ;; Past-due deadlines are only shown on the current date
21121         (if (or (and (<= diff wdays)
21122                      (and todayp (not org-agenda-only-exact-dates)))
21123                 (= diff 0))
21124             (save-excursion
21125               (setq category (org-get-category))
21126               (if (re-search-backward "^\\*+[ \t]+" nil t)
21127                   (progn
21128                     (goto-char (match-end 0))
21129                     (setq pos1 (match-beginning 0))
21130                     (setq tags (org-get-tags-at pos1))
21131                     (setq head (buffer-substring-no-properties
21132                                 (point)
21133                                 (progn (skip-chars-forward "^\r\n")
21134                                        (point))))
21135                     (setq donep (string-match org-looking-at-done-regexp head))
21136                     (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21137                         (setq timestr
21138                               (concat (substring s (match-beginning 1)) " "))
21139                       (setq timestr 'time))
21140                     (if (and donep
21141                              (or org-agenda-skip-deadline-if-done
21142                                  (not (= diff 0))))
21143                         (setq txt nil)
21144                       (setq txt (org-format-agenda-item
21145                                  (if (= diff 0)
21146                                      (car org-agenda-deadline-leaders)
21147                                    (format (nth 1 org-agenda-deadline-leaders)
21148                                            diff))
21149                                  head category tags timestr))))
21150                 (setq txt org-agenda-no-heading-message))
21151               (when txt
21152                 (setq face (org-agenda-deadline-face dfrac))
21153                 (org-add-props txt props
21154                   'org-marker (org-agenda-new-marker pos)
21155                   'org-hd-marker (org-agenda-new-marker pos1)
21156                   'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
21157                                (org-get-priority txt))
21158                   'org-category category
21159                   'type (if upcomingp "upcoming-deadline" "deadline")
21160                   'date (if upcomingp date d2)
21161                   'face (if donep 'org-done face)
21162                   'undone-face face 'done-face 'org-done)
21163                 (push txt ee))))))
21164     (nreverse ee)))
21166 (defun org-agenda-deadline-face (fraction)
21167   "Return the face to displaying a deadline item.
21168 FRACTION is what fraction of the head-warning time has passed."
21169   (let ((faces org-agenda-deadline-faces) f)
21170     (catch 'exit
21171       (while (setq f (pop faces))
21172         (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21174 (defun org-agenda-get-scheduled ()
21175   "Return the scheduled information for agenda display."
21176   (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21177                       'org-todo-regexp org-todo-regexp
21178                       'done-face 'org-done
21179                       'mouse-face 'highlight
21180                       'keymap org-agenda-keymap
21181                       'help-echo
21182                       (format "mouse-2 or RET jump to org file %s"
21183                               (abbreviate-file-name buffer-file-name))))
21184          (regexp org-scheduled-time-regexp)
21185          (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21186          (d1 (calendar-absolute-from-gregorian date))  ; DATE bound by calendar
21187          d2 diff pos pos1 category tags
21188          ee txt head pastschedp donep face timestr s)
21189     (goto-char (point-min))
21190     (while (re-search-forward regexp nil t)
21191       (catch :skip
21192         (org-agenda-skip)
21193         (setq s (match-string 1)
21194               pos (1- (match-beginning 1))
21195               d2 (org-time-string-to-absolute (match-string 1) d1)
21196               diff (- d2 d1))
21197         (setq pastschedp (and todayp (< diff 0)))
21198         ;; When to show a scheduled item in the calendar:
21199         ;; If it is on or past the date.
21200         (if (or (and (< diff 0)
21201                      (and todayp (not org-agenda-only-exact-dates)))
21202                 (= diff 0))
21203             (save-excursion
21204               (setq category (org-get-category))
21205               (if (re-search-backward "^\\*+[ \t]+" nil t)
21206                   (progn
21207                     (goto-char (match-end 0))
21208                     (setq pos1 (match-beginning 0))
21209                     (setq tags (org-get-tags-at))
21210                     (setq head (buffer-substring-no-properties
21211                                 (point)
21212                                 (progn (skip-chars-forward "^\r\n") (point))))
21213                     (setq donep (string-match org-looking-at-done-regexp head))
21214                     (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21215                         (setq timestr
21216                               (concat (substring s (match-beginning 1)) " "))
21217                       (setq timestr 'time))
21218                     (if (and donep
21219                              (or org-agenda-skip-scheduled-if-done
21220                                  (not (= diff 0))))
21221                         (setq txt nil)
21222                       (setq txt (org-format-agenda-item
21223                                  (if (= diff 0)
21224                                      (car org-agenda-scheduled-leaders)
21225                                    (format (nth 1 org-agenda-scheduled-leaders)
21226                                            (- 1 diff)))
21227                                  head category tags timestr))))
21228                 (setq txt org-agenda-no-heading-message))
21229               (when txt
21230                 (setq face (if pastschedp
21231                                'org-scheduled-previously
21232                              'org-scheduled-today))
21233                 (org-add-props txt props
21234                   'undone-face face
21235                   'face (if donep 'org-done face)
21236                   'org-marker (org-agenda-new-marker pos)
21237                   'org-hd-marker (org-agenda-new-marker pos1)
21238                   'type (if pastschedp "past-scheduled" "scheduled")
21239                   'date (if pastschedp d2 date)
21240                   'priority (+ 94 (- 5 diff) (org-get-priority txt))
21241                   'org-category category)
21242                 (push txt ee))))))
21243     (nreverse ee)))
21245 (defun org-agenda-get-blocks ()
21246   "Return the date-range information for agenda display."
21247   (let* ((props (list 'face nil
21248                       'org-not-done-regexp org-not-done-regexp
21249                       'org-todo-regexp org-todo-regexp
21250                       'mouse-face 'highlight
21251                       'keymap org-agenda-keymap
21252                       'help-echo
21253                       (format "mouse-2 or RET jump to org file %s"
21254                               (abbreviate-file-name buffer-file-name))))
21255          (regexp org-tr-regexp)
21256          (d0 (calendar-absolute-from-gregorian date))
21257          marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21258          donep head)
21259     (goto-char (point-min))
21260     (while (re-search-forward regexp nil t)
21261       (catch :skip
21262         (org-agenda-skip)
21263         (setq pos (point))
21264         (setq timestr (match-string 0)
21265               s1 (match-string 1)
21266               s2 (match-string 2)
21267               d1 (time-to-days (org-time-string-to-time s1))
21268               d2 (time-to-days (org-time-string-to-time s2)))
21269         (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21270             ;; Only allow days between the limits, because the normal
21271             ;; date stamps will catch the limits.
21272             (save-excursion
21273               (setq marker (org-agenda-new-marker (point)))
21274               (setq category (org-get-category))
21275               (if (re-search-backward "^\\*+ " nil t)
21276                   (progn
21277                     (goto-char (match-beginning 0))
21278                     (setq hdmarker (org-agenda-new-marker (point)))
21279                     (setq tags (org-get-tags-at))
21280                     (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21281                     (setq head (match-string 1))
21282                     (and org-agenda-skip-timestamp-if-done
21283                          (org-entry-is-done-p)
21284                          (throw :skip t))
21285                     (setq txt (org-format-agenda-item
21286                                (format (if (= d1 d2) "" "(%d/%d): ")
21287                                        (1+ (- d0 d1)) (1+ (- d2 d1)))
21288                                head category tags
21289                                (if (= d0 d1) timestr))))
21290                 (setq txt org-agenda-no-heading-message))
21291               (org-add-props txt props
21292                 'org-marker marker 'org-hd-marker hdmarker
21293                 'type "block" 'date date
21294                 'priority (org-get-priority txt) 'org-category category)
21295               (push txt ee)))
21296         (goto-char pos)))
21297     ;; Sort the entries by expiration date.
21298     (nreverse ee)))
21300 ;;; Agenda presentation and sorting
21302 (defconst org-plain-time-of-day-regexp
21303   (concat
21304    "\\(\\<[012]?[0-9]"
21305    "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21306    "\\(--?"
21307    "\\(\\<[012]?[0-9]"
21308    "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21309    "\\)?")
21310   "Regular expression to match a plain time or time range.
21311 Examples:  11:45 or 8am-13:15 or 2:45-2:45pm.  After a match, the following
21312 groups carry important information:
21313 0  the full match
21314 1  the first time, range or not
21315 8  the second time, if it is a range.")
21317 (defconst org-plain-time-extension-regexp
21318   (concat
21319    "\\(\\<[012]?[0-9]"
21320    "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21321    "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
21322   "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
21323 Examples:  11:45 or 8am-13:15 or 2:45-2:45pm.  After a match, the following
21324 groups carry important information:
21325 0  the full match
21326 7  hours of duration
21327 9  minutes of duration")
21329 (defconst org-stamp-time-of-day-regexp
21330   (concat
21331    "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
21332    "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
21333    "\\(--?"
21334    "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
21335   "Regular expression to match a timestamp time or time range.
21336 After a match, the following groups carry important information:
21337 0  the full match
21338 1  date plus weekday, for backreferencing to make sure both times on same day
21339 2  the first time, range or not
21340 4  the second time, if it is a range.")
21342 (defvar org-prefix-has-time nil
21343   "A flag, set by `org-compile-prefix-format'.
21344 The flag is set if the currently compiled format contains a `%t'.")
21345 (defvar org-prefix-has-tag nil
21346   "A flag, set by `org-compile-prefix-format'.
21347 The flag is set if the currently compiled format contains a `%T'.")
21349 (defun org-format-agenda-item (extra txt &optional category tags dotime
21350                                      noprefix remove-re)
21351   "Format TXT to be inserted into the agenda buffer.
21352 In particular, it adds the prefix and corresponding text properties.  EXTRA
21353 must be a string and replaces the `%s' specifier in the prefix format.
21354 CATEGORY (string, symbol or nil) may be used to overrule the default
21355 category taken from local variable or file name.  It will replace the `%c'
21356 specifier in the format.  DOTIME, when non-nil, indicates that a
21357 time-of-day should be extracted from TXT for sorting of this entry, and for
21358 the `%t' specifier in the format.  When DOTIME is a string, this string is
21359 searched for a time before TXT is.  NOPREFIX is a flag and indicates that
21360 only the correctly processes TXT should be returned - this is used by
21361 `org-agenda-change-all-lines'.  TAGS can be the tags of the headline.
21362 Any match of REMOVE-RE will be removed from TXT."
21363   (save-match-data
21364     ;; Diary entries sometimes have extra whitespace at the beginning
21365     (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
21366     (let* ((category (or category
21367                          org-category
21368                          (if buffer-file-name
21369                              (file-name-sans-extension
21370                               (file-name-nondirectory buffer-file-name))
21371                            "")))
21372            (tag (if tags (nth (1- (length tags)) tags) ""))
21373            time    ; time and tag are needed for the eval of the prefix format
21374            (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
21375            (time-of-day (and dotime (org-get-time-of-day ts)))
21376            stamp plain s0 s1 s2 rtn srp)
21377       (when (and dotime time-of-day org-prefix-has-time)
21378         ;; Extract starting and ending time and move them to prefix
21379         (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
21380                   (setq plain (string-match org-plain-time-of-day-regexp ts)))
21381           (setq s0 (match-string 0 ts)
21382                 srp (and stamp (match-end 3))
21383                 s1 (match-string (if plain 1 2) ts)
21384                 s2 (match-string (if plain 8 (if srp 4 6)) ts))
21386           ;; If the times are in TXT (not in DOTIMES), and the prefix will list
21387           ;; them, we might want to remove them there to avoid duplication.
21388           ;; The user can turn this off with a variable.
21389           (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
21390                    (string-match (concat (regexp-quote s0) " *") txt)
21391                    (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
21392                    (if (eq org-agenda-remove-times-when-in-prefix 'beg)
21393                        (= (match-beginning 0) 0)
21394                      t))
21395               (setq txt (replace-match "" nil nil txt))))
21396         ;; Normalize the time(s) to 24 hour
21397         (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
21398         (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
21400       (when (and s1 (not s2) org-agenda-default-appointment-duration
21401                  (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
21402         (let ((m (+ (string-to-number (match-string 2 s1))
21403                     (* 60 (string-to-number (match-string 1 s1)))
21404                     org-agenda-default-appointment-duration))
21405               h)
21406           (setq h (/ m 60) m (- m (* h 60)))
21407           (setq s2 (format "%02d:%02d" h m))))
21409       (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21410                           txt)
21411         ;; Tags are in the string
21412         (if (or (eq org-agenda-remove-tags t)
21413                 (and org-agenda-remove-tags
21414                      org-prefix-has-tag))
21415             (setq txt (replace-match "" t t txt))
21416           (setq txt (replace-match
21417                      (concat (make-string (max (- 50 (length txt)) 1) ?\ )
21418                              (match-string 2 txt))
21419                      t t txt))))
21421       (when remove-re
21422         (while (string-match remove-re txt)
21423           (setq txt (replace-match "" t t txt))))
21425       ;; Create the final string
21426       (if noprefix
21427           (setq rtn txt)
21428         ;; Prepare the variables needed in the eval of the compiled format
21429         (setq time (cond (s2 (concat s1 "-" s2))
21430                          (s1 (concat s1 "......"))
21431                          (t ""))
21432               extra (or extra "")
21433               category (if (symbolp category) (symbol-name category) category))
21434         ;; Evaluate the compiled format
21435         (setq rtn (concat (eval org-prefix-format-compiled) txt)))
21437       ;; And finally add the text properties
21438       (org-add-props rtn nil
21439         'org-category (downcase category) 'tags tags
21440         'org-highest-priority org-highest-priority
21441         'org-lowest-priority org-lowest-priority
21442         'prefix-length (- (length rtn) (length txt))
21443         'time-of-day time-of-day
21444         'txt txt
21445         'time time
21446         'extra extra
21447         'dotime dotime))))
21449 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
21450 (defvar org-agenda-sorting-strategy-selected nil)
21452 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
21453   (catch 'exit
21454     (cond ((not org-agenda-use-time-grid) (throw 'exit list))
21455           ((and todayp (member 'today (car org-agenda-time-grid))))
21456           ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
21457           ((member 'weekly (car org-agenda-time-grid)))
21458           (t (throw 'exit list)))
21459     (let* ((have (delq nil (mapcar
21460                             (lambda (x) (get-text-property 1 'time-of-day x))
21461                             list)))
21462            (string (nth 1 org-agenda-time-grid))
21463            (gridtimes (nth 2 org-agenda-time-grid))
21464            (req (car org-agenda-time-grid))
21465            (remove (member 'remove-match req))
21466            new time)
21467       (if (and (member 'require-timed req) (not have))
21468           ;; don't show empty grid
21469           (throw 'exit list))
21470       (while (setq time (pop gridtimes))
21471         (unless (and remove (member time have))
21472           (setq time (int-to-string time))
21473           (push (org-format-agenda-item
21474                  nil string "" nil
21475                  (concat (substring time 0 -2) ":" (substring time -2)))
21476                 new)
21477           (put-text-property
21478            1 (length (car new)) 'face 'org-time-grid (car new))))
21479       (if (member 'time-up org-agenda-sorting-strategy-selected)
21480           (append new list)
21481         (append list new)))))
21483 (defun org-compile-prefix-format (key)
21484   "Compile the prefix format into a Lisp form that can be evaluated.
21485 The resulting form is returned and stored in the variable
21486 `org-prefix-format-compiled'."
21487   (setq org-prefix-has-time nil org-prefix-has-tag nil)
21488   (let ((s (cond
21489             ((stringp org-agenda-prefix-format)
21490              org-agenda-prefix-format)
21491             ((assq key org-agenda-prefix-format)
21492              (cdr (assq key org-agenda-prefix-format)))
21493             (t "  %-12:c%?-12t% s")))
21494         (start 0)
21495         varform vars var e c f opt)
21496     (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
21497                          s start)
21498       (setq var (cdr (assoc (match-string 4 s)
21499                             '(("c" . category) ("t" . time) ("s" . extra)
21500                               ("T" . tag))))
21501             c (or (match-string 3 s) "")
21502             opt (match-beginning 1)
21503             start (1+ (match-beginning 0)))
21504       (if (equal var 'time) (setq org-prefix-has-time t))
21505       (if (equal var 'tag)  (setq org-prefix-has-tag  t))
21506       (setq f (concat "%" (match-string 2 s) "s"))
21507       (if opt
21508           (setq varform
21509                 `(if (equal "" ,var)
21510                      ""
21511                    (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
21512         (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
21513       (setq s (replace-match "%s" t nil s))
21514       (push varform vars))
21515     (setq vars (nreverse vars))
21516     (setq org-prefix-format-compiled `(format ,s ,@vars))))
21518 (defun org-set-sorting-strategy (key)
21519   (if (symbolp (car org-agenda-sorting-strategy))
21520       ;; the old format
21521       (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
21522     (setq org-agenda-sorting-strategy-selected
21523           (or (cdr (assq key org-agenda-sorting-strategy))
21524               (cdr (assq 'agenda org-agenda-sorting-strategy))
21525               '(time-up category-keep priority-down)))))
21527 (defun org-get-time-of-day (s &optional string mod24)
21528   "Check string S for a time of day.
21529 If found, return it as a military time number between 0 and 2400.
21530 If not found, return nil.
21531 The optional STRING argument forces conversion into a 5 character wide string
21532 HH:MM."
21533   (save-match-data
21534     (when
21535         (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
21536             (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
21537      (let* ((h (string-to-number (match-string 1 s)))
21538             (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
21539             (ampm (if (match-end 4) (downcase (match-string 4 s))))
21540             (am-p (equal ampm "am"))
21541             (h1   (cond ((not ampm) h)
21542                         ((= h 12) (if am-p 0 12))
21543                         (t (+ h (if am-p 0 12)))))
21544             (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
21545                     (mod h1 24) h1))
21546             (t0 (+ (* 100 h2) m))
21547             (t1 (concat (if (>= h1 24) "+" " ")
21548                         (if (< t0 100) "0" "")
21549                         (if (< t0 10)  "0" "")
21550                         (int-to-string t0))))
21551        (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
21553 (defun org-finalize-agenda-entries (list &optional nosort)
21554   "Sort and concatenate the agenda items."
21555   (setq list (mapcar 'org-agenda-highlight-todo list))
21556   (if nosort
21557       list
21558     (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
21560 (defun org-agenda-highlight-todo (x)
21561   (let (re pl)
21562     (if (eq x 'line)
21563         (save-excursion
21564           (beginning-of-line 1)
21565           (setq re (get-text-property (point) 'org-todo-regexp))
21566           (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
21567           (and (looking-at (concat "[ \t]*\\.*" re))
21568                (add-text-properties (match-beginning 0) (match-end 0)
21569                                     (list 'face (org-get-todo-face 0)))))
21570       (setq re (concat (get-text-property 0 'org-todo-regexp x))
21571             pl (get-text-property 0 'prefix-length x))
21572       (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
21573            (add-text-properties
21574             (or (match-end 1) (match-end 0)) (match-end 0)
21575             (list 'face (org-get-todo-face (match-string 2 x)))
21576             x))
21577       x)))
21579 (defsubst org-cmp-priority (a b)
21580   "Compare the priorities of string A and B."
21581   (let ((pa (or (get-text-property 1 'priority a) 0))
21582         (pb (or (get-text-property 1 'priority b) 0)))
21583     (cond ((> pa pb) +1)
21584           ((< pa pb) -1)
21585           (t nil))))
21587 (defsubst org-cmp-category (a b)
21588   "Compare the string values of categories of strings A and B."
21589   (let ((ca (or (get-text-property 1 'org-category a) ""))
21590         (cb (or (get-text-property 1 'org-category b) "")))
21591     (cond ((string-lessp ca cb) -1)
21592           ((string-lessp cb ca) +1)
21593           (t nil))))
21595 (defsubst org-cmp-tag (a b)
21596   "Compare the string values of categories of strings A and B."
21597   (let ((ta (car (last (get-text-property 1 'tags a))))
21598         (tb (car (last (get-text-property 1 'tags b)))))
21599     (cond ((not ta) +1)
21600           ((not tb) -1)
21601           ((string-lessp ta tb) -1)
21602           ((string-lessp tb ta) +1)
21603           (t nil))))
21605 (defsubst org-cmp-time (a b)
21606   "Compare the time-of-day values of strings A and B."
21607   (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
21608          (ta (or (get-text-property 1 'time-of-day a) def))
21609          (tb (or (get-text-property 1 'time-of-day b) def)))
21610     (cond ((< ta tb) -1)
21611           ((< tb ta) +1)
21612           (t nil))))
21614 (defun org-entries-lessp (a b)
21615   "Predicate for sorting agenda entries."
21616   ;; The following variables will be used when the form is evaluated.
21617   ;; So even though the compiler complains, keep them.
21618   (let* ((time-up (org-cmp-time a b))
21619          (time-down (if time-up (- time-up) nil))
21620          (priority-up (org-cmp-priority a b))
21621          (priority-down (if priority-up (- priority-up) nil))
21622          (category-up (org-cmp-category a b))
21623          (category-down (if category-up (- category-up) nil))
21624          (category-keep (if category-up +1 nil))
21625          (tag-up (org-cmp-tag a b))
21626          (tag-down (if tag-up (- tag-up) nil)))
21627     (cdr (assoc
21628           (eval (cons 'or org-agenda-sorting-strategy-selected))
21629           '((-1 . t) (1 . nil) (nil . nil))))))
21631 ;;; Agenda restriction lock
21633 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
21634   "Overlay to mark the headline to which arenda commands are restricted.")
21635 (org-overlay-put org-agenda-restriction-lock-overlay
21636                  'face 'org-agenda-restriction-lock)
21637 (org-overlay-put org-agenda-restriction-lock-overlay
21638                  'help-echo "Agendas are currently limited to this subtree.")
21639 (org-detach-overlay org-agenda-restriction-lock-overlay)
21640 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
21641   "Overlay marking the agenda restriction line in speedbar.")
21642 (org-overlay-put org-speedbar-restriction-lock-overlay
21643                  'face 'org-agenda-restriction-lock)
21644 (org-overlay-put org-speedbar-restriction-lock-overlay
21645                  'help-echo "Agendas are currently limited to this item.")
21646 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21648 (defun org-agenda-set-restriction-lock (&optional type)
21649   "Set restriction lock for agenda, to current subtree or file.
21650 Restriction will be the file if TYPE is `file', or if type is the
21651 universal prefix '(4), or if the cursor is before the first headline
21652 in the file.  Otherwise, restriction will be to the current subtree."
21653   (interactive "P")
21654   (and (equal type '(4)) (setq type 'file))
21655   (setq type (cond
21656               (type type)
21657               ((org-at-heading-p) 'subtree)
21658               ((condition-case nil (org-back-to-heading t) (error nil))
21659                'subtree)
21660               (t 'file)))
21661   (if (eq type 'subtree)
21662       (progn
21663         (setq org-agenda-restrict t)
21664         (setq org-agenda-overriding-restriction 'subtree)
21665         (put 'org-agenda-files 'org-restrict
21666              (list (buffer-file-name (buffer-base-buffer))))
21667         (org-back-to-heading t)
21668         (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
21669         (move-marker org-agenda-restrict-begin (point))
21670         (move-marker org-agenda-restrict-end
21671                      (save-excursion (org-end-of-subtree t)))
21672         (message "Locking agenda restriction to subtree"))
21673     (put 'org-agenda-files 'org-restrict
21674          (list (buffer-file-name (buffer-base-buffer))))
21675     (setq org-agenda-restrict nil)
21676     (setq org-agenda-overriding-restriction 'file)
21677     (move-marker org-agenda-restrict-begin nil)
21678     (move-marker org-agenda-restrict-end nil)
21679     (message "Locking agenda restriction to file"))
21680   (setq current-prefix-arg nil)
21681   (org-agenda-maybe-redo))
21683 (defun org-agenda-remove-restriction-lock (&optional noupdate)
21684   "Remove the agenda restriction lock."
21685   (interactive "P")
21686   (org-detach-overlay org-agenda-restriction-lock-overlay)
21687   (org-detach-overlay org-speedbar-restriction-lock-overlay)
21688   (setq org-agenda-overriding-restriction nil)
21689   (setq org-agenda-restrict nil)
21690   (put 'org-agenda-files 'org-restrict nil)
21691   (move-marker org-agenda-restrict-begin nil)
21692   (move-marker org-agenda-restrict-end nil)
21693   (setq current-prefix-arg nil)
21694   (message "Agenda restriction lock removed")
21695   (or noupdate (org-agenda-maybe-redo)))
21697 (defun org-agenda-maybe-redo ()
21698   "If there is any window showing the agenda view, update it."
21699   (let ((w (get-buffer-window org-agenda-buffer-name t))
21700         (w0 (selected-window)))
21701     (when w
21702       (select-window w)
21703       (org-agenda-redo)
21704       (select-window w0)
21705       (if org-agenda-overriding-restriction
21706           (message "Agenda view shifted to new %s restriction"
21707                    org-agenda-overriding-restriction)
21708         (message "Agenda restriction lock removed")))))
21710 ;;; Agenda commands
21712 (defun org-agenda-check-type (error &rest types)
21713   "Check if agenda buffer is of allowed type.
21714 If ERROR is non-nil, throw an error, otherwise just return nil."
21715   (if (memq org-agenda-type types)
21716       t
21717     (if error
21718         (error "Not allowed in %s-type agenda buffers" org-agenda-type)
21719       nil)))
21721 (defun org-agenda-quit ()
21722   "Exit agenda by removing the window or the buffer."
21723   (interactive)
21724   (let ((buf (current-buffer)))
21725     (if (not (one-window-p)) (delete-window))
21726     (kill-buffer buf)
21727     (org-agenda-maybe-reset-markers 'force)
21728     (org-columns-remove-overlays))
21729   ;; Maybe restore the pre-agenda window configuration.
21730   (and org-agenda-restore-windows-after-quit
21731        (not (eq org-agenda-window-setup 'other-frame))
21732        org-pre-agenda-window-conf
21733        (set-window-configuration org-pre-agenda-window-conf)))
21735 (defun org-agenda-exit ()
21736   "Exit agenda by removing the window or the buffer.
21737 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
21738 Org-mode buffers visited directly by the user will not be touched."
21739   (interactive)
21740   (org-release-buffers org-agenda-new-buffers)
21741   (setq org-agenda-new-buffers nil)
21742   (org-agenda-quit))
21744 (defun org-agenda-execute (arg)
21745   "Execute another agenda command, keeping same window.\\<global-map>
21746 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
21747   (interactive "P")
21748   (let ((org-agenda-window-setup 'current-window))
21749     (org-agenda arg)))
21751 (defun org-save-all-org-buffers ()
21752   "Save all Org-mode buffers without user confirmation."
21753   (interactive)
21754   (message "Saving all Org-mode buffers...")
21755   (save-some-buffers t 'org-mode-p)
21756   (message "Saving all Org-mode buffers... done"))
21758 (defun org-agenda-redo ()
21759   "Rebuild Agenda.
21760 When this is the global TODO list, a prefix argument will be interpreted."
21761   (interactive)
21762   (let* ((org-agenda-keep-modes t)
21763          (line (org-current-line))
21764          (window-line (- line (org-current-line (window-start))))
21765          (lprops (get 'org-agenda-redo-command 'org-lprops)))
21766     (message "Rebuilding agenda buffer...")
21767     (org-let lprops '(eval org-agenda-redo-command))
21768     (setq org-agenda-undo-list nil
21769           org-agenda-pending-undo-list nil)
21770     (message "Rebuilding agenda buffer...done")
21771     (goto-line line)
21772     (recenter window-line)))
21774 (defun org-agenda-goto-date (date)
21775   "Jump to DATE in agenda."
21776   (interactive (list (org-read-date)))
21777   (org-agenda-list nil date))
21779 (defun org-agenda-goto-today ()
21780   "Go to today."
21781   (interactive)
21782   (org-agenda-check-type t 'timeline 'agenda)
21783   (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
21784     (cond
21785      (tdpos (goto-char tdpos))
21786      ((eq org-agenda-type 'agenda)
21787       (let* ((sd (time-to-days
21788                   (time-subtract (current-time)
21789                                  (list 0 (* 3600 org-extend-today-until) 0))))
21790              (comp (org-agenda-compute-time-span sd org-agenda-span))
21791              (org-agenda-overriding-arguments org-agenda-last-arguments))
21792         (setf (nth 1 org-agenda-overriding-arguments) (car comp))
21793         (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
21794         (org-agenda-redo)
21795         (org-agenda-find-same-or-today-or-agenda)))
21796      (t (error "Cannot find today")))))
21798 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
21799   (goto-char
21800    (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
21801        (text-property-any (point-min) (point-max) 'org-today t)
21802        (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
21803        (point-min))))
21805 (defun org-agenda-later (arg)
21806   "Go forward in time by thee current span.
21807 With prefix ARG, go forward that many times the current span."
21808   (interactive "p")
21809   (org-agenda-check-type t 'agenda)
21810   (let* ((span org-agenda-span)
21811          (sd org-starting-day)
21812          (greg (calendar-gregorian-from-absolute sd))
21813          (cnt (get-text-property (point) 'org-day-cnt))
21814          greg2 nd)
21815     (cond
21816      ((eq span 'day)
21817       (setq sd (+ arg sd) nd 1))
21818      ((eq span 'week)
21819       (setq sd (+ (* 7 arg) sd) nd 7))
21820      ((eq span 'month)
21821       (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
21822             sd (calendar-absolute-from-gregorian greg2))
21823       (setcar greg2 (1+ (car greg2)))
21824       (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
21825      ((eq span 'year)
21826       (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
21827             sd (calendar-absolute-from-gregorian greg2))
21828       (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
21829       (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
21830     (let ((org-agenda-overriding-arguments
21831            (list (car org-agenda-last-arguments) sd nd t)))
21832       (org-agenda-redo)
21833       (org-agenda-find-same-or-today-or-agenda cnt))))
21835 (defun org-agenda-earlier (arg)
21836   "Go backward in time by the current span.
21837 With prefix ARG, go backward that many times the current span."
21838   (interactive "p")
21839   (org-agenda-later (- arg)))
21841 (defun org-agenda-day-view ()
21842   "Switch to daily view for agenda."
21843   (interactive)
21844   (setq org-agenda-ndays 1)
21845   (org-agenda-change-time-span 'day))
21846 (defun org-agenda-week-view ()
21847   "Switch to daily view for agenda."
21848   (interactive)
21849   (setq org-agenda-ndays 7)
21850   (org-agenda-change-time-span 'week))
21851 (defun org-agenda-month-view ()
21852   "Switch to daily view for agenda."
21853   (interactive)
21854   (org-agenda-change-time-span 'month))
21855 (defun org-agenda-year-view ()
21856   "Switch to daily view for agenda."
21857   (interactive)
21858   (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
21859       (org-agenda-change-time-span 'year)
21860     (error "Abort")))
21862 (defun org-agenda-change-time-span (span)
21863   "Change the agenda view to SPAN.
21864 SPAN may be `day', `week', `month', `year'."
21865   (org-agenda-check-type t 'agenda)
21866   (if (equal org-agenda-span span)
21867       (error "Viewing span is already \"%s\"" span))
21868   (let* ((sd (or (get-text-property (point) 'day)
21869                 org-starting-day))
21870          (computed (org-agenda-compute-time-span sd span))
21871          (org-agenda-overriding-arguments
21872           (list (car org-agenda-last-arguments)
21873                 (car computed) (cdr computed) t)))
21874     (org-agenda-redo)
21875     (org-agenda-find-same-or-today-or-agenda))
21876   (org-agenda-set-mode-name)
21877   (message "Switched to %s view" span))
21879 (defun org-agenda-compute-time-span (sd span)
21880   "Compute starting date and number of days for agenda.
21881 SPAN may be `day', `week', `month', `year'.  The return value
21882 is a cons cell with the starting date and the number of days,
21883 so that the date SD will be in that range."
21884   (let* ((greg (calendar-gregorian-from-absolute sd))
21885          nd)
21886     (cond
21887      ((eq span 'day)
21888       (setq nd 1))
21889      ((eq span 'week)
21890       (let* ((nt (calendar-day-of-week
21891                   (calendar-gregorian-from-absolute sd)))
21892              (d (if org-agenda-start-on-weekday
21893                     (- nt org-agenda-start-on-weekday)
21894                   0)))
21895         (setq sd (- sd (+ (if (< d 0) 7 0) d)))
21896         (setq nd 7)))
21897      ((eq span 'month)
21898       (setq sd (calendar-absolute-from-gregorian
21899                 (list (car greg) 1 (nth 2 greg)))
21900             nd (- (calendar-absolute-from-gregorian
21901                    (list (1+ (car greg)) 1 (nth 2 greg)))
21902                   sd)))
21903      ((eq span 'year)
21904       (setq sd (calendar-absolute-from-gregorian
21905                 (list 1 1 (nth 2 greg)))
21906             nd (- (calendar-absolute-from-gregorian
21907                    (list 1 1 (1+ (nth 2 greg))))
21908                   sd))))
21909     (cons sd nd)))
21911 ;; FIXME: does not work if user makes date format that starts with a blank
21912 (defun org-agenda-next-date-line (&optional arg)
21913   "Jump to the next line indicating a date in agenda buffer."
21914   (interactive "p")
21915   (org-agenda-check-type t 'agenda 'timeline)
21916   (beginning-of-line 1)
21917   (if (looking-at "^\\S-") (forward-char 1))
21918   (if (not (re-search-forward "^\\S-" nil t arg))
21919       (progn
21920         (backward-char 1)
21921         (error "No next date after this line in this buffer")))
21922   (goto-char (match-beginning 0)))
21924 (defun org-agenda-previous-date-line (&optional arg)
21925   "Jump to the previous line indicating a date in agenda buffer."
21926   (interactive "p")
21927   (org-agenda-check-type t 'agenda 'timeline)
21928   (beginning-of-line 1)
21929   (if (not (re-search-backward "^\\S-" nil t arg))
21930       (error "No previous date before this line in this buffer")))
21932 ;; Initialize the highlight
21933 (defvar org-hl (org-make-overlay 1 1))
21934 (org-overlay-put org-hl 'face 'highlight)
21936 (defun org-highlight (begin end &optional buffer)
21937   "Highlight a region with overlay."
21938   (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
21939            org-hl begin end (or buffer (current-buffer))))
21941 (defun org-unhighlight ()
21942   "Detach overlay INDEX."
21943   (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
21945 ;; FIXME this is currently not used.
21946 (defun org-highlight-until-next-command (beg end &optional buffer)
21947   (org-highlight beg end buffer)
21948   (add-hook 'pre-command-hook 'org-unhighlight-once))
21949 (defun org-unhighlight-once ()
21950   (remove-hook 'pre-command-hook 'org-unhighlight-once)
21951   (org-unhighlight))
21953 (defun org-agenda-follow-mode ()
21954   "Toggle follow mode in an agenda buffer."
21955   (interactive)
21956   (setq org-agenda-follow-mode (not org-agenda-follow-mode))
21957   (org-agenda-set-mode-name)
21958   (message "Follow mode is %s"
21959            (if org-agenda-follow-mode "on" "off")))
21961 (defun org-agenda-log-mode ()
21962   "Toggle log mode in an agenda buffer."
21963   (interactive)
21964   (org-agenda-check-type t 'agenda 'timeline)
21965   (setq org-agenda-show-log (not org-agenda-show-log))
21966   (org-agenda-set-mode-name)
21967   (org-agenda-redo)
21968   (message "Log mode is %s"
21969            (if org-agenda-show-log "on" "off")))
21971 (defun org-agenda-toggle-diary ()
21972   "Toggle diary inclusion in an agenda buffer."
21973   (interactive)
21974   (org-agenda-check-type t 'agenda)
21975   (setq org-agenda-include-diary (not org-agenda-include-diary))
21976   (org-agenda-redo)
21977   (org-agenda-set-mode-name)
21978   (message "Diary inclusion turned %s"
21979            (if org-agenda-include-diary "on" "off")))
21981 (defun org-agenda-toggle-time-grid ()
21982   "Toggle time grid in an agenda buffer."
21983   (interactive)
21984   (org-agenda-check-type t 'agenda)
21985   (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
21986   (org-agenda-redo)
21987   (org-agenda-set-mode-name)
21988   (message "Time-grid turned %s"
21989            (if org-agenda-use-time-grid "on" "off")))
21991 (defun org-agenda-set-mode-name ()
21992   "Set the mode name to indicate all the small mode settings."
21993   (setq mode-name
21994         (concat "Org-Agenda"
21995                 (if (equal org-agenda-ndays 1) " Day"    "")
21996                 (if (equal org-agenda-ndays 7) " Week"   "")
21997                 (if org-agenda-follow-mode     " Follow" "")
21998                 (if org-agenda-include-diary   " Diary"  "")
21999                 (if org-agenda-use-time-grid   " Grid"   "")
22000                 (if org-agenda-show-log        " Log"    "")))
22001   (force-mode-line-update))
22003 (defun org-agenda-post-command-hook ()
22004   (and (eolp) (not (bolp)) (backward-char 1))
22005   (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22006   (if (and org-agenda-follow-mode
22007            (get-text-property (point) 'org-marker))
22008       (org-agenda-show)))
22010 (defun org-agenda-show-priority ()
22011   "Show the priority of the current item.
22012 This priority is composed of the main priority given with the [#A] cookies,
22013 and by additional input from the age of a schedules or deadline entry."
22014   (interactive)
22015   (let* ((pri (get-text-property (point-at-bol) 'priority)))
22016     (message "Priority is %d" (if pri pri -1000))))
22018 (defun org-agenda-show-tags ()
22019   "Show the tags applicable to the current item."
22020   (interactive)
22021   (let* ((tags (get-text-property (point-at-bol) 'tags)))
22022     (if tags
22023         (message "Tags are :%s:"
22024                  (org-no-properties (mapconcat 'identity tags ":")))
22025       (message "No tags associated with this line"))))
22027 (defun org-agenda-goto (&optional highlight)
22028   "Go to the Org-mode file which contains the item at point."
22029   (interactive)
22030   (let* ((marker (or (get-text-property (point) 'org-marker)
22031                      (org-agenda-error)))
22032          (buffer (marker-buffer marker))
22033          (pos (marker-position marker)))
22034     (switch-to-buffer-other-window buffer)
22035     (widen)
22036     (goto-char pos)
22037     (when (org-mode-p)
22038       (org-show-context 'agenda)
22039       (save-excursion
22040         (and (outline-next-heading)
22041              (org-flag-heading nil)))) ; show the next heading
22042     (run-hooks 'org-agenda-after-show-hook)
22043     (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22045 (defvar org-agenda-after-show-hook nil
22046   "Normal hook run after an item has been shown from the agenda.
22047 Point is in the buffer where the item originated.")
22049 (defun org-agenda-kill ()
22050   "Kill the entry or subtree belonging to the current agenda entry."
22051   (interactive)
22052   (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22053   (let* ((marker (or (get-text-property (point) 'org-marker)
22054                      (org-agenda-error)))
22055          (buffer (marker-buffer marker))
22056          (pos (marker-position marker))
22057          (type (get-text-property (point) 'type))
22058          dbeg dend (n 0) conf)
22059     (org-with-remote-undo buffer
22060      (with-current-buffer buffer
22061        (save-excursion
22062          (goto-char pos)
22063          (if (and (org-mode-p) (not (member type '("sexp"))))
22064              (setq dbeg (progn (org-back-to-heading t) (point))
22065                    dend (org-end-of-subtree t t))
22066            (setq dbeg (point-at-bol)
22067                  dend (min (point-max) (1+ (point-at-eol)))))
22068          (goto-char dbeg)
22069          (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22070      (setq conf (or (eq t org-agenda-confirm-kill)
22071                     (and (numberp org-agenda-confirm-kill)
22072                          (> n org-agenda-confirm-kill))))
22073      (and conf
22074           (not (y-or-n-p
22075                 (format "Delete entry with %d lines in buffer \"%s\"? "
22076                         n (buffer-name buffer))))
22077           (error "Abort"))
22078      (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22079      (with-current-buffer buffer (delete-region dbeg dend))
22080      (message "Agenda item and source killed"))))
22082 (defun org-agenda-archive ()
22083   "Kill the entry or subtree belonging to the current agenda entry."
22084   (interactive)
22085   (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22086   (let* ((marker (or (get-text-property (point) 'org-marker)
22087                      (org-agenda-error)))
22088          (buffer (marker-buffer marker))
22089          (pos (marker-position marker)))
22090     (org-with-remote-undo buffer
22091       (with-current-buffer buffer
22092         (if (org-mode-p)
22093             (save-excursion
22094               (goto-char pos)
22095               (org-remove-subtree-entries-from-agenda)
22096               (org-back-to-heading t)
22097               (org-archive-subtree))
22098           (error "Archiving works only in Org-mode files"))))))
22100 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22101   "Remove all lines in the agenda that correspond to a given subtree.
22102 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22103 If this information is not given, the function uses the tree at point."
22104   (let ((buf (or buf (current-buffer))) m p)
22105     (save-excursion
22106       (unless (and beg end)
22107         (org-back-to-heading t)
22108         (setq beg (point))
22109         (org-end-of-subtree t)
22110         (setq end (point)))
22111       (set-buffer (get-buffer org-agenda-buffer-name))
22112       (save-excursion
22113         (goto-char (point-max))
22114         (beginning-of-line 1)
22115         (while (not (bobp))
22116           (when (and (setq m (get-text-property (point) 'org-marker))
22117                      (equal buf (marker-buffer m))
22118                      (setq p (marker-position m))
22119                      (>= p beg)
22120                      (<= p end))
22121             (let ((inhibit-read-only t))
22122               (delete-region (point-at-bol) (1+ (point-at-eol)))))
22123           (beginning-of-line 0))))))
22125 (defun org-agenda-open-link ()
22126   "Follow the link in the current line, if any."
22127   (interactive)
22128   (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22129   (save-excursion
22130     (save-restriction
22131       (narrow-to-region (point-at-bol) (point-at-eol))
22132       (org-open-at-point))))
22134 (defun org-agenda-copy-local-variable (var)
22135   "Get a variable from a referenced buffer and install it here."
22136   (let ((m (get-text-property (point) 'org-marker)))
22137     (when (and m (buffer-live-p (marker-buffer m)))
22138       (org-set-local var (with-current-buffer (marker-buffer m)
22139                            (symbol-value var))))))
22141 (defun org-agenda-switch-to (&optional delete-other-windows)
22142   "Go to the Org-mode file which contains the item at point."
22143   (interactive)
22144   (let* ((marker (or (get-text-property (point) 'org-marker)
22145                      (org-agenda-error)))
22146          (buffer (marker-buffer marker))
22147          (pos (marker-position marker)))
22148     (switch-to-buffer buffer)
22149     (and delete-other-windows (delete-other-windows))
22150     (widen)
22151     (goto-char pos)
22152     (when (org-mode-p)
22153       (org-show-context 'agenda)
22154       (save-excursion
22155         (and (outline-next-heading)
22156              (org-flag-heading nil))))))  ; show the next heading
22158 (defun org-agenda-goto-mouse (ev)
22159   "Go to the Org-mode file which contains the item at the mouse click."
22160   (interactive "e")
22161   (mouse-set-point ev)
22162   (org-agenda-goto))
22164 (defun org-agenda-show ()
22165   "Display the Org-mode file which contains the item at point."
22166   (interactive)
22167   (let ((win (selected-window)))
22168     (org-agenda-goto t)
22169     (select-window win)))
22171 (defun org-agenda-recenter (arg)
22172   "Display the Org-mode file which contains the item at point and recenter."
22173   (interactive "P")
22174   (let ((win (selected-window)))
22175     (org-agenda-goto t)
22176     (recenter arg)
22177     (select-window win)))
22179 (defun org-agenda-show-mouse (ev)
22180   "Display the Org-mode file which contains the item at the mouse click."
22181   (interactive "e")
22182   (mouse-set-point ev)
22183   (org-agenda-show))
22185 (defun org-agenda-check-no-diary ()
22186   "Check if the entry is a diary link and abort if yes."
22187   (if (get-text-property (point) 'org-agenda-diary-link)
22188       (org-agenda-error)))
22190 (defun org-agenda-error ()
22191   (error "Command not allowed in this line"))
22193 (defun org-agenda-tree-to-indirect-buffer ()
22194   "Show the subtree corresponding to the current entry in an indirect buffer.
22195 This calls the command `org-tree-to-indirect-buffer' from the original
22196 Org-mode buffer.
22197 With numerical prefix arg ARG, go up to this level and then take that tree.
22198 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22199 dedicated frame)."
22200   (interactive)
22201   (org-agenda-check-no-diary)
22202   (let* ((marker (or (get-text-property (point) 'org-marker)
22203                      (org-agenda-error)))
22204          (buffer (marker-buffer marker))
22205          (pos (marker-position marker)))
22206     (with-current-buffer buffer
22207       (save-excursion
22208         (goto-char pos)
22209         (call-interactively 'org-tree-to-indirect-buffer)))))
22211 (defvar org-last-heading-marker (make-marker)
22212   "Marker pointing to the headline that last changed its TODO state
22213 by a remote command from the agenda.")
22215 (defun org-agenda-todo-nextset ()
22216   "Switch TODO entry to next sequence."
22217   (interactive)
22218   (org-agenda-todo 'nextset))
22220 (defun org-agenda-todo-previousset ()
22221   "Switch TODO entry to previous sequence."
22222   (interactive)
22223   (org-agenda-todo 'previousset))
22225 (defun org-agenda-todo (&optional arg)
22226   "Cycle TODO state of line at point, also in Org-mode file.
22227 This changes the line at point, all other lines in the agenda referring to
22228 the same tree node, and the headline of the tree node in the Org-mode file."
22229   (interactive "P")
22230   (org-agenda-check-no-diary)
22231   (let* ((col (current-column))
22232          (marker (or (get-text-property (point) 'org-marker)
22233                      (org-agenda-error)))
22234          (buffer (marker-buffer marker))
22235          (pos (marker-position marker))
22236          (hdmarker (get-text-property (point) 'org-hd-marker))
22237          (inhibit-read-only t)
22238          newhead)
22239     (org-with-remote-undo buffer
22240       (with-current-buffer buffer
22241         (widen)
22242         (goto-char pos)
22243         (org-show-context 'agenda)
22244         (save-excursion
22245           (and (outline-next-heading)
22246                (org-flag-heading nil)))   ; show the next heading
22247         (org-todo arg)
22248         (and (bolp) (forward-char 1))
22249         (setq newhead (org-get-heading))
22250         (save-excursion
22251           (org-back-to-heading)
22252           (move-marker org-last-heading-marker (point))))
22253       (beginning-of-line 1)
22254       (save-excursion
22255         (org-agenda-change-all-lines newhead hdmarker 'fixface))
22256       (move-to-column col))))
22258 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
22259   "Change all lines in the agenda buffer which match HDMARKER.
22260 The new content of the line will be NEWHEAD (as modified by
22261 `org-format-agenda-item').  HDMARKER is checked with
22262 `equal' against all `org-hd-marker' text properties in the file.
22263 If FIXFACE is non-nil, the face of each item is modified acording to
22264 the new TODO state."
22265   (let* ((inhibit-read-only t)
22266          props m pl undone-face done-face finish new dotime cat tags)
22267     (save-excursion
22268       (goto-char (point-max))
22269       (beginning-of-line 1)
22270       (while (not finish)
22271         (setq finish (bobp))
22272         (when (and (setq m (get-text-property (point) 'org-hd-marker))
22273                    (equal m hdmarker))
22274           (setq props (text-properties-at (point))
22275                 dotime (get-text-property (point) 'dotime)
22276                 cat (get-text-property (point) 'org-category)
22277                 tags (get-text-property (point) 'tags)
22278                 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
22279                 pl (get-text-property (point) 'prefix-length)
22280                 undone-face (get-text-property (point) 'undone-face)
22281                 done-face (get-text-property (point) 'done-face))
22282           (move-to-column pl)
22283           (cond
22284            ((equal new "")
22285             (beginning-of-line 1)
22286             (and (looking-at ".*\n?") (replace-match "")))
22287            ((looking-at ".*")
22288             (replace-match new t t)
22289             (beginning-of-line 1)
22290             (add-text-properties (point-at-bol) (point-at-eol) props)
22291             (when fixface
22292               (add-text-properties
22293                (point-at-bol) (point-at-eol)
22294                (list 'face
22295                      (if org-last-todo-state-is-todo
22296                          undone-face done-face))))
22297             (org-agenda-highlight-todo 'line)
22298             (beginning-of-line 1))
22299            (t (error "Line update did not work"))))
22300         (beginning-of-line 0)))
22301     (org-finalize-agenda)))
22303 (defun org-agenda-align-tags (&optional line)
22304   "Align all tags in agenda items to `org-agenda-tags-column'."
22305   (let ((inhibit-read-only t) l c)
22306     (save-excursion
22307       (goto-char (if line (point-at-bol) (point-min)))
22308       (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22309                                 (if line (point-at-eol) nil) t)
22310         (add-text-properties
22311          (match-beginning 2) (match-end 2)
22312          (list 'face (list 'org-tag (get-text-property
22313                                      (match-beginning 2) 'face))))
22314         (setq l (- (match-end 2) (match-beginning 2))
22315               c (if (< org-agenda-tags-column 0)
22316                     (- (abs org-agenda-tags-column) l)
22317                   org-agenda-tags-column))
22318         (delete-region (match-beginning 1) (match-end 1))
22319         (goto-char (match-beginning 1))
22320         (insert (org-add-props
22321                     (make-string (max 1 (- c (current-column))) ?\ )
22322                     (text-properties-at (point))))))))
22324 (defun org-agenda-priority-up ()
22325   "Increase the priority of line at point, also in Org-mode file."
22326   (interactive)
22327   (org-agenda-priority 'up))
22329 (defun org-agenda-priority-down ()
22330   "Decrease the priority of line at point, also in Org-mode file."
22331   (interactive)
22332   (org-agenda-priority 'down))
22334 (defun org-agenda-priority (&optional force-direction)
22335   "Set the priority of line at point, also in Org-mode file.
22336 This changes the line at point, all other lines in the agenda referring to
22337 the same tree node, and the headline of the tree node in the Org-mode file."
22338   (interactive)
22339   (org-agenda-check-no-diary)
22340   (let* ((marker (or (get-text-property (point) 'org-marker)
22341                      (org-agenda-error)))
22342          (hdmarker (get-text-property (point) 'org-hd-marker))
22343          (buffer (marker-buffer hdmarker))
22344          (pos (marker-position hdmarker))
22345          (inhibit-read-only t)
22346          newhead)
22347     (org-with-remote-undo buffer
22348       (with-current-buffer buffer
22349         (widen)
22350         (goto-char pos)
22351         (org-show-context 'agenda)
22352         (save-excursion
22353           (and (outline-next-heading)
22354                (org-flag-heading nil)))   ; show the next heading
22355         (funcall 'org-priority force-direction)
22356         (end-of-line 1)
22357         (setq newhead (org-get-heading)))
22358       (org-agenda-change-all-lines newhead hdmarker)
22359       (beginning-of-line 1))))
22361 (defun org-get-tags-at (&optional pos)
22362   "Get a list of all headline tags applicable at POS.
22363 POS defaults to point.  If tags are inherited, the list contains
22364 the targets in the same sequence as the headlines appear, i.e.
22365 the tags of the current headline come last."
22366   (interactive)
22367   (let (tags lastpos)
22368     (save-excursion
22369       (save-restriction
22370         (widen)
22371         (goto-char (or pos (point)))
22372         (save-match-data
22373           (org-back-to-heading t)
22374           (condition-case nil
22375               (while (not (equal lastpos (point)))
22376                 (setq lastpos (point))
22377                 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
22378                     (setq tags (append (org-split-string
22379                                         (org-match-string-no-properties 1) ":")
22380                                        tags)))
22381               (or org-use-tag-inheritance (error ""))
22382               (org-up-heading-all 1))
22383             (error nil))))
22384       tags)))
22386 ;; FIXME: should fix the tags property of the agenda line.
22387 (defun org-agenda-set-tags ()
22388   "Set tags for the current headline."
22389   (interactive)
22390   (org-agenda-check-no-diary)
22391   (if (and (org-region-active-p) (interactive-p))
22392       (call-interactively 'org-change-tag-in-region)
22393     (org-agenda-show)   ;;; FIXME This is a stupid hack and should not be needed
22394     (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22395                          (org-agenda-error)))
22396            (buffer (marker-buffer hdmarker))
22397            (pos (marker-position hdmarker))
22398            (inhibit-read-only t)
22399            newhead)
22400       (org-with-remote-undo buffer
22401         (with-current-buffer buffer
22402           (widen)
22403           (goto-char pos)
22404           (save-excursion
22405             (org-show-context 'agenda))
22406           (save-excursion
22407             (and (outline-next-heading)
22408                  (org-flag-heading nil)))   ; show the next heading
22409           (goto-char pos)
22410           (call-interactively 'org-set-tags)
22411           (end-of-line 1)
22412           (setq newhead (org-get-heading)))
22413         (org-agenda-change-all-lines newhead hdmarker)
22414         (beginning-of-line 1)))))
22416 (defun org-agenda-toggle-archive-tag ()
22417   "Toggle the archive tag for the current entry."
22418   (interactive)
22419   (org-agenda-check-no-diary)
22420   (org-agenda-show)   ;;; FIXME This is a stupid hack and should not be needed
22421   (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22422                        (org-agenda-error)))
22423          (buffer (marker-buffer hdmarker))
22424          (pos (marker-position hdmarker))
22425          (inhibit-read-only t)
22426          newhead)
22427     (org-with-remote-undo buffer
22428       (with-current-buffer buffer
22429         (widen)
22430         (goto-char pos)
22431         (org-show-context 'agenda)
22432         (save-excursion
22433           (and (outline-next-heading)
22434                (org-flag-heading nil)))   ; show the next heading
22435         (call-interactively 'org-toggle-archive-tag)
22436         (end-of-line 1)
22437         (setq newhead (org-get-heading)))
22438       (org-agenda-change-all-lines newhead hdmarker)
22439       (beginning-of-line 1))))
22441 (defun org-agenda-date-later (arg &optional what)
22442   "Change the date of this item to one day later."
22443   (interactive "p")
22444   (org-agenda-check-type t 'agenda 'timeline)
22445   (org-agenda-check-no-diary)
22446   (let* ((marker (or (get-text-property (point) 'org-marker)
22447                      (org-agenda-error)))
22448          (buffer (marker-buffer marker))
22449          (pos (marker-position marker)))
22450     (org-with-remote-undo buffer
22451      (with-current-buffer buffer
22452        (widen)
22453        (goto-char pos)
22454        (if (not (org-at-timestamp-p))
22455            (error "Cannot find time stamp"))
22456        (org-timestamp-change arg (or what 'day)))
22457      (org-agenda-show-new-time marker org-last-changed-timestamp))
22458     (message "Time stamp changed to %s" org-last-changed-timestamp)))
22460 (defun org-agenda-date-earlier (arg &optional what)
22461   "Change the date of this item to one day earlier."
22462   (interactive "p")
22463   (org-agenda-date-later (- arg) what))
22465 (defun org-agenda-show-new-time (marker stamp &optional prefix)
22466   "Show new date stamp via text properties."
22467   ;; We use text properties to make this undoable
22468   (let ((inhibit-read-only t))
22469     (setq stamp (concat " " prefix " => " stamp))
22470     (save-excursion
22471       (goto-char (point-max))
22472       (while (not (bobp))
22473         (when (equal marker (get-text-property (point) 'org-marker))
22474           (move-to-column (- (window-width) (length stamp)) t)
22475           (if (featurep 'xemacs)
22476               ;; Use `duplicable' property to trigger undo recording
22477               (let ((ex (make-extent nil nil))
22478                     (gl (make-glyph stamp)))
22479                 (set-glyph-face gl 'secondary-selection)
22480                 (set-extent-properties
22481                  ex (list 'invisible t 'end-glyph gl 'duplicable t))
22482                 (insert-extent ex (1- (point)) (point-at-eol)))
22483             (add-text-properties
22484              (1- (point)) (point-at-eol)
22485              (list 'display (org-add-props stamp nil
22486                               'face 'secondary-selection))))
22487           (beginning-of-line 1))
22488         (beginning-of-line 0)))))
22490 (defun org-agenda-date-prompt (arg)
22491   "Change the date of this item.  Date is prompted for, with default today.
22492 The prefix ARG is passed to the `org-time-stamp' command and can therefore
22493 be used to request time specification in the time stamp."
22494   (interactive "P")
22495   (org-agenda-check-type t 'agenda 'timeline)
22496   (org-agenda-check-no-diary)
22497   (let* ((marker (or (get-text-property (point) 'org-marker)
22498                      (org-agenda-error)))
22499          (buffer (marker-buffer marker))
22500          (pos (marker-position marker)))
22501     (org-with-remote-undo buffer
22502       (with-current-buffer buffer
22503         (widen)
22504         (goto-char pos)
22505         (if (not (org-at-timestamp-p))
22506             (error "Cannot find time stamp"))
22507         (org-time-stamp arg)
22508         (message "Time stamp changed to %s" org-last-changed-timestamp)))))
22510 (defun org-agenda-schedule (arg)
22511   "Schedule the item at point."
22512   (interactive "P")
22513   (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22514   (org-agenda-check-no-diary)
22515   (let* ((marker (or (get-text-property (point) 'org-marker)
22516                      (org-agenda-error)))
22517          (buffer (marker-buffer marker))
22518          (pos (marker-position marker))
22519          (org-insert-labeled-timestamps-at-point nil)
22520          ts)
22521     (org-with-remote-undo buffer
22522       (with-current-buffer buffer
22523         (widen)
22524         (goto-char pos)
22525         (setq ts (org-schedule arg)))
22526       (org-agenda-show-new-time marker ts "S"))
22527     (message "Item scheduled for %s" ts)))
22529 (defun org-agenda-deadline (arg)
22530   "Schedule the item at point."
22531   (interactive "P")
22532   (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22533   (org-agenda-check-no-diary)
22534   (let* ((marker (or (get-text-property (point) 'org-marker)
22535                      (org-agenda-error)))
22536          (buffer (marker-buffer marker))
22537          (pos (marker-position marker))
22538          (org-insert-labeled-timestamps-at-point nil)
22539          ts)
22540     (org-with-remote-undo buffer
22541       (with-current-buffer buffer
22542         (widen)
22543         (goto-char pos)
22544         (setq ts (org-deadline arg)))
22545       (org-agenda-show-new-time marker ts "S"))
22546         (message "Deadline for this item set to %s" ts)))
22548 (defun org-get-heading (&optional no-tags)
22549   "Return the heading of the current entry, without the stars."
22550   (save-excursion
22551     (org-back-to-heading t)
22552     (if (looking-at
22553          (if no-tags
22554              (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
22555            "\\*+[ \t]+\\([^\r\n]*\\)"))
22556         (match-string 1) "")))
22558 (defun org-agenda-clock-in (&optional arg)
22559   "Start the clock on the currently selected item."
22560   (interactive "P")
22561   (org-agenda-check-no-diary)
22562   (let* ((marker (or (get-text-property (point) 'org-marker)
22563                      (org-agenda-error)))
22564          (pos (marker-position marker)))
22565     (org-with-remote-undo (marker-buffer marker)
22566       (with-current-buffer (marker-buffer marker)
22567         (widen)
22568         (goto-char pos)
22569         (org-clock-in)))))
22571 (defun org-agenda-clock-out (&optional arg)
22572   "Stop the currently running clock."
22573   (interactive "P")
22574   (unless (marker-buffer org-clock-marker)
22575     (error "No running clock"))
22576   (org-with-remote-undo (marker-buffer org-clock-marker)
22577     (org-clock-out)))
22579 (defun org-agenda-clock-cancel (&optional arg)
22580   "Cancel the currently running clock."
22581   (interactive "P")
22582   (unless (marker-buffer org-clock-marker)
22583     (error "No running clock"))
22584   (org-with-remote-undo (marker-buffer org-clock-marker)
22585     (org-clock-cancel)))
22587 (defun org-agenda-diary-entry ()
22588   "Make a diary entry, like the `i' command from the calendar.
22589 All the standard commands work: block, weekly etc."
22590   (interactive)
22591   (org-agenda-check-type t 'agenda 'timeline)
22592   (require 'diary-lib)
22593   (let* ((char (progn
22594                  (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
22595                  (read-char-exclusive)))
22596          (cmd (cdr (assoc char
22597                           '((?d . insert-diary-entry)
22598                             (?w . insert-weekly-diary-entry)
22599                             (?m . insert-monthly-diary-entry)
22600                             (?y . insert-yearly-diary-entry)
22601                             (?a . insert-anniversary-diary-entry)
22602                             (?b . insert-block-diary-entry)
22603                             (?c . insert-cyclic-diary-entry)))))
22604          (oldf (symbol-function 'calendar-cursor-to-date))
22605 ;        (buf (get-file-buffer (substitute-in-file-name diary-file)))
22606          (point (point))
22607          (mark (or (mark t) (point))))
22608     (unless cmd
22609       (error "No command associated with <%c>" char))
22610     (unless (and (get-text-property point 'day)
22611                  (or (not (equal ?b char))
22612                      (get-text-property mark 'day)))
22613       (error "Don't know which date to use for diary entry"))
22614     ;; We implement this by hacking the `calendar-cursor-to-date' function
22615     ;; and the `calendar-mark-ring' variable.  Saves a lot of code.
22616     (let ((calendar-mark-ring
22617            (list (calendar-gregorian-from-absolute
22618                   (or (get-text-property mark 'day)
22619                       (get-text-property point 'day))))))
22620       (unwind-protect
22621           (progn
22622             (fset 'calendar-cursor-to-date
22623                   (lambda (&optional error)
22624                     (calendar-gregorian-from-absolute
22625                      (get-text-property point 'day))))
22626               (call-interactively cmd))
22627         (fset 'calendar-cursor-to-date oldf)))))
22630 (defun org-agenda-execute-calendar-command (cmd)
22631   "Execute a calendar command from the agenda, with the date associated to
22632 the cursor position."
22633   (org-agenda-check-type t 'agenda 'timeline)
22634   (require 'diary-lib)
22635   (unless (get-text-property (point) 'day)
22636     (error "Don't know which date to use for calendar command"))
22637   (let* ((oldf (symbol-function 'calendar-cursor-to-date))
22638          (point (point))
22639          (date (calendar-gregorian-from-absolute
22640                 (get-text-property point 'day)))
22641          ;; the following 3 vars are needed in the calendar
22642          (displayed-day (extract-calendar-day date))
22643          (displayed-month (extract-calendar-month date))
22644          (displayed-year (extract-calendar-year date)))
22645       (unwind-protect
22646           (progn
22647             (fset 'calendar-cursor-to-date
22648                   (lambda (&optional error)
22649                     (calendar-gregorian-from-absolute
22650                      (get-text-property point 'day))))
22651             (call-interactively cmd))
22652         (fset 'calendar-cursor-to-date oldf))))
22654 (defun org-agenda-phases-of-moon ()
22655   "Display the phases of the moon for the 3 months around the cursor date."
22656   (interactive)
22657   (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
22659 (defun org-agenda-holidays ()
22660   "Display the holidays for the 3 months around the cursor date."
22661   (interactive)
22662   (org-agenda-execute-calendar-command 'list-calendar-holidays))
22664 (defun org-agenda-sunrise-sunset (arg)
22665   "Display sunrise and sunset for the cursor date.
22666 Latitude and longitude can be specified with the variables
22667 `calendar-latitude' and `calendar-longitude'.  When called with prefix
22668 argument, latitude and longitude will be prompted for."
22669   (interactive "P")
22670   (let ((calendar-longitude (if arg nil calendar-longitude))
22671         (calendar-latitude  (if arg nil calendar-latitude))
22672         (calendar-location-name
22673          (if arg "the given coordinates" calendar-location-name)))
22674     (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
22676 (defun org-agenda-goto-calendar ()
22677   "Open the Emacs calendar with the date at the cursor."
22678   (interactive)
22679   (org-agenda-check-type t 'agenda 'timeline)
22680   (let* ((day (or (get-text-property (point) 'day)
22681                   (error "Don't know which date to open in calendar")))
22682          (date (calendar-gregorian-from-absolute day))
22683          (calendar-move-hook nil)
22684          (view-calendar-holidays-initially nil)
22685          (view-diary-entries-initially nil))
22686     (calendar)
22687     (calendar-goto-date date)))
22689 (defun org-calendar-goto-agenda ()
22690   "Compute the Org-mode agenda for the calendar date displayed at the cursor.
22691 This is a command that has to be installed in `calendar-mode-map'."
22692   (interactive)
22693   (org-agenda-list nil (calendar-absolute-from-gregorian
22694                         (calendar-cursor-to-date))
22695                    nil))
22697 (defun org-agenda-convert-date ()
22698   (interactive)
22699   (org-agenda-check-type t 'agenda 'timeline)
22700   (let ((day (get-text-property (point) 'day))
22701         date s)
22702     (unless day
22703       (error "Don't know which date to convert"))
22704     (setq date (calendar-gregorian-from-absolute day))
22705     (setq s (concat
22706              "Gregorian:  " (calendar-date-string date) "\n"
22707              "ISO:        " (calendar-iso-date-string date) "\n"
22708              "Day of Yr:  " (calendar-day-of-year-string date) "\n"
22709              "Julian:     " (calendar-julian-date-string date) "\n"
22710              "Astron. JD: " (calendar-astro-date-string date)
22711              " (Julian date number at noon UTC)\n"
22712              "Hebrew:     " (calendar-hebrew-date-string date) " (until sunset)\n"
22713              "Islamic:    " (calendar-islamic-date-string date) " (until sunset)\n"
22714              "French:     " (calendar-french-date-string date) "\n"
22715              "Baha'i:     " (calendar-bahai-date-string date) " (until sunset)\n"
22716              "Mayan:      " (calendar-mayan-date-string date) "\n"
22717              "Coptic:     " (calendar-coptic-date-string date) "\n"
22718              "Ethiopic:   " (calendar-ethiopic-date-string date) "\n"
22719              "Persian:    " (calendar-persian-date-string date) "\n"
22720              "Chinese:    " (calendar-chinese-date-string date) "\n"))
22721     (with-output-to-temp-buffer "*Dates*"
22722       (princ s))
22723     (if (fboundp 'fit-window-to-buffer)
22724         (fit-window-to-buffer (get-buffer-window "*Dates*")))))
22727 ;;;; Embedded LaTeX
22729 (defvar org-cdlatex-mode-map (make-sparse-keymap)
22730   "Keymap for the minor `org-cdlatex-mode'.")
22732 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
22733 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
22734 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
22735 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
22736 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
22738 (defvar org-cdlatex-texmathp-advice-is-done nil
22739   "Flag remembering if we have applied the advice to texmathp already.")
22741 (define-minor-mode org-cdlatex-mode
22742   "Toggle the minor `org-cdlatex-mode'.
22743 This mode supports entering LaTeX environment and math in LaTeX fragments
22744 in Org-mode.
22745 \\{org-cdlatex-mode-map}"
22746   nil " OCDL" nil
22747   (when org-cdlatex-mode (require 'cdlatex))
22748   (unless org-cdlatex-texmathp-advice-is-done
22749     (setq org-cdlatex-texmathp-advice-is-done t)
22750     (defadvice texmathp (around org-math-always-on activate)
22751       "Always return t in org-mode buffers.
22752 This is because we want to insert math symbols without dollars even outside
22753 the LaTeX math segments.  If Orgmode thinks that point is actually inside
22754 en embedded LaTeX fragement, let texmathp do its job.
22755 \\[org-cdlatex-mode-map]"
22756       (interactive)
22757       (let (p)
22758         (cond
22759          ((not (org-mode-p)) ad-do-it)
22760          ((eq this-command 'cdlatex-math-symbol)
22761           (setq ad-return-value t
22762                 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
22763          (t
22764           (let ((p (org-inside-LaTeX-fragment-p)))
22765             (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
22766                 (setq ad-return-value t
22767                       texmathp-why '("Org-mode embedded math" . 0))
22768               (if p ad-do-it)))))))))
22770 (defun turn-on-org-cdlatex ()
22771   "Unconditionally turn on `org-cdlatex-mode'."
22772   (org-cdlatex-mode 1))
22774 (defun org-inside-LaTeX-fragment-p ()
22775   "Test if point is inside a LaTeX fragment.
22776 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
22777 sequence appearing also before point.
22778 Even though the matchers for math are configurable, this function assumes
22779 that \\begin, \\(, \\[, and $$ are always used.  Only the single dollar
22780 delimiters are skipped when they have been removed by customization.
22781 The return value is nil, or a cons cell with the delimiter and
22782 and the position of this delimiter.
22784 This function does a reasonably good job, but can locally be fooled by
22785 for example currency specifications.  For example it will assume being in
22786 inline math after \"$22.34\".  The LaTeX fragment formatter will only format
22787 fragments that are properly closed, but during editing, we have to live
22788 with the uncertainty caused by missing closing delimiters.  This function
22789 looks only before point, not after."
22790   (catch 'exit
22791     (let ((pos (point))
22792           (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
22793           (lim (progn
22794                  (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
22795                  (point)))
22796           dd-on str (start 0) m re)
22797       (goto-char pos)
22798       (when dodollar
22799         (setq str (concat (buffer-substring lim (point)) "\000 X$.")
22800               re (nth 1 (assoc "$" org-latex-regexps)))
22801         (while (string-match re str start)
22802           (cond
22803            ((= (match-end 0) (length str))
22804             (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
22805            ((= (match-end 0) (- (length str) 5))
22806             (throw 'exit nil))
22807            (t (setq start (match-end 0))))))
22808       (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
22809         (goto-char pos)
22810         (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
22811         (and (match-beginning 2) (throw 'exit nil))
22812         ;; count $$
22813         (while (re-search-backward "\\$\\$" lim t)
22814           (setq dd-on (not dd-on)))
22815         (goto-char pos)
22816         (if dd-on (cons "$$" m))))))
22819 (defun org-try-cdlatex-tab ()
22820   "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
22821 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
22822   - inside a LaTeX fragment, or
22823   - after the first word in a line, where an abbreviation expansion could
22824     insert a LaTeX environment."
22825   (when org-cdlatex-mode
22826     (cond
22827      ((save-excursion
22828         (skip-chars-backward "a-zA-Z0-9*")
22829         (skip-chars-backward " \t")
22830         (bolp))
22831       (cdlatex-tab) t)
22832      ((org-inside-LaTeX-fragment-p)
22833       (cdlatex-tab) t)
22834      (t nil))))
22836 (defun org-cdlatex-underscore-caret (&optional arg)
22837   "Execute `cdlatex-sub-superscript' in LaTeX fragments.
22838 Revert to the normal definition outside of these fragments."
22839   (interactive "P")
22840   (if (org-inside-LaTeX-fragment-p)
22841       (call-interactively 'cdlatex-sub-superscript)
22842     (let (org-cdlatex-mode)
22843       (call-interactively (key-binding (vector last-input-event))))))
22845 (defun org-cdlatex-math-modify (&optional arg)
22846   "Execute `cdlatex-math-modify' in LaTeX fragments.
22847 Revert to the normal definition outside of these fragments."
22848   (interactive "P")
22849   (if (org-inside-LaTeX-fragment-p)
22850       (call-interactively 'cdlatex-math-modify)
22851     (let (org-cdlatex-mode)
22852       (call-interactively (key-binding (vector last-input-event))))))
22854 (defvar org-latex-fragment-image-overlays nil
22855   "List of overlays carrying the images of latex fragments.")
22856 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
22858 (defun org-remove-latex-fragment-image-overlays ()
22859   "Remove all overlays with LaTeX fragment images in current buffer."
22860   (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
22861   (setq org-latex-fragment-image-overlays nil))
22863 (defun org-preview-latex-fragment (&optional subtree)
22864   "Preview the LaTeX fragment at point, or all locally or globally.
22865 If the cursor is in a LaTeX fragment, create the image and overlay
22866 it over the source code.  If there is no fragment at point, display
22867 all fragments in the current text, from one headline to the next.  With
22868 prefix SUBTREE, display all fragments in the current subtree.  With a
22869 double prefix `C-u C-u', or when the cursor is before the first headline,
22870 display all fragments in the buffer.
22871 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
22872   (interactive "P")
22873   (org-remove-latex-fragment-image-overlays)
22874   (save-excursion
22875     (save-restriction
22876       (let (beg end at msg)
22877         (cond
22878          ((or (equal subtree '(16))
22879               (not (save-excursion
22880                      (re-search-backward (concat "^" outline-regexp) nil t))))
22881           (setq beg (point-min) end (point-max)
22882                 msg "Creating images for buffer...%s"))
22883          ((equal subtree '(4))
22884           (org-back-to-heading)
22885           (setq beg (point) end (org-end-of-subtree t)
22886                 msg "Creating images for subtree...%s"))
22887          (t
22888           (if (setq at (org-inside-LaTeX-fragment-p))
22889               (goto-char (max (point-min) (- (cdr at) 2)))
22890             (org-back-to-heading))
22891           (setq beg (point) end (progn (outline-next-heading) (point))
22892                 msg (if at "Creating image...%s"
22893                       "Creating images for entry...%s"))))
22894         (message msg "")
22895         (narrow-to-region beg end)
22896         (goto-char beg)
22897         (org-format-latex
22898          (concat "ltxpng/" (file-name-sans-extension
22899                             (file-name-nondirectory
22900                              buffer-file-name)))
22901          default-directory 'overlays msg at 'forbuffer)
22902       (message msg "done.  Use `C-c C-c' to remove images.")))))
22904 (defvar org-latex-regexps
22905   '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
22906     ;; ("$" "\\([       (]\\|^\\)\\(\\(\\([$]\\)\\([^   \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^       \r\n,.$]\\)\\4\\)\\)\\([        .,?;:'\")]\\|$\\)" 2 nil)
22907     ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
22908     ("$" "\\([^$]\\)\\(\\(\\$\\([^      \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^        \r\n,.$]\\)\\$\\)\\)\\([        .,?;:'\")\000]\\|$\\)" 2 nil)
22909     ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
22910     ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
22911     ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
22912   "Regular expressions for matching embedded LaTeX.")
22914 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
22915   "Replace LaTeX fragments with links to an image, and produce images."
22916   (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
22917   (let* ((prefixnodir (file-name-nondirectory prefix))
22918          (absprefix (expand-file-name prefix dir))
22919          (todir (file-name-directory absprefix))
22920          (opt org-format-latex-options)
22921          (matchers (plist-get opt :matchers))
22922          (re-list org-latex-regexps)
22923          (cnt 0) txt link beg end re e checkdir
22924          m n block linkfile movefile ov)
22925     ;; Check if there are old images files with this prefix, and remove them
22926     (when (file-directory-p todir)
22927       (mapc 'delete-file
22928             (directory-files
22929              todir 'full
22930              (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
22931     ;; Check the different regular expressions
22932     (while (setq e (pop re-list))
22933       (setq m (car e) re (nth 1 e) n (nth 2 e)
22934             block (if (nth 3 e) "\n\n" ""))
22935       (when (member m matchers)
22936         (goto-char (point-min))
22937         (while (re-search-forward re nil t)
22938           (when (or (not at) (equal (cdr at) (match-beginning n)))
22939             (setq txt (match-string n)
22940                   beg (match-beginning n) end (match-end n)
22941                   cnt (1+ cnt)
22942                   linkfile (format "%s_%04d.png" prefix cnt)
22943                   movefile (format "%s_%04d.png" absprefix cnt)
22944                   link (concat block "[[file:" linkfile "]]" block))
22945             (if msg (message msg cnt))
22946             (goto-char beg)
22947             (unless checkdir ; make sure the directory exists
22948               (setq checkdir t)
22949               (or (file-directory-p todir) (make-directory todir)))
22950             (org-create-formula-image
22951              txt movefile opt forbuffer)
22952             (if overlays
22953                 (progn
22954                   (setq ov (org-make-overlay beg end))
22955                   (if (featurep 'xemacs)
22956                       (progn
22957                         (org-overlay-put ov 'invisible t)
22958                         (org-overlay-put
22959                          ov 'end-glyph
22960                          (make-glyph (vector 'png :file movefile))))
22961                     (org-overlay-put
22962                      ov 'display
22963                      (list 'image :type 'png :file movefile :ascent 'center)))
22964                   (push ov org-latex-fragment-image-overlays)
22965                   (goto-char end))
22966               (delete-region beg end)
22967               (insert link))))))))
22969 ;; This function borrows from Ganesh Swami's latex2png.el
22970 (defun org-create-formula-image (string tofile options buffer)
22971   (let* ((tmpdir (if (featurep 'xemacs)
22972                      (temp-directory)
22973                    temporary-file-directory))
22974          (texfilebase (make-temp-name
22975                        (expand-file-name "orgtex" tmpdir)))
22976          (texfile (concat texfilebase ".tex"))
22977          (dvifile (concat texfilebase ".dvi"))
22978          (pngfile (concat texfilebase ".png"))
22979          (fnh (face-attribute 'default :height nil))
22980          (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
22981          (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
22982          (fg (or (plist-get options (if buffer :foreground :html-foreground))
22983                  "Black"))
22984          (bg (or (plist-get options (if buffer :background :html-background))
22985                  "Transparent")))
22986     (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
22987     (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
22988     (with-temp-file texfile
22989       (insert org-format-latex-header
22990               "\n\\begin{document}\n" string "\n\\end{document}\n"))
22991     (let ((dir default-directory))
22992       (condition-case nil
22993           (progn
22994             (cd tmpdir)
22995             (call-process "latex" nil nil nil texfile))
22996         (error nil))
22997       (cd dir))
22998     (if (not (file-exists-p dvifile))
22999         (progn (message "Failed to create dvi file from %s" texfile) nil)
23000       (call-process "dvipng" nil nil nil
23001                     "-E" "-fg" fg "-bg" bg
23002                     "-D" dpi
23003                     ;;"-x" scale "-y" scale
23004                     "-T" "tight"
23005                     "-o" pngfile
23006                     dvifile)
23007       (if (not (file-exists-p pngfile))
23008           (progn (message "Failed to create png file from %s" texfile) nil)
23009         ;; Use the requested file name and clean up
23010         (copy-file pngfile tofile 'replace)
23011         (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23012               (delete-file (concat texfilebase e)))
23013         pngfile))))
23015 (defun org-dvipng-color (attr)
23016   "Return an rgb color specification for dvipng."
23017   (apply 'format "rgb %s %s %s"
23018          (mapcar 'org-normalize-color
23019                  (color-values (face-attribute 'default attr nil)))))
23021 (defun org-normalize-color (value)
23022   "Return string to be used as color value for an RGB component."
23023   (format "%g" (/ value 65535.0)))
23025 ;;;; Exporting
23027 ;;; Variables, constants, and parameter plists
23029 (defconst org-level-max 20)
23031 (defvar org-export-html-preamble nil
23032   "Preamble, to be inserted just after <body>.  Set by publishing functions.")
23033 (defvar org-export-html-postamble nil
23034   "Preamble, to be inserted just before </body>.  Set by publishing functions.")
23035 (defvar org-export-html-auto-preamble t
23036   "Should default preamble be inserted?  Set by publishing functions.")
23037 (defvar org-export-html-auto-postamble t
23038   "Should default postamble be inserted?  Set by publishing functions.")
23039 (defvar org-current-export-file nil) ; dynamically scoped parameter
23040 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23043 (defconst org-export-plist-vars
23044   '((:language             . org-export-default-language)
23045     (:customtime           . org-display-custom-times)
23046     (:headline-levels      . org-export-headline-levels)
23047     (:section-numbers      . org-export-with-section-numbers)
23048     (:table-of-contents    . org-export-with-toc)
23049     (:preserve-breaks      . org-export-preserve-breaks)
23050     (:archived-trees       . org-export-with-archived-trees)
23051     (:emphasize            . org-export-with-emphasize)
23052     (:sub-superscript      . org-export-with-sub-superscripts)
23053     (:special-strings      . org-export-with-special-strings)
23054     (:footnotes            . org-export-with-footnotes)
23055     (:drawers              . org-export-with-drawers)
23056     (:tags                 . org-export-with-tags)
23057     (:TeX-macros           . org-export-with-TeX-macros)
23058     (:LaTeX-fragments      . org-export-with-LaTeX-fragments)
23059     (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23060     (:fixed-width          . org-export-with-fixed-width)
23061     (:timestamps           . org-export-with-timestamps)
23062     (:author-info          . org-export-author-info)
23063     (:time-stamp-file      . org-export-time-stamp-file)
23064     (:tables               . org-export-with-tables)
23065     (:table-auto-headline  . org-export-highlight-first-table-line)
23066     (:style                . org-export-html-style)
23067     (:agenda-style         . org-agenda-export-html-style)
23068     (:convert-org-links    . org-export-html-link-org-files-as-html)
23069     (:inline-images        . org-export-html-inline-images)
23070     (:html-extension       . org-export-html-extension)
23071     (:html-table-tag       . org-export-html-table-tag)
23072     (:expand-quoted-html   . org-export-html-expand)
23073     (:timestamp            . org-export-html-with-timestamp)
23074     (:publishing-directory . org-export-publishing-directory)
23075     (:preamble             . org-export-html-preamble)
23076     (:postamble            . org-export-html-postamble)
23077     (:auto-preamble        . org-export-html-auto-preamble)
23078     (:auto-postamble       . org-export-html-auto-postamble)
23079     (:author               . user-full-name)
23080     (:email                . user-mail-address)))
23082 (defun org-default-export-plist ()
23083   "Return the property list with default settings for the export variables."
23084   (let ((l org-export-plist-vars) rtn e)
23085     (while (setq e (pop l))
23086       (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23087     rtn))
23089 (defun org-infile-export-plist ()
23090   "Return the property list with file-local settings for export."
23091   (save-excursion
23092     (save-restriction
23093       (widen)
23094       (goto-char 0)
23095       (let ((re (org-make-options-regexp
23096                  '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23097             p key val text options)
23098         (while (re-search-forward re nil t)
23099           (setq key (org-match-string-no-properties 1)
23100                 val (org-match-string-no-properties 2))
23101           (cond
23102            ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23103            ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23104            ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23105            ((string-equal key "DATE") (setq p (plist-put p :date val)))
23106            ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23107            ((string-equal key "TEXT")
23108             (setq text (if text (concat text "\n" val) val)))
23109            ((string-equal key "OPTIONS") (setq options val))))
23110         (setq p (plist-put p :text text))
23111         (when options
23112           (let ((op '(("H"     . :headline-levels)
23113                       ("num"   . :section-numbers)
23114                       ("toc"   . :table-of-contents)
23115                       ("\\n"   . :preserve-breaks)
23116                       ("@"     . :expand-quoted-html)
23117                       (":"     . :fixed-width)
23118                       ("|"     . :tables)
23119                       ("^"     . :sub-superscript)
23120                       ("-"     . :special-strings)
23121                       ("f"     . :footnotes)
23122                       ("d"     . :drawers)
23123                       ("tags"  . :tags)
23124                       ("*"     . :emphasize)
23125                       ("TeX"   . :TeX-macros)
23126                       ("LaTeX" . :LaTeX-fragments)
23127                       ("skip"  . :skip-before-1st-heading)
23128                       ("author" . :author-info)
23129                       ("timestamp" . :time-stamp-file)))
23130                 o)
23131             (while (setq o (pop op))
23132               (if (string-match (concat (regexp-quote (car o))
23133                                         ":\\([^ \t\n\r;,.]*\\)")
23134                                 options)
23135                   (setq p (plist-put p (cdr o)
23136                                      (car (read-from-string
23137                                            (match-string 1 options)))))))))
23138         p))))
23140 (defun org-export-directory (type plist)
23141   (let* ((val (plist-get plist :publishing-directory))
23142          (dir (if (listp val)
23143                   (or (cdr (assoc type val)) ".")
23144                 val)))
23145     dir))
23147 (defun org-skip-comments (lines)
23148   "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23149   (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23150         (re2 "^\\(\\*+\\)[ \t\n\r]")
23151         (case-fold-search nil)
23152         rtn line level)
23153     (while (setq line (pop lines))
23154       (cond
23155        ((and (string-match re1 line)
23156              (setq level (- (match-end 1) (match-beginning 1))))
23157         ;; Beginning of a COMMENT subtree.  Skip it.
23158         (while (and (setq line (pop lines))
23159                     (or (not (string-match re2 line))
23160                         (> (- (match-end 1) (match-beginning 1)) level))))
23161         (setq lines (cons line lines)))
23162        ((string-match "^#" line)
23163         ;; an ordinary comment line
23164         )
23165        ((and org-export-table-remove-special-lines
23166              (string-match "^[ \t]*|" line)
23167              (or (string-match "^[ \t]*| *[!_^] *|" line)
23168                  (and (string-match "| *<[0-9]+> *|" line)
23169                       (not (string-match "| *[^ <|]" line)))))
23170         ;; a special table line that should be removed
23171         )
23172        (t (setq rtn (cons line rtn)))))
23173     (nreverse rtn)))
23175 (defun org-export (&optional arg)
23176   (interactive)
23177   (let ((help "[t]   insert the export option template
23178 \[v]   limit export to visible part of outline tree
23180 \[a] export as ASCII
23182 \[h] export as HTML
23183 \[H] export as HTML to temporary buffer
23184 \[R] export region as HTML
23185 \[b] export as HTML and browse immediately
23186 \[x] export as XOXO
23188 \[l] export as LaTeX
23189 \[L] export as LaTeX to temporary buffer
23191 \[i] export current file as iCalendar file
23192 \[I] export all agenda files as iCalendar files
23193 \[c] export agenda files into combined iCalendar file
23195 \[F] publish current file
23196 \[P] publish current project
23197 \[X] publish... (project will be prompted for)
23198 \[A] publish all projects")
23199         (cmds
23200          '((?t . org-insert-export-options-template)
23201            (?v . org-export-visible)
23202            (?a . org-export-as-ascii)
23203            (?h . org-export-as-html)
23204            (?b . org-export-as-html-and-open)
23205            (?H . org-export-as-html-to-buffer)
23206            (?R . org-export-region-as-html)
23207            (?x . org-export-as-xoxo)
23208            (?l . org-export-as-latex)
23209            (?L . org-export-as-latex-to-buffer)
23210            (?i . org-export-icalendar-this-file)
23211            (?I . org-export-icalendar-all-agenda-files)
23212            (?c . org-export-icalendar-combine-agenda-files)
23213            (?F . org-publish-current-file)
23214            (?P . org-publish-current-project)
23215            (?X . org-publish)
23216            (?A . org-publish-all)))
23217         r1 r2 ass)
23218     (save-window-excursion
23219       (delete-other-windows)
23220       (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23221         (princ help))
23222       (message "Select command: ")
23223       (setq r1 (read-char-exclusive)))
23224     (setq r2 (if (< r1 27) (+ r1 96) r1))
23225     (if (setq ass (assq r2 cmds))
23226         (call-interactively (cdr ass))
23227       (error "No command associated with key %c" r1))))
23229 (defconst org-html-entities
23230   '(("nbsp")
23231     ("iexcl")
23232     ("cent")
23233     ("pound")
23234     ("curren")
23235     ("yen")
23236     ("brvbar")
23237     ("vert" . "&#124;")
23238     ("sect")
23239     ("uml")
23240     ("copy")
23241     ("ordf")
23242     ("laquo")
23243     ("not")
23244     ("shy")
23245     ("reg")
23246     ("macr")
23247     ("deg")
23248     ("plusmn")
23249     ("sup2")
23250     ("sup3")
23251     ("acute")
23252     ("micro")
23253     ("para")
23254     ("middot")
23255     ("odot"."o")
23256     ("star"."*")
23257     ("cedil")
23258     ("sup1")
23259     ("ordm")
23260     ("raquo")
23261     ("frac14")
23262     ("frac12")
23263     ("frac34")
23264     ("iquest")
23265     ("Agrave")
23266     ("Aacute")
23267     ("Acirc")
23268     ("Atilde")
23269     ("Auml")
23270     ("Aring") ("AA"."&Aring;")
23271     ("AElig")
23272     ("Ccedil")
23273     ("Egrave")
23274     ("Eacute")
23275     ("Ecirc")
23276     ("Euml")
23277     ("Igrave")
23278     ("Iacute")
23279     ("Icirc")
23280     ("Iuml")
23281     ("ETH")
23282     ("Ntilde")
23283     ("Ograve")
23284     ("Oacute")
23285     ("Ocirc")
23286     ("Otilde")
23287     ("Ouml")
23288     ("times")
23289     ("Oslash")
23290     ("Ugrave")
23291     ("Uacute")
23292     ("Ucirc")
23293     ("Uuml")
23294     ("Yacute")
23295     ("THORN")
23296     ("szlig")
23297     ("agrave")
23298     ("aacute")
23299     ("acirc")
23300     ("atilde")
23301     ("auml")
23302     ("aring")
23303     ("aelig")
23304     ("ccedil")
23305     ("egrave")
23306     ("eacute")
23307     ("ecirc")
23308     ("euml")
23309     ("igrave")
23310     ("iacute")
23311     ("icirc")
23312     ("iuml")
23313     ("eth")
23314     ("ntilde")
23315     ("ograve")
23316     ("oacute")
23317     ("ocirc")
23318     ("otilde")
23319     ("ouml")
23320     ("divide")
23321     ("oslash")
23322     ("ugrave")
23323     ("uacute")
23324     ("ucirc")
23325     ("uuml")
23326     ("yacute")
23327     ("thorn")
23328     ("yuml")
23329     ("fnof")
23330     ("Alpha")
23331     ("Beta")
23332     ("Gamma")
23333     ("Delta")
23334     ("Epsilon")
23335     ("Zeta")
23336     ("Eta")
23337     ("Theta")
23338     ("Iota")
23339     ("Kappa")
23340     ("Lambda")
23341     ("Mu")
23342     ("Nu")
23343     ("Xi")
23344     ("Omicron")
23345     ("Pi")
23346     ("Rho")
23347     ("Sigma")
23348     ("Tau")
23349     ("Upsilon")
23350     ("Phi")
23351     ("Chi")
23352     ("Psi")
23353     ("Omega")
23354     ("alpha")
23355     ("beta")
23356     ("gamma")
23357     ("delta")
23358     ("epsilon")
23359     ("varepsilon"."&epsilon;")
23360     ("zeta")
23361     ("eta")
23362     ("theta")
23363     ("iota")
23364     ("kappa")
23365     ("lambda")
23366     ("mu")
23367     ("nu")
23368     ("xi")
23369     ("omicron")
23370     ("pi")
23371     ("rho")
23372     ("sigmaf") ("varsigma"."&sigmaf;")
23373     ("sigma")
23374     ("tau")
23375     ("upsilon")
23376     ("phi")
23377     ("chi")
23378     ("psi")
23379     ("omega")
23380     ("thetasym") ("vartheta"."&thetasym;")
23381     ("upsih")
23382     ("piv")
23383     ("bull") ("bullet"."&bull;")
23384     ("hellip") ("dots"."&hellip;")
23385     ("prime")
23386     ("Prime")
23387     ("oline")
23388     ("frasl")
23389     ("weierp")
23390     ("image")
23391     ("real")
23392     ("trade")
23393     ("alefsym")
23394     ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
23395     ("uarr") ("uparrow"."&uarr;")
23396     ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
23397     ("darr")("downarrow"."&darr;")
23398     ("harr") ("leftrightarrow"."&harr;")
23399     ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
23400     ("lArr") ("Leftarrow"."&lArr;")
23401     ("uArr") ("Uparrow"."&uArr;")
23402     ("rArr") ("Rightarrow"."&rArr;")
23403     ("dArr") ("Downarrow"."&dArr;")
23404     ("hArr") ("Leftrightarrow"."&hArr;")
23405     ("forall")
23406     ("part") ("partial"."&part;")
23407     ("exist") ("exists"."&exist;")
23408     ("empty") ("emptyset"."&empty;")
23409     ("nabla")
23410     ("isin") ("in"."&isin;")
23411     ("notin")
23412     ("ni")
23413     ("prod")
23414     ("sum")
23415     ("minus")
23416     ("lowast") ("ast"."&lowast;")
23417     ("radic")
23418     ("prop") ("proptp"."&prop;")
23419     ("infin") ("infty"."&infin;")
23420     ("ang") ("angle"."&ang;")
23421     ("and") ("wedge"."&and;")
23422     ("or") ("vee"."&or;")
23423     ("cap")
23424     ("cup")
23425     ("int")
23426     ("there4")
23427     ("sim")
23428     ("cong") ("simeq"."&cong;")
23429     ("asymp")("approx"."&asymp;")
23430     ("ne") ("neq"."&ne;")
23431     ("equiv")
23432     ("le")
23433     ("ge")
23434     ("sub") ("subset"."&sub;")
23435     ("sup") ("supset"."&sup;")
23436     ("nsub")
23437     ("sube")
23438     ("supe")
23439     ("oplus")
23440     ("otimes")
23441     ("perp")
23442     ("sdot") ("cdot"."&sdot;")
23443     ("lceil")
23444     ("rceil")
23445     ("lfloor")
23446     ("rfloor")
23447     ("lang")
23448     ("rang")
23449     ("loz") ("Diamond"."&loz;")
23450     ("spades") ("spadesuit"."&spades;")
23451     ("clubs") ("clubsuit"."&clubs;")
23452     ("hearts") ("diamondsuit"."&hearts;")
23453     ("diams") ("diamondsuit"."&diams;")
23454     ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
23455     ("quot")
23456     ("amp")
23457     ("lt")
23458     ("gt")
23459     ("OElig")
23460     ("oelig")
23461     ("Scaron")
23462     ("scaron")
23463     ("Yuml")
23464     ("circ")
23465     ("tilde")
23466     ("ensp")
23467     ("emsp")
23468     ("thinsp")
23469     ("zwnj")
23470     ("zwj")
23471     ("lrm")
23472     ("rlm")
23473     ("ndash")
23474     ("mdash")
23475     ("lsquo")
23476     ("rsquo")
23477     ("sbquo")
23478     ("ldquo")
23479     ("rdquo")
23480     ("bdquo")
23481     ("dagger")
23482     ("Dagger")
23483     ("permil")
23484     ("lsaquo")
23485     ("rsaquo")
23486     ("euro")
23488     ("arccos"."arccos")
23489     ("arcsin"."arcsin")
23490     ("arctan"."arctan")
23491     ("arg"."arg")
23492     ("cos"."cos")
23493     ("cosh"."cosh")
23494     ("cot"."cot")
23495     ("coth"."coth")
23496     ("csc"."csc")
23497     ("deg"."deg")
23498     ("det"."det")
23499     ("dim"."dim")
23500     ("exp"."exp")
23501     ("gcd"."gcd")
23502     ("hom"."hom")
23503     ("inf"."inf")
23504     ("ker"."ker")
23505     ("lg"."lg")
23506     ("lim"."lim")
23507     ("liminf"."liminf")
23508     ("limsup"."limsup")
23509     ("ln"."ln")
23510     ("log"."log")
23511     ("max"."max")
23512     ("min"."min")
23513     ("Pr"."Pr")
23514     ("sec"."sec")
23515     ("sin"."sin")
23516     ("sinh"."sinh")
23517     ("sup"."sup")
23518     ("tan"."tan")
23519     ("tanh"."tanh")
23520     )
23521   "Entities for TeX->HTML translation.
23522 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
23523 \"&ent;\".  An entry can also be a dotted pair like (\"ent\".\"&other;\").
23524 In that case, \"\\ent\" will be translated to \"&other;\".
23525 The list contains HTML entities for Latin-1, Greek and other symbols.
23526 It is supplemented by a number of commonly used TeX macros with appropriate
23527 translations.  There is currently no way for users to extend this.")
23529 ;;; General functions for all backends
23531 (defun org-cleaned-string-for-export (string &rest parameters)
23532   "Cleanup a buffer STRING so that links can be created safely."
23533   (interactive)
23534   (let* ((re-radio (and org-target-link-regexp
23535                         (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
23536          (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
23537          (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
23538          (re-archive (concat ":" org-archive-tag ":"))
23539          (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
23540          (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
23541          (htmlp (plist-get parameters :for-html))
23542          (asciip (plist-get parameters :for-ascii))
23543          (latexp (plist-get parameters :for-LaTeX))
23544          (commentsp (plist-get parameters :comments))
23545          (archived-trees (plist-get parameters :archived-trees))
23546          (inhibit-read-only t)
23547          (drawers org-drawers)
23548          (exp-drawers (plist-get parameters :drawers))
23549          (outline-regexp "\\*+ ")
23550          a b xx
23551          rtn p)
23552     (with-current-buffer (get-buffer-create " org-mode-tmp")
23553       (erase-buffer)
23554       (insert string)
23555       ;; Remove license-to-kill stuff
23556       (while (setq p (text-property-any (point-min) (point-max)
23557                                         :org-license-to-kill t))
23558         (delete-region p (next-single-property-change p :org-license-to-kill)))
23560       (let ((org-inhibit-startup t)) (org-mode))
23561       (untabify (point-min) (point-max))
23563       ;; Get the correct stuff before the first headline
23564       (when (plist-get parameters :skip-before-1st-heading)
23565         (goto-char (point-min))
23566         (when (re-search-forward "^\\*+[ \t]" nil t)
23567           (delete-region (point-min) (match-beginning 0))
23568           (goto-char (point-min))
23569           (insert "\n")))
23570       (when (plist-get parameters :add-text)
23571         (goto-char (point-min))
23572         (insert (plist-get parameters :add-text) "\n"))
23574       ;; Get rid of archived trees
23575       (when (not (eq archived-trees t))
23576         (goto-char (point-min))
23577         (while (re-search-forward re-archive nil t)
23578           (if (not (org-on-heading-p t))
23579               (org-end-of-subtree t)
23580             (beginning-of-line 1)
23581             (setq a (if archived-trees
23582                         (1+ (point-at-eol)) (point))
23583                   b (org-end-of-subtree t))
23584             (if (> b a) (delete-region a b)))))
23586       ;; Get rid of drawers
23587       (unless (eq t exp-drawers)
23588         (goto-char (point-min))
23589         (let ((re (concat "^[ \t]*:\\("
23590                           (mapconcat
23591                            'identity
23592                            (org-delete-all exp-drawers
23593                                            (copy-sequence drawers))
23594                            "\\|")
23595                           "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
23596           (while (re-search-forward re nil t)
23597             (replace-match ""))))
23599       ;; Find targets in comments and move them out of comments,
23600       ;; but mark them as targets that should be invisible
23601       (goto-char (point-min))
23602       (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
23603         (replace-match "\\1(INVISIBLE)"))
23605       ;; Protect backend specific stuff, throw away the others.
23606       (let ((formatters
23607              `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
23608                (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
23609                (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
23610             fmt)
23611         (goto-char (point-min))
23612         (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
23613           (goto-char (match-end 0))
23614           (while (not (looking-at "#\\+END_EXAMPLE"))
23615             (insert ": ")
23616             (beginning-of-line 2)))
23617         (goto-char (point-min))
23618         (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
23619           (add-text-properties (match-beginning 0) (match-end 0)
23620                                '(org-protected t)))
23621         (while formatters
23622           (setq fmt (pop formatters))
23623           (when (car fmt)
23624             (goto-char (point-min))
23625             (while (re-search-forward (concat "^#\\+" (cadr fmt)
23626                                               ":[ \t]*\\(.*\\)") nil t)
23627               (replace-match "\\1" t)
23628               (add-text-properties
23629                (point-at-bol) (min (1+ (point-at-eol)) (point-max))
23630                '(org-protected t))))
23631           (goto-char (point-min))
23632           (while (re-search-forward
23633                   (concat "^#\\+"
23634                           (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
23635                           (cadddr fmt) "\\>.*\n?") nil t)
23636             (if (car fmt)
23637                 (add-text-properties (match-beginning 1) (1+ (match-end 1))
23638                                      '(org-protected t))
23639               (delete-region (match-beginning 0) (match-end 0))))))
23641       ;; Protect quoted subtrees
23642       (goto-char (point-min))
23643       (while (re-search-forward re-quote nil t)
23644         (goto-char (match-beginning 0))
23645         (end-of-line 1)
23646         (add-text-properties (point) (org-end-of-subtree t)
23647                              '(org-protected t)))
23649       ;; Protect verbatim elements
23650       (goto-char (point-min))
23651       (while (re-search-forward org-verbatim-re nil t)
23652         (add-text-properties (match-beginning 4) (match-end 4)
23653                              '(org-protected t))
23654         (goto-char (1+ (match-end 4))))
23656       ;; Remove subtrees that are commented
23657       (goto-char (point-min))
23658       (while (re-search-forward re-commented nil t)
23659         (goto-char (match-beginning 0))
23660         (delete-region (point) (org-end-of-subtree t)))
23662       ;; Remove special table lines
23663       (when org-export-table-remove-special-lines
23664         (goto-char (point-min))
23665         (while (re-search-forward "^[ \t]*|" nil t)
23666           (beginning-of-line 1)
23667           (if (or (looking-at "[ \t]*| *[!_^] *|")
23668                   (and (looking-at ".*?| *<[0-9]+> *|")
23669                        (not (looking-at ".*?| *[^ <|]"))))
23670               (delete-region (max (point-min) (1- (point-at-bol)))
23671                              (point-at-eol))
23672             (end-of-line 1))))
23674       ;; Specific LaTeX stuff
23675       (when latexp
23676         (require 'org-export-latex nil)
23677         (org-export-latex-cleaned-string))
23679       (when asciip
23680         (org-export-ascii-clean-string))
23682       ;; Specific HTML stuff
23683       (when htmlp
23684         ;; Convert LaTeX fragments to images
23685         (when (plist-get parameters :LaTeX-fragments)
23686           (org-format-latex
23687            (concat "ltxpng/" (file-name-sans-extension
23688                               (file-name-nondirectory
23689                                org-current-export-file)))
23690            org-current-export-dir nil "Creating LaTeX image %s"))
23691         (message "Exporting..."))
23693       ;; Remove or replace comments
23694       (goto-char (point-min))
23695       (while (re-search-forward "^#\\(.*\n?\\)" nil t)
23696         (if commentsp
23697             (progn (add-text-properties
23698                     (match-beginning 0) (match-end 0) '(org-protected t))
23699                    (replace-match (format commentsp (match-string 1)) t t))
23700           (replace-match "")))
23702       ;; Find matches for radio targets and turn them into internal links
23703       (goto-char (point-min))
23704       (when re-radio
23705         (while (re-search-forward re-radio nil t)
23706           (org-if-unprotected
23707            (replace-match "\\1[[\\2]]"))))
23709       ;; Find all links that contain a newline and put them into a single line
23710       (goto-char (point-min))
23711       (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
23712         (org-if-unprotected
23713          (replace-match "\\1 \\3")
23714          (goto-char (match-beginning 0))))
23717       ;; Normalize links: Convert angle and plain links into bracket links
23718       ;; Expand link abbreviations
23719       (goto-char (point-min))
23720       (while (re-search-forward re-plain-link nil t)
23721         (goto-char (1- (match-end 0)))
23722         (org-if-unprotected
23723          (let* ((s (concat (match-string 1) "[[" (match-string 2)
23724                            ":" (match-string 3) "]]")))
23725            ;; added 'org-link face to links
23726            (put-text-property 0 (length s) 'face 'org-link s)
23727            (replace-match s t t))))
23728       (goto-char (point-min))
23729       (while (re-search-forward re-angle-link nil t)
23730         (goto-char (1- (match-end 0)))
23731         (org-if-unprotected
23732          (let* ((s (concat (match-string 1) "[[" (match-string 2)
23733                            ":" (match-string 3) "]]")))
23734            (put-text-property 0 (length s) 'face 'org-link s)
23735            (replace-match s t t))))
23736       (goto-char (point-min))
23737       (while (re-search-forward org-bracket-link-regexp nil t)
23738         (org-if-unprotected
23739          (let* ((s (concat "[[" (setq xx (save-match-data
23740                                            (org-link-expand-abbrev (match-string 1))))
23741                            "]"
23742                            (if (match-end 3)
23743                                (match-string 2)
23744                              (concat "[" xx "]"))
23745                            "]")))
23746            (put-text-property 0 (length s) 'face 'org-link s)
23747            (replace-match s t t))))
23749       ;; Find multiline emphasis and put them into single line
23750       (when (plist-get  parameters :emph-multiline)
23751         (goto-char (point-min))
23752         (while (re-search-forward org-emph-re nil t)
23753           (if (not (= (char-after (match-beginning 3))
23754                       (char-after (match-beginning 4))))
23755               (org-if-unprotected
23756                (subst-char-in-region (match-beginning 0) (match-end 0)
23757                                      ?\n ?\  t)
23758                (goto-char (1- (match-end 0))))
23759             (goto-char (1+ (match-beginning 0))))))
23761       (setq rtn (buffer-string)))
23762     (kill-buffer " org-mode-tmp")
23763     rtn))
23765 (defun org-export-grab-title-from-buffer ()
23766   "Get a title for the current document, from looking at the buffer."
23767   (let ((inhibit-read-only t))
23768     (save-excursion
23769       (goto-char (point-min))
23770       (let ((end (save-excursion (outline-next-heading) (point))))
23771         (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
23772           ;; Mark the line so that it will not be exported as normal text.
23773           (org-unmodified
23774            (add-text-properties (match-beginning 0) (match-end 0)
23775                                 (list :org-license-to-kill t)))
23776           ;; Return the title string
23777           (org-trim (match-string 0)))))))
23779 (defun org-export-get-title-from-subtree ()
23780   "Return subtree title and exclude it from export."
23781   (let (title (m (mark)))
23782     (save-excursion
23783       (goto-char (region-beginning))
23784       (when (and (org-at-heading-p)
23785                  (>= (org-end-of-subtree t t) (region-end)))
23786         ;; This is a subtree, we take the title from the first heading
23787         (goto-char (region-beginning))
23788         (looking-at org-todo-line-regexp)
23789         (setq title (match-string 3))
23790         (org-unmodified
23791          (add-text-properties (point) (1+ (point-at-eol))
23792                               (list :org-license-to-kill t)))))
23793     title))
23795 (defun org-solidify-link-text (s &optional alist)
23796   "Take link text and make a safe target out of it."
23797   (save-match-data
23798     (let* ((rtn
23799             (mapconcat
23800              'identity
23801              (org-split-string s "[ \t\r\n]+") "--"))
23802            (a (assoc rtn alist)))
23803       (or (cdr a) rtn))))
23805 (defun org-get-min-level (lines)
23806   "Get the minimum level in LINES."
23807   (let ((re "^\\(\\*+\\) ") l min)
23808     (catch 'exit
23809       (while (setq l (pop lines))
23810         (if (string-match re l)
23811             (throw 'exit (org-tr-level (length (match-string 1 l))))))
23812       1)))
23814 ;; Variable holding the vector with section numbers
23815 (defvar org-section-numbers (make-vector org-level-max 0))
23817 (defun org-init-section-numbers ()
23818   "Initialize the vector for the section numbers."
23819   (let* ((level  -1)
23820          (numbers (nreverse (org-split-string "" "\\.")))
23821          (depth (1- (length org-section-numbers)))
23822          (i depth) number-string)
23823     (while (>= i 0)
23824       (if (> i level)
23825           (aset org-section-numbers i 0)
23826         (setq number-string (or (car numbers) "0"))
23827         (if (string-match "\\`[A-Z]\\'" number-string)
23828             (aset org-section-numbers i
23829                   (- (string-to-char number-string) ?A -1))
23830             (aset org-section-numbers i (string-to-number number-string)))
23831         (pop numbers))
23832       (setq i (1- i)))))
23834 (defun org-section-number (&optional level)
23835   "Return a string with the current section number.
23836 When LEVEL is non-nil, increase section numbers on that level."
23837   (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
23838     (when level
23839       (when (> level -1)
23840         (aset org-section-numbers
23841               level (1+ (aref org-section-numbers level))))
23842       (setq idx (1+ level))
23843       (while (<= idx depth)
23844         (if (not (= idx 1))
23845             (aset org-section-numbers idx 0))
23846         (setq idx (1+ idx))))
23847     (setq idx 0)
23848     (while (<= idx depth)
23849       (setq n (aref org-section-numbers idx))
23850       (setq string (concat string (if (not (string= string "")) "." "")
23851                            (int-to-string n)))
23852       (setq idx (1+ idx)))
23853     (save-match-data
23854       (if (string-match "\\`\\([@0]\\.\\)+" string)
23855           (setq string (replace-match "" t nil string)))
23856       (if (string-match "\\(\\.0\\)+\\'" string)
23857           (setq string (replace-match "" t nil string))))
23858     string))
23860 ;;; ASCII export
23862 (defvar org-last-level nil) ; dynamically scoped variable
23863 (defvar org-min-level nil) ; dynamically scoped variable
23864 (defvar org-levels-open nil) ; dynamically scoped parameter
23865 (defvar org-ascii-current-indentation nil) ; For communication
23867 (defun org-export-as-ascii (arg)
23868   "Export the outline as a pretty ASCII file.
23869 If there is an active region, export only the region.
23870 The prefix ARG specifies how many levels of the outline should become
23871 underlined headlines.  The default is 3."
23872   (interactive "P")
23873   (setq-default org-todo-line-regexp org-todo-line-regexp)
23874   (let* ((opt-plist (org-combine-plists (org-default-export-plist)
23875                                         (org-infile-export-plist)))
23876          (region-p (org-region-active-p))
23877          (subtree-p
23878           (when region-p
23879             (save-excursion
23880               (goto-char (region-beginning))
23881               (and (org-at-heading-p)
23882                    (>= (org-end-of-subtree t t) (region-end))))))
23883          (custom-times org-display-custom-times)
23884          (org-ascii-current-indentation '(0 . 0))
23885          (level 0) line txt
23886          (umax nil)
23887          (umax-toc nil)
23888          (case-fold-search nil)
23889          (filename (concat (file-name-as-directory
23890                             (org-export-directory :ascii opt-plist))
23891                            (file-name-sans-extension
23892                             (or (and subtree-p
23893                                      (org-entry-get (region-beginning)
23894                                                     "EXPORT_FILE_NAME" t))
23895                                 (file-name-nondirectory buffer-file-name)))
23896                            ".txt"))
23897          (filename (if (equal (file-truename filename)
23898                               (file-truename buffer-file-name))
23899                        (concat filename ".txt")
23900                      filename))
23901          (buffer (find-file-noselect filename))
23902          (org-levels-open (make-vector org-level-max nil))
23903          (odd org-odd-levels-only)
23904          (date  (plist-get opt-plist :date))
23905          (author      (plist-get opt-plist :author))
23906          (title       (or (and subtree-p (org-export-get-title-from-subtree))
23907                           (plist-get opt-plist :title)
23908                           (and (not
23909                                 (plist-get opt-plist :skip-before-1st-heading))
23910                                (org-export-grab-title-from-buffer))
23911                           (file-name-sans-extension
23912                            (file-name-nondirectory buffer-file-name))))
23913          (email       (plist-get opt-plist :email))
23914          (language    (plist-get opt-plist :language))
23915          (quote-re0   (concat "^[ \t]*" org-quote-string "\\>"))
23916 ;        (quote-re    (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
23917          (todo nil)
23918          (lang-words nil)
23919          (region
23920           (buffer-substring
23921            (if (org-region-active-p) (region-beginning) (point-min))
23922            (if (org-region-active-p) (region-end) (point-max))))
23923          (lines (org-split-string
23924                  (org-cleaned-string-for-export
23925                   region
23926                   :for-ascii t
23927                   :skip-before-1st-heading
23928                   (plist-get opt-plist :skip-before-1st-heading)
23929                   :drawers (plist-get opt-plist :drawers)
23930                   :verbatim-multiline t
23931                   :archived-trees
23932                   (plist-get opt-plist :archived-trees)
23933                   :add-text (plist-get opt-plist :text))
23934                  "\n"))
23935          thetoc have-headings first-heading-pos
23936          table-open table-buffer)
23938     (let ((inhibit-read-only t))
23939       (org-unmodified
23940        (remove-text-properties (point-min) (point-max)
23941                                '(:org-license-to-kill t))))
23943     (setq org-min-level (org-get-min-level lines))
23944     (setq org-last-level org-min-level)
23945     (org-init-section-numbers)
23947     (find-file-noselect filename)
23949     (setq lang-words (or (assoc language org-export-language-setup)
23950                          (assoc "en" org-export-language-setup)))
23951     (switch-to-buffer-other-window buffer)
23952     (erase-buffer)
23953     (fundamental-mode)
23954     ;; create local variables for all options, to make sure all called
23955     ;; functions get the correct information
23956     (mapc (lambda (x)
23957             (set (make-local-variable (cdr x))
23958                  (plist-get opt-plist (car x))))
23959           org-export-plist-vars)
23960     (org-set-local 'org-odd-levels-only odd)
23961     (setq umax (if arg (prefix-numeric-value arg)
23962                  org-export-headline-levels))
23963     (setq umax-toc (if (integerp org-export-with-toc)
23964                        (min org-export-with-toc umax)
23965                      umax))
23967     ;; File header
23968     (if title (org-insert-centered title ?=))
23969     (insert "\n")
23970     (if (and (or author email)
23971              org-export-author-info)
23972         (insert (concat (nth 1 lang-words) ": " (or author "")
23973                         (if email (concat " <" email ">") "")
23974                         "\n")))
23976     (cond
23977      ((and date (string-match "%" date))
23978       (setq date (format-time-string date (current-time))))
23979      (date)
23980      (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
23982     (if (and date org-export-time-stamp-file)
23983         (insert (concat (nth 2 lang-words) ": " date"\n")))
23985     (insert "\n\n")
23987     (if org-export-with-toc
23988         (progn
23989           (push (concat (nth 3 lang-words) "\n") thetoc)
23990           (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
23991           (mapc '(lambda (line)
23992                    (if (string-match org-todo-line-regexp
23993                                      line)
23994                        ;; This is a headline
23995                        (progn
23996                          (setq have-headings t)
23997                          (setq level (- (match-end 1) (match-beginning 1))
23998                                level (org-tr-level level)
23999                                txt (match-string 3 line)
24000                                todo
24001                                (or (and org-export-mark-todo-in-toc
24002                                         (match-beginning 2)
24003                                         (not (member (match-string 2 line)
24004                                                      org-done-keywords)))
24005                                         ; TODO, not DONE
24006                                    (and org-export-mark-todo-in-toc
24007                                         (= level umax-toc)
24008                                         (org-search-todo-below
24009                                          line lines level))))
24010                          (setq txt (org-html-expand-for-ascii txt))
24012                          (while (string-match org-bracket-link-regexp txt)
24013                            (setq txt
24014                                  (replace-match
24015                                   (match-string (if (match-end 2) 3 1) txt)
24016                                   t t txt)))
24018                          (if (and (memq org-export-with-tags '(not-in-toc nil))
24019                                   (string-match
24020                                    (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24021                                    txt))
24022                              (setq txt (replace-match "" t t txt)))
24023                          (if (string-match quote-re0 txt)
24024                              (setq txt (replace-match "" t t txt)))
24026                          (if org-export-with-section-numbers
24027                              (setq txt (concat (org-section-number level)
24028                                                " " txt)))
24029                          (if (<= level umax-toc)
24030                              (progn
24031                                (push
24032                                 (concat
24033                                  (make-string
24034                                   (* (max 0 (- level org-min-level)) 4) ?\ )
24035                                  (format (if todo "%s (*)\n" "%s\n") txt))
24036                                 thetoc)
24037                                (setq org-last-level level))
24038                            ))))
24039                 lines)
24040           (setq thetoc (if have-headings (nreverse thetoc) nil))))
24042     (org-init-section-numbers)
24043     (while (setq line (pop lines))
24044       ;; Remove the quoted HTML tags.
24045       (setq line (org-html-expand-for-ascii line))
24046       ;; Remove targets
24047       (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24048         (setq line (replace-match "" t t line)))
24049       ;; Replace internal links
24050       (while (string-match org-bracket-link-regexp line)
24051         (setq line (replace-match
24052                     (if (match-end 3) "[\\3]" "[\\1]")
24053                     t nil line)))
24054       (when custom-times
24055         (setq line (org-translate-time line)))
24056       (cond
24057        ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24058         ;; a Headline
24059         (setq first-heading-pos (or first-heading-pos (point)))
24060         (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24061               txt (match-string 2 line))
24062         (org-ascii-level-start level txt umax lines))
24064        ((and org-export-with-tables
24065              (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24066         (if (not table-open)
24067             ;; New table starts
24068             (setq table-open t table-buffer nil))
24069         ;; Accumulate lines
24070         (setq table-buffer (cons line table-buffer))
24071         (when (or (not lines)
24072                   (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24073                                      (car lines))))
24074           (setq table-open nil
24075                 table-buffer (nreverse table-buffer))
24076           (insert (mapconcat
24077                    (lambda (x)
24078                      (org-fix-indentation x org-ascii-current-indentation))
24079                    (org-format-table-ascii table-buffer)
24080                    "\n") "\n")))
24081        (t
24082         (setq line (org-fix-indentation line org-ascii-current-indentation))
24083         (if (and org-export-with-fixed-width
24084                  (string-match "^\\([ \t]*\\)\\(:\\)" line))
24085             (setq line (replace-match "\\1" nil nil line)))
24086         (insert line "\n"))))
24088     (normal-mode)
24090     ;; insert the table of contents
24091     (when thetoc
24092       (goto-char (point-min))
24093       (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24094           (progn
24095             (goto-char (match-beginning 0))
24096             (replace-match ""))
24097         (goto-char first-heading-pos))
24098       (mapc 'insert thetoc)
24099       (or (looking-at "[ \t]*\n[ \t]*\n")
24100           (insert "\n\n")))
24102     ;; Convert whitespace place holders
24103     (goto-char (point-min))
24104     (let (beg end)
24105       (while (setq beg (next-single-property-change (point) 'org-whitespace))
24106         (setq end (next-single-property-change beg 'org-whitespace))
24107         (goto-char beg)
24108         (delete-region beg end)
24109         (insert (make-string (- end beg) ?\ ))))
24111     (save-buffer)
24112     ;; remove display and invisible chars
24113     (let (beg end)
24114       (goto-char (point-min))
24115       (while (setq beg (next-single-property-change (point) 'display))
24116         (setq end (next-single-property-change beg 'display))
24117         (delete-region beg end)
24118         (goto-char beg)
24119         (insert "=>"))
24120       (goto-char (point-min))
24121       (while (setq beg (next-single-property-change (point) 'org-cwidth))
24122         (setq end (next-single-property-change beg 'org-cwidth))
24123         (delete-region beg end)
24124         (goto-char beg)))
24125     (goto-char (point-min))))
24127 (defun org-export-ascii-clean-string ()
24128   "Do extra work for ASCII export"
24129   (goto-char (point-min))
24130   (while (re-search-forward org-verbatim-re nil t)
24131     (goto-char (match-end 2))
24132     (backward-delete-char 1) (insert "'")
24133     (goto-char (match-beginning 2))
24134     (delete-char 1) (insert "`")
24135     (goto-char (match-end 2))))
24137 (defun org-search-todo-below (line lines level)
24138   "Search the subtree below LINE for any TODO entries."
24139   (let ((rest (cdr (memq line lines)))
24140         (re org-todo-line-regexp)
24141         line lv todo)
24142     (catch 'exit
24143       (while (setq line (pop rest))
24144         (if (string-match re line)
24145             (progn
24146               (setq lv (- (match-end 1) (match-beginning 1))
24147                     todo (and (match-beginning 2)
24148                               (not (member (match-string 2 line)
24149                                           org-done-keywords))))
24150                                         ; TODO, not DONE
24151               (if (<= lv level) (throw 'exit nil))
24152               (if todo (throw 'exit t))))))))
24154 (defun org-html-expand-for-ascii (line)
24155   "Handle quoted HTML for ASCII export."
24156   (if org-export-html-expand
24157       (while (string-match "@<[^<>\n]*>" line)
24158         ;; We just remove the tags for now.
24159         (setq line (replace-match "" nil nil line))))
24160   line)
24162 (defun org-insert-centered (s &optional underline)
24163   "Insert the string S centered and underline it with character UNDERLINE."
24164   (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24165     (insert (make-string ind ?\ ) s "\n")
24166     (if underline
24167         (insert (make-string ind ?\ )
24168                 (make-string (string-width s) underline)
24169                 "\n"))))
24171 (defun org-ascii-level-start (level title umax &optional lines)
24172   "Insert a new level in ASCII export."
24173   (let (char (n (- level umax 1)) (ind 0))
24174     (if (> level umax)
24175         (progn
24176           (insert (make-string (* 2 n) ?\ )
24177                   (char-to-string (nth (% n (length org-export-ascii-bullets))
24178                                        org-export-ascii-bullets))
24179                   " " title "\n")
24180           ;; find the indentation of the next non-empty line
24181           (catch 'stop
24182             (while lines
24183               (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24184               (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24185                   (throw 'stop (setq ind (org-get-indentation (car lines)))))
24186               (pop lines)))
24187           (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24188       (if (or (not (equal (char-before) ?\n))
24189               (not (equal (char-before (1- (point))) ?\n)))
24190           (insert "\n"))
24191       (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24192       (unless org-export-with-tags
24193         (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24194             (setq title (replace-match "" t t title))))
24195       (if org-export-with-section-numbers
24196           (setq title (concat (org-section-number level) " " title)))
24197       (insert title "\n" (make-string (string-width title) char) "\n")
24198       (setq org-ascii-current-indentation '(0 . 0)))))
24200 (defun org-export-visible (type arg)
24201   "Create a copy of the visible part of the current buffer, and export it.
24202 The copy is created in a temporary buffer and removed after use.
24203 TYPE is the final key (as a string) that also select the export command in
24204 the `C-c C-e' export dispatcher.
24205 As a special case, if the you type SPC at the prompt, the temporary
24206 org-mode file will not be removed but presented to you so that you can
24207 continue to use it.  The prefix arg ARG is passed through to the exporting
24208 command."
24209   (interactive
24210    (list (progn
24211            (message "Export visible: [a]SCII  [h]tml  [b]rowse HTML [H/R]uffer with HTML  [x]OXO  [ ]keep buffer")
24212            (read-char-exclusive))
24213          current-prefix-arg))
24214   (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24215       (error "Invalid export key"))
24216   (let* ((binding (cdr (assoc type
24217                               '((?a . org-export-as-ascii)
24218                                 (?\C-a . org-export-as-ascii)
24219                                 (?b . org-export-as-html-and-open)
24220                                 (?\C-b . org-export-as-html-and-open)
24221                                 (?h . org-export-as-html)
24222                                 (?H . org-export-as-html-to-buffer)
24223                                 (?R . org-export-region-as-html)
24224                                 (?x . org-export-as-xoxo)))))
24225          (keepp (equal type ?\ ))
24226          (file buffer-file-name)
24227          (buffer (get-buffer-create "*Org Export Visible*"))
24228          s e)
24229     ;; Need to hack the drawers here.
24230     (save-excursion
24231       (goto-char (point-min))
24232       (while (re-search-forward org-drawer-regexp nil t)
24233         (goto-char (match-beginning 1))
24234         (or (org-invisible-p) (org-flag-drawer nil))))
24235     (with-current-buffer buffer (erase-buffer))
24236     (save-excursion
24237       (setq s (goto-char (point-min)))
24238       (while (not (= (point) (point-max)))
24239         (goto-char (org-find-invisible))
24240         (append-to-buffer buffer s (point))
24241         (setq s (goto-char (org-find-visible))))
24242       (org-cycle-hide-drawers 'all)
24243       (goto-char (point-min))
24244       (unless keepp
24245         ;; Copy all comment lines to the end, to make sure #+ settings are
24246         ;; still available for the second export step.  Kind of a hack, but
24247         ;; does do the trick.
24248         (if (looking-at "#[^\r\n]*")
24249             (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
24250         (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
24251           (append-to-buffer buffer (1+ (match-beginning 0))
24252                             (min (point-max) (1+ (match-end 0))))))
24253       (set-buffer buffer)
24254       (let ((buffer-file-name file)
24255             (org-inhibit-startup t))
24256         (org-mode)
24257         (show-all)
24258         (unless keepp (funcall binding arg))))
24259     (if (not keepp)
24260         (kill-buffer buffer)
24261       (switch-to-buffer-other-window buffer)
24262       (goto-char (point-min)))))
24264 (defun org-find-visible ()
24265   (let ((s (point)))
24266     (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24267                 (get-char-property s 'invisible)))
24268     s))
24269 (defun org-find-invisible ()
24270   (let ((s (point)))
24271     (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24272                 (not (get-char-property s 'invisible))))
24273     s))
24275 ;;; HTML export
24277 (defun org-get-current-options ()
24278   "Return a string with current options as keyword options.
24279 Does include HTML export options as well as TODO and CATEGORY stuff."
24280   (format
24281    "#+TITLE:     %s
24282 #+AUTHOR:    %s
24283 #+EMAIL:     %s
24284 #+LANGUAGE:  %s
24285 #+TEXT:      Some descriptive text to be emitted.  Several lines OK.
24286 #+OPTIONS:   H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s -:%s f:%s *:%s TeX:%s LaTeX:%s skip:%s d:%s tags:%s
24287 #+CATEGORY:  %s
24288 #+SEQ_TODO:  %s
24289 #+TYP_TODO:  %s
24290 #+PRIORITIES: %c %c %c
24291 #+DRAWERS:   %s
24292 #+STARTUP:   %s %s %s %s %s
24293 #+TAGS:      %s
24294 #+ARCHIVE:   %s
24295 #+LINK:      %s
24297    (buffer-name) (user-full-name) user-mail-address org-export-default-language
24298    org-export-headline-levels
24299    org-export-with-section-numbers
24300    org-export-with-toc
24301    org-export-preserve-breaks
24302    org-export-html-expand
24303    org-export-with-fixed-width
24304    org-export-with-tables
24305    org-export-with-sub-superscripts
24306    org-export-with-special-strings
24307    org-export-with-footnotes
24308    org-export-with-emphasize
24309    org-export-with-TeX-macros
24310    org-export-with-LaTeX-fragments
24311    org-export-skip-text-before-1st-heading
24312    org-export-with-drawers
24313    org-export-with-tags
24314    (file-name-nondirectory buffer-file-name)
24315    "TODO FEEDBACK VERIFY DONE"
24316    "Me Jason Marie DONE"
24317    org-highest-priority org-lowest-priority org-default-priority
24318    (mapconcat 'identity org-drawers " ")
24319    (cdr (assoc org-startup-folded
24320                '((nil . "showall") (t . "overview") (content . "content"))))
24321    (if org-odd-levels-only "odd" "oddeven")
24322    (if org-hide-leading-stars "hidestars" "showstars")
24323    (if org-startup-align-all-tables "align" "noalign")
24324    (cond ((eq t org-log-done) "logdone")
24325          ((not org-log-done) "nologging")
24326          ((listp org-log-done)
24327           (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
24328                      org-log-done " ")))
24329    (or (mapconcat (lambda (x)
24330                     (cond
24331                      ((equal '(:startgroup) x) "{")
24332                      ((equal '(:endgroup) x) "}")
24333                      ((cdr x) (format "%s(%c)" (car x) (cdr x)))
24334                      (t (car x))))
24335                   (or org-tag-alist (org-get-buffer-tags)) " ") "")
24336    org-archive-location
24337    "org file:~/org/%s.org"
24338    ))
24340 (defun org-insert-export-options-template ()
24341   "Insert into the buffer a template with information for exporting."
24342   (interactive)
24343   (if (not (bolp)) (newline))
24344   (let ((s (org-get-current-options)))
24345     (and (string-match "#\\+CATEGORY" s)
24346          (setq s (substring s 0 (match-beginning 0))))
24347     (insert s)))
24349 (defun org-toggle-fixed-width-section (arg)
24350   "Toggle the fixed-width export.
24351 If there is no active region, the QUOTE keyword at the current headline is
24352 inserted or removed.  When present, it causes the text between this headline
24353 and the next to be exported as fixed-width text, and unmodified.
24354 If there is an active region, this command adds or removes a colon as the
24355 first character of this line.  If the first character of a line is a colon,
24356 this line is also exported in fixed-width font."
24357   (interactive "P")
24358   (let* ((cc 0)
24359          (regionp (org-region-active-p))
24360          (beg (if regionp (region-beginning) (point)))
24361          (end (if regionp (region-end)))
24362          (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
24363          (case-fold-search nil)
24364          (re "[ \t]*\\(:\\)")
24365          off)
24366     (if regionp
24367         (save-excursion
24368           (goto-char beg)
24369           (setq cc (current-column))
24370           (beginning-of-line 1)
24371           (setq off (looking-at re))
24372           (while (> nlines 0)
24373             (setq nlines (1- nlines))
24374             (beginning-of-line 1)
24375             (cond
24376              (arg
24377               (move-to-column cc t)
24378               (insert ":\n")
24379               (forward-line -1))
24380              ((and off (looking-at re))
24381               (replace-match "" t t nil 1))
24382              ((not off) (move-to-column cc t) (insert ":")))
24383             (forward-line 1)))
24384       (save-excursion
24385         (org-back-to-heading)
24386         (if (looking-at (concat outline-regexp
24387                                 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
24388             (replace-match "" t t nil 1)
24389           (if (looking-at outline-regexp)
24390               (progn
24391                 (goto-char (match-end 0))
24392                 (insert org-quote-string " "))))))))
24394 (defun org-export-as-html-and-open (arg)
24395   "Export the outline as HTML and immediately open it with a browser.
24396 If there is an active region, export only the region.
24397 The prefix ARG specifies how many levels of the outline should become
24398 headlines.  The default is 3.  Lower levels will become bulleted lists."
24399   (interactive "P")
24400   (org-export-as-html arg 'hidden)
24401   (org-open-file buffer-file-name))
24403 (defun org-export-as-html-batch ()
24404   "Call `org-export-as-html', may be used in batch processing as
24405 emacs   --batch
24406         --load=$HOME/lib/emacs/org.el
24407         --eval \"(setq org-export-headline-levels 2)\"
24408         --visit=MyFile --funcall org-export-as-html-batch"
24409   (org-export-as-html org-export-headline-levels 'hidden))
24411 (defun org-export-as-html-to-buffer (arg)
24412   "Call `org-exort-as-html` with output to a temporary buffer.
24413 No file is created.  The prefix ARG is passed through to `org-export-as-html'."
24414   (interactive "P")
24415   (org-export-as-html arg nil nil "*Org HTML Export*")
24416   (switch-to-buffer-other-window "*Org HTML Export*"))
24418 (defun org-replace-region-by-html (beg end)
24419   "Assume the current region has org-mode syntax, and convert it to HTML.
24420 This can be used in any buffer.  For example, you could write an
24421 itemized list in org-mode syntax in an HTML buffer and then use this
24422 command to convert it."
24423   (interactive "r")
24424   (let (reg html buf pop-up-frames)
24425     (save-window-excursion
24426       (if (org-mode-p)
24427           (setq html (org-export-region-as-html
24428                       beg end t 'string))
24429         (setq reg (buffer-substring beg end)
24430               buf (get-buffer-create "*Org tmp*"))
24431         (with-current-buffer buf
24432           (erase-buffer)
24433           (insert reg)
24434           (org-mode)
24435           (setq html (org-export-region-as-html
24436                       (point-min) (point-max) t 'string)))
24437         (kill-buffer buf)))
24438     (delete-region beg end)
24439     (insert html)))
24441 (defun org-export-region-as-html (beg end &optional body-only buffer)
24442   "Convert region from BEG to END in org-mode buffer to HTML.
24443 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
24444 contents, and only produce the region of converted text, useful for
24445 cut-and-paste operations.
24446 If BUFFER is a buffer or a string, use/create that buffer as a target
24447 of the converted HTML.  If BUFFER is the symbol `string', return the
24448 produced HTML as a string and leave not buffer behind.  For example,
24449 a Lisp program could call this function in the following way:
24451   (setq html (org-export-region-as-html beg end t 'string))
24453 When called interactively, the output buffer is selected, and shown
24454 in a window.  A non-interactive call will only retunr the buffer."
24455   (interactive "r\nP")
24456   (when (interactive-p)
24457     (setq buffer "*Org HTML Export*"))
24458   (let ((transient-mark-mode t) (zmacs-regions t)
24459         rtn)
24460     (goto-char end)
24461     (set-mark (point)) ;; to activate the region
24462     (goto-char beg)
24463     (setq rtn (org-export-as-html
24464                nil nil nil
24465                buffer body-only))
24466     (if (fboundp 'deactivate-mark) (deactivate-mark))
24467     (if (and (interactive-p) (bufferp rtn))
24468         (switch-to-buffer-other-window rtn)
24469       rtn)))
24471 (defvar html-table-tag nil) ; dynamically scoped into this.
24472 (defun org-export-as-html (arg &optional hidden ext-plist
24473                                to-buffer body-only)
24474   "Export the outline as a pretty HTML file.
24475 If there is an active region, export only the region.  The prefix
24476 ARG specifies how many levels of the outline should become
24477 headlines.  The default is 3.  Lower levels will become bulleted
24478 lists.  When HIDDEN is non-nil, don't display the HTML buffer.
24479 EXT-PLIST is a property list with external parameters overriding
24480 org-mode's default settings, but still inferior to file-local
24481 settings.  When TO-BUFFER is non-nil, create a buffer with that
24482 name and export to that buffer.  If TO-BUFFER is the symbol `string',
24483 don't leave any buffer behind but just return the resulting HTML as
24484 a string.  When BODY-ONLY is set, don't produce the file header and footer,
24485 simply return the content of <body>...</body>, without even
24486 the body tags themselves."
24487   (interactive "P")
24489   ;; Make sure we have a file name when we need it.
24490   (when (and (not (or to-buffer body-only))
24491              (not buffer-file-name))
24492     (if (buffer-base-buffer)
24493         (org-set-local 'buffer-file-name
24494                        (with-current-buffer (buffer-base-buffer)
24495                          buffer-file-name))
24496       (error "Need a file name to be able to export.")))
24498   (message "Exporting...")
24499   (setq-default org-todo-line-regexp org-todo-line-regexp)
24500   (setq-default org-deadline-line-regexp org-deadline-line-regexp)
24501   (setq-default org-done-keywords org-done-keywords)
24502   (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
24503   (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24504                                         ext-plist
24505                                         (org-infile-export-plist)))
24507          (style (plist-get opt-plist :style))
24508          (link-validate (plist-get opt-plist :link-validation-function))
24509          valid thetoc have-headings first-heading-pos
24510          (odd org-odd-levels-only)
24511          (region-p (org-region-active-p))
24512          (subtree-p
24513           (when region-p
24514             (save-excursion
24515               (goto-char (region-beginning))
24516               (and (org-at-heading-p)
24517                    (>= (org-end-of-subtree t t) (region-end))))))
24518          ;; The following two are dynamically scoped into other
24519          ;; routines below.
24520          (org-current-export-dir (org-export-directory :html opt-plist))
24521          (org-current-export-file buffer-file-name)
24522          (level 0) (line "") (origline "") txt todo
24523          (umax nil)
24524          (umax-toc nil)
24525          (filename (if to-buffer nil
24526                      (expand-file-name
24527                       (concat
24528                        (file-name-sans-extension
24529                         (or (and subtree-p
24530                                  (org-entry-get (region-beginning)
24531                                                 "EXPORT_FILE_NAME" t))
24532                             (file-name-nondirectory buffer-file-name)))
24533                        "." org-export-html-extension)
24534                       (file-name-as-directory
24535                        (org-export-directory :html opt-plist)))))
24536          (current-dir (if buffer-file-name
24537                           (file-name-directory buffer-file-name)
24538                         default-directory))
24539          (buffer (if to-buffer
24540                      (cond
24541                       ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
24542                       (t (get-buffer-create to-buffer)))
24543                    (find-file-noselect filename)))
24544          (org-levels-open (make-vector org-level-max nil))
24545          (date (plist-get opt-plist :date))
24546          (author      (plist-get opt-plist :author))
24547          (title       (or (and subtree-p (org-export-get-title-from-subtree))
24548                           (plist-get opt-plist :title)
24549                           (and (not
24550                                 (plist-get opt-plist :skip-before-1st-heading))
24551                                (org-export-grab-title-from-buffer))
24552                           (and buffer-file-name
24553                                (file-name-sans-extension
24554                                 (file-name-nondirectory buffer-file-name)))
24555                           "UNTITLED"))
24556          (html-table-tag (plist-get opt-plist :html-table-tag))
24557          (quote-re0   (concat "^[ \t]*" org-quote-string "\\>"))
24558          (quote-re    (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
24559          (inquote     nil)
24560          (infixed     nil)
24561          (in-local-list nil)
24562          (local-list-num nil)
24563          (local-list-indent nil)
24564          (llt org-plain-list-ordered-item-terminator)
24565          (email       (plist-get opt-plist :email))
24566          (language    (plist-get opt-plist :language))
24567          (lang-words  nil)
24568          (target-alist nil) tg
24569          (head-count  0) cnt
24570          (start       0)
24571          (coding-system (and (boundp 'buffer-file-coding-system)
24572                              buffer-file-coding-system))
24573          (coding-system-for-write (or org-export-html-coding-system
24574                                       coding-system))
24575          (save-buffer-coding-system (or org-export-html-coding-system
24576                                         coding-system))
24577          (charset (and coding-system-for-write
24578                        (fboundp 'coding-system-get)
24579                        (coding-system-get coding-system-for-write
24580                                           'mime-charset)))
24581          (region
24582           (buffer-substring
24583            (if region-p (region-beginning) (point-min))
24584            (if region-p (region-end) (point-max))))
24585          (lines
24586           (org-split-string
24587            (org-cleaned-string-for-export
24588             region
24589             :emph-multiline t
24590             :for-html t
24591             :skip-before-1st-heading
24592             (plist-get opt-plist :skip-before-1st-heading)
24593             :drawers (plist-get opt-plist :drawers)
24594             :archived-trees
24595             (plist-get opt-plist :archived-trees)
24596             :add-text
24597             (plist-get opt-plist :text)
24598             :LaTeX-fragments
24599             (plist-get opt-plist :LaTeX-fragments))
24600            "[\r\n]"))
24601          table-open type
24602          table-buffer table-orig-buffer
24603          ind start-is-num starter didclose
24604          rpl path desc descp desc1 desc2 link
24605          )
24607     (let ((inhibit-read-only t))
24608       (org-unmodified
24609        (remove-text-properties (point-min) (point-max)
24610                                '(:org-license-to-kill t))))
24612     (message "Exporting...")
24614     (setq org-min-level (org-get-min-level lines))
24615     (setq org-last-level org-min-level)
24616     (org-init-section-numbers)
24618     (cond
24619      ((and date (string-match "%" date))
24620       (setq date (format-time-string date (current-time))))
24621      (date)
24622      (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24624     ;; Get the language-dependent settings
24625     (setq lang-words (or (assoc language org-export-language-setup)
24626                          (assoc "en" org-export-language-setup)))
24628     ;; Switch to the output buffer
24629     (set-buffer buffer)
24630     (erase-buffer)
24631     (fundamental-mode)
24633     (and (fboundp 'set-buffer-file-coding-system)
24634          (set-buffer-file-coding-system coding-system-for-write))
24636     (let ((case-fold-search nil)
24637           (org-odd-levels-only odd))
24638       ;; create local variables for all options, to make sure all called
24639       ;; functions get the correct information
24640       (mapc (lambda (x)
24641               (set (make-local-variable (cdr x))
24642                    (plist-get opt-plist (car x))))
24643             org-export-plist-vars)
24644       (setq umax (if arg (prefix-numeric-value arg)
24645                    org-export-headline-levels))
24646       (setq umax-toc (if (integerp org-export-with-toc)
24647                          (min org-export-with-toc umax)
24648                        umax))
24649       (unless body-only
24650         ;; File header
24651         (insert (format
24652                  "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
24653                \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
24654 <html xmlns=\"http://www.w3.org/1999/xhtml\"
24655 lang=\"%s\" xml:lang=\"%s\">
24656 <head>
24657 <title>%s</title>
24658 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
24659 <meta name=\"generator\" content=\"Org-mode\"/>
24660 <meta name=\"generated\" content=\"%s\"/>
24661 <meta name=\"author\" content=\"%s\"/>
24663 </head><body>
24665                  language language (org-html-expand title)
24666                  (or charset "iso-8859-1") date author style))
24668         (insert (or (plist-get opt-plist :preamble) ""))
24670         (when (plist-get opt-plist :auto-preamble)
24671           (if title (insert (format org-export-html-title-format
24672                                     (org-html-expand title))))))
24674       (if (and org-export-with-toc (not body-only))
24675           (progn
24676             (push (format "<h%d>%s</h%d>\n"
24677                           org-export-html-toplevel-hlevel
24678                           (nth 3 lang-words)
24679                           org-export-html-toplevel-hlevel)
24680                   thetoc)
24681             (push "<ul>\n<li>" thetoc)
24682             (setq lines
24683                   (mapcar '(lambda (line)
24684                     (if (string-match org-todo-line-regexp line)
24685                         ;; This is a headline
24686                         (progn
24687                           (setq have-headings t)
24688                           (setq level (- (match-end 1) (match-beginning 1))
24689                                 level (org-tr-level level)
24690                                 txt (save-match-data
24691                                       (org-html-expand
24692                                        (org-export-cleanup-toc-line
24693                                         (match-string 3 line))))
24694                                 todo
24695                                 (or (and org-export-mark-todo-in-toc
24696                                          (match-beginning 2)
24697                                          (not (member (match-string 2 line)
24698                                                       org-done-keywords)))
24699                                         ; TODO, not DONE
24700                                     (and org-export-mark-todo-in-toc
24701                                          (= level umax-toc)
24702                                          (org-search-todo-below
24703                                           line lines level))))
24704                           (if (string-match
24705                                (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
24706                               (setq txt (replace-match  "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
24707                           (if (string-match quote-re0 txt)
24708                               (setq txt (replace-match "" t t txt)))
24709                           (if org-export-with-section-numbers
24710                               (setq txt (concat (org-section-number level)
24711                                                 " " txt)))
24712                           (if (<= level (max umax umax-toc))
24713                               (setq head-count (+ head-count 1)))
24714                           (if (<= level umax-toc)
24715                               (progn
24716                                 (if (> level org-last-level)
24717                                     (progn
24718                                       (setq cnt (- level org-last-level))
24719                                       (while (>= (setq cnt (1- cnt)) 0)
24720                                         (push "\n<ul>\n<li>" thetoc))
24721                                       (push "\n" thetoc)))
24722                                 (if (< level org-last-level)
24723                                     (progn
24724                                       (setq cnt (- org-last-level level))
24725                                       (while (>= (setq cnt (1- cnt)) 0)
24726                                         (push "</li>\n</ul>" thetoc))
24727                                       (push "\n" thetoc)))
24728                                 ;; Check for targets
24729                                 (while (string-match org-target-regexp line)
24730                                   (setq tg (match-string 1 line)
24731                                         line (replace-match
24732                                               (concat "@<span class=\"target\">" tg "@</span> ")
24733                                               t t line))
24734                                   (push (cons (org-solidify-link-text tg)
24735                                               (format "sec-%d" head-count))
24736                                         target-alist))
24737                                 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
24738                                   (setq txt (replace-match "" t t txt)))
24739                                 (push
24740                                  (format
24741                                   (if todo
24742                                       "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
24743                                     "</li>\n<li><a href=\"#sec-%d\">%s</a>")
24744                                   head-count txt) thetoc)
24746                                 (setq org-last-level level))
24747                             )))
24748                     line)
24749                           lines))
24750             (while (> org-last-level (1- org-min-level))
24751               (setq org-last-level (1- org-last-level))
24752               (push "</li>\n</ul>\n" thetoc))
24753             (setq thetoc (if have-headings (nreverse thetoc) nil))))
24755       (setq head-count 0)
24756       (org-init-section-numbers)
24758       (while (setq line (pop lines) origline line)
24759         (catch 'nextline
24761           ;; end of quote section?
24762           (when (and inquote (string-match "^\\*+ " line))
24763             (insert "</pre>\n")
24764             (setq inquote nil))
24765           ;; inside a quote section?
24766           (when inquote
24767             (insert (org-html-protect line) "\n")
24768             (throw 'nextline nil))
24770           ;; verbatim lines
24771           (when (and org-export-with-fixed-width
24772                      (string-match "^[ \t]*:\\(.*\\)" line))
24773             (when (not infixed)
24774               (setq infixed t)
24775               (insert "<pre>\n"))
24776             (insert (org-html-protect (match-string 1 line)) "\n")
24777             (when (and lines
24778                        (not (string-match "^[ \t]*\\(:.*\\)"
24779                                           (car lines))))
24780               (setq infixed nil)
24781               (insert "</pre>\n"))
24782             (throw 'nextline nil))
24784           ;; Protected HTML
24785           (when (get-text-property 0 'org-protected line)
24786             (let (par)
24787               (when (re-search-backward
24788                      "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
24789                 (setq par (match-string 1))
24790                 (replace-match "\\2\n"))
24791               (insert line "\n")
24792               (while (and lines
24793                           (or (= (length (car lines)) 0)
24794                               (get-text-property 0 'org-protected (car lines))))
24795                 (insert (pop lines) "\n"))
24796               (and par (insert "<p>\n")))
24797             (throw 'nextline nil))
24799           ;; Horizontal line
24800           (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
24801             (insert "\n<hr/>\n")
24802             (throw 'nextline nil))
24804           ;; make targets to anchors
24805           (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
24806             (cond
24807              ((match-end 2)
24808               (setq line (replace-match
24809                           (concat "@<a name=\""
24810                                   (org-solidify-link-text (match-string 1 line))
24811                                   "\">\\nbsp@</a>")
24812                           t t line)))
24813              ((and org-export-with-toc (equal (string-to-char line) ?*))
24814               (setq line (replace-match
24815                           (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
24816 ;                         (concat "@<i>" (match-string 1 line) "@</i> ")
24817                           t t line)))
24818              (t
24819               (setq line (replace-match
24820                           (concat "@<a name=\""
24821                                   (org-solidify-link-text (match-string 1 line))
24822                                   "\" class=\"target\">" (match-string 1 line) "@</a> ")
24823                           t t line)))))
24825           (setq line (org-html-handle-time-stamps line))
24827           ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
24828           ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
24829           ;; Also handle sub_superscripts and checkboxes
24830           (or (string-match org-table-hline-regexp line)
24831               (setq line (org-html-expand line)))
24833           ;; Format the links
24834           (setq start 0)
24835           (while (string-match org-bracket-link-analytic-regexp line start)
24836             (setq start (match-beginning 0))
24837             (setq type (if (match-end 2) (match-string 2 line) "internal"))
24838             (setq path (match-string 3 line))
24839             (setq desc1 (if (match-end 5) (match-string 5 line))
24840                   desc2 (if (match-end 2) (concat type ":" path) path)
24841                   descp (and desc1 (not (equal desc1 desc2)))
24842                   desc (or desc1 desc2))
24843             ;; Make an image out of the description if that is so wanted
24844             (when (and descp (org-file-image-p desc))
24845               (save-match-data
24846                 (if (string-match "^file:" desc)
24847                     (setq desc (substring desc (match-end 0)))))
24848               (setq desc (concat "<img src=\"" desc "\"/>")))
24849             ;; FIXME: do we need to unescape here somewhere?
24850             (cond
24851              ((equal type "internal")
24852               (setq rpl
24853                     (concat
24854                      "<a href=\"#"
24855                      (org-solidify-link-text
24856                       (save-match-data (org-link-unescape path)) target-alist)
24857                      "\">" desc "</a>")))
24858              ((member type '("http" "https"))
24859               ;; standard URL, just check if we need to inline an image
24860               (if (and (or (eq t org-export-html-inline-images)
24861                            (and org-export-html-inline-images (not descp)))
24862                        (org-file-image-p path))
24863                   (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
24864                 (setq link (concat type ":" path))
24865                 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
24866              ((member type '("ftp" "mailto" "news"))
24867               ;; standard URL
24868               (setq link (concat type ":" path))
24869               (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
24870              ((string= type "file")
24871               ;; FILE link
24872               (let* ((filename path)
24873                      (abs-p (file-name-absolute-p filename))
24874                      thefile file-is-image-p search)
24875                 (save-match-data
24876                   (if (string-match "::\\(.*\\)" filename)
24877                       (setq search (match-string 1 filename)
24878                             filename (replace-match "" t nil filename)))
24879                   (setq valid
24880                         (if (functionp link-validate)
24881                             (funcall link-validate filename current-dir)
24882                           t))
24883                   (setq file-is-image-p (org-file-image-p filename))
24884                   (setq thefile (if abs-p (expand-file-name filename) filename))
24885                   (when (and org-export-html-link-org-files-as-html
24886                              (string-match "\\.org$" thefile))
24887                     (setq thefile (concat (substring thefile 0
24888                                                      (match-beginning 0))
24889                                           "." org-export-html-extension))
24890                     (if (and search
24891                              ;; make sure this is can be used as target search
24892                              (not (string-match "^[0-9]*$" search))
24893                              (not (string-match "^\\*" search))
24894                              (not (string-match "^/.*/$" search)))
24895                         (setq thefile (concat thefile "#"
24896                                               (org-solidify-link-text
24897                                                (org-link-unescape search)))))
24898                     (when (string-match "^file:" desc)
24899                       (setq desc (replace-match "" t t desc))
24900                       (if (string-match "\\.org$" desc)
24901                           (setq desc (replace-match "" t t desc))))))
24902                 (setq rpl (if (and file-is-image-p
24903                                    (or (eq t org-export-html-inline-images)
24904                                        (and org-export-html-inline-images
24905                                             (not descp))))
24906                               (concat "<img src=\"" thefile "\"/>")
24907                             (concat "<a href=\"" thefile "\">" desc "</a>")))
24908                 (if (not valid) (setq rpl desc))))
24909              ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
24910               (setq rpl (concat "<i>&lt;" type ":"
24911                                 (save-match-data (org-link-unescape path))
24912                                 "&gt;</i>"))))
24913             (setq line (replace-match rpl t t line)
24914                   start (+ start (length rpl))))
24916           ;; TODO items
24917           (if (and (string-match org-todo-line-regexp line)
24918                    (match-beginning 2))
24920               (setq line
24921                     (concat (substring line 0 (match-beginning 2))
24922                             "<span class=\""
24923                             (if (member (match-string 2 line)
24924                                         org-done-keywords)
24925                                 "done" "todo")
24926                             "\">" (match-string 2 line)
24927                             "</span>" (substring line (match-end 2)))))
24929           ;; Does this contain a reference to a footnote?
24930           (when org-export-with-footnotes
24931             (setq start 0)
24932             (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
24933               (if (get-text-property (match-beginning 2) 'org-protected line)
24934                   (setq start (match-end 2))
24935                 (let ((n (match-string 2 line)))
24936                   (setq line
24937                         (replace-match
24938                          (format
24939                           "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
24940                           (match-string 1 line) n n n)
24941                          t t line))))))
24943           (cond
24944            ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24945             ;; This is a headline
24946             (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24947                   txt (match-string 2 line))
24948             (if (string-match quote-re0 txt)
24949                 (setq txt (replace-match "" t t txt)))
24950             (if (<= level (max umax umax-toc))
24951                 (setq head-count (+ head-count 1)))
24952             (when in-local-list
24953               ;; Close any local lists before inserting a new header line
24954               (while local-list-num
24955                 (org-close-li)
24956                 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
24957                 (pop local-list-num))
24958               (setq local-list-indent nil
24959                     in-local-list nil))
24960             (setq first-heading-pos (or first-heading-pos (point)))
24961             (org-html-level-start level txt umax
24962                                   (and org-export-with-toc (<= level umax))
24963                                   head-count)
24964             ;; QUOTES
24965             (when (string-match quote-re line)
24966               (insert "<pre>")
24967               (setq inquote t)))
24969            ((and org-export-with-tables
24970                  (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24971             (if (not table-open)
24972                 ;; New table starts
24973                 (setq table-open t table-buffer nil table-orig-buffer nil))
24974             ;; Accumulate lines
24975             (setq table-buffer (cons line table-buffer)
24976                   table-orig-buffer (cons origline table-orig-buffer))
24977             (when (or (not lines)
24978                       (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24979                                          (car lines))))
24980               (setq table-open nil
24981                     table-buffer (nreverse table-buffer)
24982                     table-orig-buffer (nreverse table-orig-buffer))
24983               (org-close-par-maybe)
24984               (insert (org-format-table-html table-buffer table-orig-buffer))))
24985            (t
24986             ;; Normal lines
24987             (when (string-match
24988                    (cond
24989                     ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
24990                     ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
24991                     ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
24992                     (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
24993                    line)
24994               (setq ind (org-get-string-indentation line)
24995                     start-is-num (match-beginning 4)
24996                     starter (if (match-beginning 2)
24997                                 (substring (match-string 2 line) 0 -1))
24998                     line (substring line (match-beginning 5)))
24999               (unless (string-match "[^ \t]" line)
25000                 ;; empty line.  Pretend indentation is large.
25001                 (setq ind (if org-empty-line-terminates-plain-lists
25002                               0
25003                             (1+ (or (car local-list-indent) 1)))))
25004               (setq didclose nil)
25005               (while (and in-local-list
25006                           (or (and (= ind (car local-list-indent))
25007                                    (not starter))
25008                               (< ind (car local-list-indent))))
25009                 (setq didclose t)
25010                 (org-close-li)
25011                 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25012                 (pop local-list-num) (pop local-list-indent)
25013                 (setq in-local-list local-list-indent))
25014               (cond
25015                ((and starter
25016                      (or (not in-local-list)
25017                          (> ind (car local-list-indent))))
25018                 ;; Start new (level of) list
25019                 (org-close-par-maybe)
25020                 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25021                 (push start-is-num local-list-num)
25022                 (push ind local-list-indent)
25023                 (setq in-local-list t))
25024                (starter
25025                 ;; continue current list
25026                 (org-close-li)
25027                 (insert "<li>\n"))
25028                (didclose
25029                 ;; we did close a list, normal text follows: need <p>
25030                 (org-open-par)))
25031               (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25032                   (setq line
25033                         (replace-match
25034                          (if (equal (match-string 1 line) "X")
25035                              "<b>[X]</b>"
25036                            "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25037                            t t line))))
25039             ;; Empty lines start a new paragraph.  If hand-formatted lists
25040             ;; are not fully interpreted, lines starting with "-", "+", "*"
25041             ;; also start a new paragraph.
25042             (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25044             ;; Is this the start of a footnote?
25045             (when org-export-with-footnotes
25046               (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25047                 (org-close-par-maybe)
25048                 (let ((n (match-string 1 line)))
25049                   (setq line (replace-match
25050                               (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25052             ;; Check if the line break needs to be conserved
25053             (cond
25054              ((string-match "\\\\\\\\[ \t]*$" line)
25055               (setq line (replace-match "<br/>" t t line)))
25056              (org-export-preserve-breaks
25057               (setq line (concat line "<br/>"))))
25059             (insert line "\n")))))
25061       ;; Properly close all local lists and other lists
25062       (when inquote (insert "</pre>\n"))
25063       (when in-local-list
25064         ;; Close any local lists before inserting a new header line
25065         (while local-list-num
25066           (org-close-li)
25067           (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25068           (pop local-list-num))
25069         (setq local-list-indent nil
25070               in-local-list nil))
25071       (org-html-level-start 1 nil umax
25072                             (and org-export-with-toc (<= level umax))
25073                             head-count)
25075       (unless body-only
25076         (when (plist-get opt-plist :auto-postamble)
25077           (insert "<div id=\"postamble\">")
25078           (when (and org-export-author-info author)
25079             (insert "<p class=\"author\"> "
25080                     (nth 1 lang-words) ": " author "\n")
25081             (when email
25082               (if (listp (split-string email ",+ *"))
25083                   (mapc (lambda(e)
25084                           (insert "<a href=\"mailto:" e "\">&lt;"
25085                                   e "&gt;</a>\n"))
25086                         (split-string email ",+ *"))
25087                 (insert "<a href=\"mailto:" email "\">&lt;"
25088                         email "&gt;</a>\n")))
25089             (insert "</p>\n"))
25090           (when (and date org-export-time-stamp-file)
25091             (insert "<p class=\"date\"> "
25092                     (nth 2 lang-words) ": "
25093                     date "</p>\n"))
25094           (insert "</div>"))
25096         (if org-export-html-with-timestamp
25097             (insert org-export-html-html-helper-timestamp))
25098         (insert (or (plist-get opt-plist :postamble) ""))
25099         (insert "</body>\n</html>\n"))
25101       (normal-mode)
25102       (if (eq major-mode default-major-mode) (html-mode))
25104       ;; insert the table of contents
25105       (goto-char (point-min))
25106       (when thetoc
25107         (if (or (re-search-forward
25108                  "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25109                 (re-search-forward
25110                  "\\[TABLE-OF-CONTENTS\\]" nil t))
25111             (progn
25112               (goto-char (match-beginning 0))
25113               (replace-match ""))
25114           (goto-char first-heading-pos)
25115           (when (looking-at "\\s-*</p>")
25116             (goto-char (match-end 0))
25117             (insert "\n")))
25118         (insert "<div id=\"table-of-contents\">\n")
25119         (mapc 'insert thetoc)
25120         (insert "</div>\n"))
25121       ;; remove empty paragraphs and lists
25122       (goto-char (point-min))
25123       (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25124         (replace-match ""))
25125       (goto-char (point-min))
25126       (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25127         (replace-match ""))
25128       ;; Convert whitespace place holders
25129       (goto-char (point-min))
25130       (let (beg end n)
25131         (while (setq beg (next-single-property-change (point) 'org-whitespace))
25132           (setq n (get-text-property beg 'org-whitespace)
25133                 end (next-single-property-change beg 'org-whitespace))
25134           (goto-char beg)
25135           (delete-region beg end)
25136           (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25137                           (make-string n ?x)))))
25139       (or to-buffer (save-buffer))
25140       (goto-char (point-min))
25141       (message "Exporting... done")
25142       (if (eq to-buffer 'string)
25143           (prog1 (buffer-substring (point-min) (point-max))
25144             (kill-buffer (current-buffer)))
25145         (current-buffer)))))
25147 (defvar org-table-colgroup-info nil)
25148 (defun org-format-table-ascii (lines)
25149   "Format a table for ascii export."
25150   (if (stringp lines)
25151       (setq lines (org-split-string lines "\n")))
25152   (if (not (string-match "^[ \t]*|" (car lines)))
25153       ;; Table made by table.el - test for spanning
25154       lines
25156     ;; A normal org table
25157     ;; Get rid of hlines at beginning and end
25158     (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25159     (setq lines (nreverse lines))
25160     (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25161     (setq lines (nreverse lines))
25162     (when org-export-table-remove-special-lines
25163       ;; Check if the table has a marking column.  If yes remove the
25164       ;; column and the special lines
25165       (setq lines (org-table-clean-before-export lines)))
25166     ;; Get rid of the vertical lines except for grouping
25167     (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25168           rtn line vl1 start)
25169       (while (setq line (pop lines))
25170         (if (string-match org-table-hline-regexp line)
25171             (and (string-match "|\\(.*\\)|" line)
25172                  (setq line (replace-match " \\1" t nil line)))
25173           (setq start 0 vl1 vl)
25174           (while (string-match "|" line start)
25175             (setq start (match-end 0))
25176             (or (pop vl1) (setq line (replace-match " " t t line)))))
25177         (push line rtn))
25178       (nreverse rtn))))
25180 (defun org-colgroup-info-to-vline-list (info)
25181   (let (vl new last)
25182     (while info
25183       (setq last new new (pop info))
25184       (if (or (memq last '(:end :startend))
25185               (memq new  '(:start :startend)))
25186           (push t vl)
25187         (push nil vl)))
25188     (setq vl (nreverse vl))
25189     (and vl (setcar vl nil))
25190     vl))
25192 (defun org-format-table-html (lines olines)
25193   "Find out which HTML converter to use and return the HTML code."
25194   (if (stringp lines)
25195       (setq lines (org-split-string lines "\n")))
25196   (if (string-match "^[ \t]*|" (car lines))
25197       ;; A normal org table
25198       (org-format-org-table-html lines)
25199     ;; Table made by table.el - test for spanning
25200     (let* ((hlines (delq nil (mapcar
25201                               (lambda (x)
25202                                 (if (string-match "^[ \t]*\\+-" x) x
25203                                   nil))
25204                               lines)))
25205            (first (car hlines))
25206            (ll (and (string-match "\\S-+" first)
25207                     (match-string 0 first)))
25208            (re (concat "^[ \t]*" (regexp-quote ll)))
25209            (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25210                                        hlines))))
25211       (if (and (not spanning)
25212                (not org-export-prefer-native-exporter-for-tables))
25213           ;; We can use my own converter with HTML conversions
25214           (org-format-table-table-html lines)
25215         ;; Need to use the code generator in table.el, with the original text.
25216         (org-format-table-table-html-using-table-generate-source olines)))))
25218 (defun org-format-org-table-html (lines &optional splice)
25219   "Format a table into HTML."
25220   ;; Get rid of hlines at beginning and end
25221   (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25222   (setq lines (nreverse lines))
25223   (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25224   (setq lines (nreverse lines))
25225   (when org-export-table-remove-special-lines
25226     ;; Check if the table has a marking column.  If yes remove the
25227     ;; column and the special lines
25228     (setq lines (org-table-clean-before-export lines)))
25230   (let ((head (and org-export-highlight-first-table-line
25231                    (delq nil (mapcar
25232                               (lambda (x) (string-match "^[ \t]*|-" x))
25233                               (cdr lines)))))
25234         (nlines 0) fnum i
25235         tbopen line fields html gr colgropen)
25236     (if splice (setq head nil))
25237     (unless splice (push (if head "<thead>" "<tbody>") html))
25238     (setq tbopen t)
25239     (while (setq line (pop lines))
25240       (catch 'next-line
25241         (if (string-match "^[ \t]*|-" line)
25242             (progn
25243               (unless splice
25244                 (push (if head "</thead>" "</tbody>") html)
25245                 (if lines (push "<tbody>" html) (setq tbopen nil)))
25246               (setq head nil)   ;; head ends here, first time around
25247               ;; ignore this line
25248               (throw 'next-line t)))
25249         ;; Break the line into fields
25250         (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25251         (unless fnum (setq fnum (make-vector (length fields) 0)))
25252         (setq nlines (1+ nlines) i -1)
25253         (push (concat "<tr>"
25254                       (mapconcat
25255                        (lambda (x)
25256                          (setq i (1+ i))
25257                          (if (and (< i nlines)
25258                                   (string-match org-table-number-regexp x))
25259                              (incf (aref fnum i)))
25260                          (if head
25261                              (concat (car org-export-table-header-tags) x
25262                                      (cdr org-export-table-header-tags))
25263                            (concat (car org-export-table-data-tags) x
25264                                    (cdr org-export-table-data-tags))))
25265                        fields "")
25266                       "</tr>")
25267               html)))
25268     (unless splice (if tbopen (push "</tbody>" html)))
25269     (unless splice (push "</table>\n" html))
25270     (setq html (nreverse html))
25271     (unless splice
25272       ;; Put in col tags with the alignment (unfortuntely often ignored...)
25273       (push (mapconcat
25274              (lambda (x)
25275                (setq gr (pop org-table-colgroup-info))
25276                (format "%s<col align=\"%s\"></col>%s"
25277                        (if (memq gr '(:start :startend))
25278                            (prog1
25279                                (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
25280                              (setq colgropen t))
25281                          "")
25282                        (if (> (/ (float x) nlines) org-table-number-fraction)
25283                            "right" "left")
25284                        (if (memq gr '(:end :startend))
25285                            (progn (setq colgropen nil) "</colgroup>")
25286                          "")))
25287              fnum "")
25288             html)
25289       (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
25290       (push html-table-tag html))
25291     (concat (mapconcat 'identity html "\n") "\n")))
25293 (defun org-table-clean-before-export (lines)
25294   "Check if the table has a marking column.
25295 If yes remove the column and the special lines."
25296   (setq org-table-colgroup-info nil)
25297   (if (memq nil
25298             (mapcar
25299              (lambda (x) (or (string-match "^[ \t]*|-" x)
25300                              (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
25301              lines))
25302       (progn
25303         (setq org-table-clean-did-remove-column nil)
25304         (delq nil
25305               (mapcar
25306                (lambda (x)
25307                  (cond
25308                   ((string-match  "^[ \t]*| */ *|" x)
25309                    (setq org-table-colgroup-info
25310                          (mapcar (lambda (x)
25311                                    (cond ((member x '("<" "&lt;")) :start)
25312                                          ((member x '(">" "&gt;")) :end)
25313                                          ((member x '("<>" "&lt;&gt;")) :startend)
25314                                          (t nil)))
25315                                  (org-split-string x "[ \t]*|[ \t]*")))
25316                    nil)
25317                   (t x)))
25318                lines)))
25319     (setq org-table-clean-did-remove-column t)
25320     (delq nil
25321           (mapcar
25322            (lambda (x)
25323              (cond
25324               ((string-match  "^[ \t]*| */ *|" x)
25325                (setq org-table-colgroup-info
25326                      (mapcar (lambda (x)
25327                                (cond ((member x '("<" "&lt;")) :start)
25328                                      ((member x '(">" "&gt;")) :end)
25329                                      ((member x '("<>" "&lt;&gt;")) :startend)
25330                                      (t nil)))
25331                              (cdr (org-split-string x "[ \t]*|[ \t]*"))))
25332                nil)
25333               ((string-match "^[ \t]*| *[!_^/] *|" x)
25334                nil) ; ignore this line
25335               ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
25336                    (string-match "^\\([ \t]*\\)|[^|]*|" x))
25337                ;; remove the first column
25338                (replace-match "\\1|" t nil x))))
25339            lines))))
25341 (defun org-format-table-table-html (lines)
25342   "Format a table generated by table.el into HTML.
25343 This conversion does *not* use `table-generate-source' from table.el.
25344 This has the advantage that Org-mode's HTML conversions can be used.
25345 But it has the disadvantage, that no cell- or row-spanning is allowed."
25346   (let (line field-buffer
25347              (head org-export-highlight-first-table-line)
25348              fields html empty)
25349     (setq html (concat html-table-tag "\n"))
25350     (while (setq line (pop lines))
25351       (setq empty "&nbsp;")
25352       (catch 'next-line
25353         (if (string-match "^[ \t]*\\+-" line)
25354             (progn
25355               (if field-buffer
25356                   (progn
25357                     (setq
25358                      html
25359                      (concat
25360                       html
25361                       "<tr>"
25362                       (mapconcat
25363                        (lambda (x)
25364                          (if (equal x "") (setq x empty))
25365                          (if head
25366                              (concat (car org-export-table-header-tags) x
25367                                      (cdr org-export-table-header-tags))
25368                            (concat (car org-export-table-data-tags) x
25369                                    (cdr org-export-table-data-tags))))
25370                        field-buffer "\n")
25371                       "</tr>\n"))
25372                     (setq head nil)
25373                     (setq field-buffer nil)))
25374               ;; Ignore this line
25375               (throw 'next-line t)))
25376         ;; Break the line into fields and store the fields
25377         (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25378         (if field-buffer
25379             (setq field-buffer (mapcar
25380                                 (lambda (x)
25381                                   (concat x "<br/>" (pop fields)))
25382                                 field-buffer))
25383           (setq field-buffer fields))))
25384     (setq html (concat html "</table>\n"))
25385     html))
25387 (defun org-format-table-table-html-using-table-generate-source (lines)
25388   "Format a table into html, using `table-generate-source' from table.el.
25389 This has the advantage that cell- or row-spanning is allowed.
25390 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
25391   (require 'table)
25392   (with-current-buffer (get-buffer-create " org-tmp1 ")
25393     (erase-buffer)
25394     (insert (mapconcat 'identity lines "\n"))
25395     (goto-char (point-min))
25396     (if (not (re-search-forward "|[^+]" nil t))
25397         (error "Error processing table"))
25398     (table-recognize-table)
25399     (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
25400     (table-generate-source 'html " org-tmp2 ")
25401     (set-buffer " org-tmp2 ")
25402     (buffer-substring (point-min) (point-max))))
25404 (defun org-html-handle-time-stamps (s)
25405   "Format time stamps in string S, or remove them."
25406   (catch 'exit
25407     (let (r b)
25408       (while (string-match org-maybe-keyword-time-regexp s)
25409         (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
25410             ;; never export CLOCK
25411             (throw 'exit ""))
25412         (or b (setq b (substring s 0 (match-beginning 0))))
25413         (if (not org-export-with-timestamps)
25414             (setq r (concat r (substring s 0 (match-beginning 0)))
25415                   s (substring s (match-end 0)))
25416           (setq r (concat
25417                    r (substring s 0 (match-beginning 0))
25418                    (if (match-end 1)
25419                        (format "@<span class=\"timestamp-kwd\">%s @</span>"
25420                                (match-string 1 s)))
25421                    (format " @<span class=\"timestamp\">%s@</span>"
25422                            (substring
25423                             (org-translate-time (match-string 3 s)) 1 -1)))
25424                 s (substring s (match-end 0)))))
25425       ;; Line break if line started and ended with time stamp stuff
25426       (if (not r)
25427           s
25428         (setq r (concat r s))
25429         (unless (string-match "\\S-" (concat b s))
25430           (setq r (concat r "@<br/>")))
25431         r))))
25433 (defun org-html-protect (s)
25434   ;; convert & to &amp;, < to &lt; and > to &gt;
25435   (let ((start 0))
25436     (while (string-match "&" s start)
25437       (setq s (replace-match "&amp;" t t s)
25438             start (1+ (match-beginning 0))))
25439     (while (string-match "<" s)
25440       (setq s (replace-match "&lt;" t t s)))
25441     (while (string-match ">" s)
25442       (setq s (replace-match "&gt;" t t s))))
25443   s)
25445 (defun org-export-cleanup-toc-line (s)
25446   "Remove tags and time staps from lines going into the toc."
25447   (when (memq org-export-with-tags '(not-in-toc nil))
25448     (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
25449         (setq s (replace-match "" t t s))))
25450   (when org-export-remove-timestamps-from-toc
25451     (while (string-match org-maybe-keyword-time-regexp s)
25452       (setq s (replace-match "" t t s))))
25453   (while (string-match org-bracket-link-regexp s)
25454     (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
25455                            t t s)))
25456   s)
25458 (defun org-html-expand (string)
25459   "Prepare STRING for HTML export.  Applies all active conversions.
25460 If there are links in the string, don't modify these."
25461   (let* ((re (concat org-bracket-link-regexp "\\|"
25462                      (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
25463          m s l res)
25464     (while (setq m (string-match re string))
25465       (setq s (substring string 0 m)
25466             l (match-string 0 string)
25467             string (substring string (match-end 0)))
25468       (push (org-html-do-expand s) res)
25469       (push l res))
25470     (push (org-html-do-expand string) res)
25471     (apply 'concat (nreverse res))))
25473 (defun org-html-do-expand (s)
25474   "Apply all active conversions to translate special ASCII to HTML."
25475   (setq s (org-html-protect s))
25476   (if org-export-html-expand
25477       (let ((start 0))
25478         (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
25479           (setq s (replace-match "<\\1>" t nil s)))))
25480   (if org-export-with-emphasize
25481       (setq s (org-export-html-convert-emphasize s)))
25482   (if org-export-with-special-strings
25483       (setq s (org-export-html-convert-special-strings s)))
25484   (if org-export-with-sub-superscripts
25485       (setq s (org-export-html-convert-sub-super s)))
25486   (if org-export-with-TeX-macros
25487       (let ((start 0) wd ass)
25488         (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
25489           (if (get-text-property (match-beginning 0) 'org-protected s)
25490               (setq start (match-end 0))
25491             (setq wd (match-string 1 s))
25492             (if (setq ass (assoc wd org-html-entities))
25493                 (setq s (replace-match (or (cdr ass)
25494                                            (concat "&" (car ass) ";"))
25495                                        t t s))
25496               (setq start (+ start (length wd))))))))
25497   s)
25499 (defun org-create-multibrace-regexp (left right n)
25500   "Create a regular expression which will match a balanced sexp.
25501 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
25502 as single character strings.
25503 The regexp returned will match the entire expression including the
25504 delimiters.  It will also define a single group which contains the
25505 match except for the outermost delimiters.  The maximum depth of
25506 stacked delimiters is N.  Escaping delimiters is not possible."
25507   (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
25508          (or "\\|")
25509          (re nothing)
25510          (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
25511     (while (> n 1)
25512       (setq n (1- n)
25513             re (concat re or next)
25514             next (concat "\\(?:" nothing left next right "\\)+" nothing)))
25515     (concat left "\\(" re "\\)" right)))
25517 (defvar org-match-substring-regexp
25518   (concat
25519    "\\([^\\]\\)\\([_^]\\)\\("
25520    "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25521    "\\|"
25522    "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
25523    "\\|"
25524    "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
25525   "The regular expression matching a sub- or superscript.")
25527 (defvar org-match-substring-with-braces-regexp
25528   (concat
25529    "\\([^\\]\\)\\([_^]\\)\\("
25530    "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25531    "\\)")
25532   "The regular expression matching a sub- or superscript, forcing braces.")
25534 (defconst org-export-html-special-string-regexps
25535   '(("\\\\-" . "&shy;")
25536     ("---\\([^-]\\)" . "&mdash;\\1")
25537     ("--\\([^-]\\)" . "&ndash;\\1")
25538     ("\\.\\.\\." . "&hellip;"))
25539   "Regular expressions for special string conversion.")
25541 (defun org-export-html-convert-special-strings (string)
25542   "Convert special characters in STRING to HTML."
25543   (let ((all org-export-html-special-string-regexps)
25544         e a re rpl start)
25545     (while (setq a (pop all))
25546       (setq re (car a) rpl (cdr a) start 0)
25547       (while (string-match re string start)
25548         (if (get-text-property (match-beginning 0) 'org-protected string)
25549             (setq start (match-end 0))
25550           (setq string (replace-match rpl t nil string)))))
25551     string))
25553 (defun org-export-html-convert-sub-super (string)
25554   "Convert sub- and superscripts in STRING to HTML."
25555   (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
25556     (while (string-match org-match-substring-regexp string s)
25557       (cond
25558        ((and requireb (match-end 8)) (setq s (match-end 2)))
25559        ((get-text-property  (match-beginning 2) 'org-protected string)
25560         (setq s (match-end 2)))
25561        (t
25562         (setq s (match-end 1)
25563               key (if (string= (match-string 2 string) "_") "sub" "sup")
25564               c (or (match-string 8 string)
25565                     (match-string 6 string)
25566                     (match-string 5 string))
25567               string (replace-match
25568                       (concat (match-string 1 string)
25569                               "<" key ">" c "</" key ">")
25570                       t t string)))))
25571     (while (string-match "\\\\\\([_^]\\)" string)
25572       (setq string (replace-match (match-string 1 string) t t string)))
25573     string))
25575 (defun org-export-html-convert-emphasize (string)
25576   "Apply emphasis."
25577   (let ((s 0) rpl)
25578     (while (string-match org-emph-re string s)
25579       (if (not (equal
25580                 (substring string (match-beginning 3) (1+ (match-beginning 3)))
25581                 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
25582           (setq s (match-beginning 0)
25583                 rpl
25584                 (concat
25585                  (match-string 1 string)
25586                  (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
25587                  (match-string 4 string)
25588                  (nth 3 (assoc (match-string 3 string)
25589                                org-emphasis-alist))
25590                  (match-string 5 string))
25591                 string (replace-match rpl t t string)
25592                 s (+ s (- (length rpl) 2)))
25593         (setq s (1+ s))))
25594     string))
25596 (defvar org-par-open nil)
25597 (defun org-open-par ()
25598   "Insert <p>, but first close previous paragraph if any."
25599   (org-close-par-maybe)
25600   (insert "\n<p>")
25601   (setq org-par-open t))
25602 (defun org-close-par-maybe ()
25603   "Close paragraph if there is one open."
25604   (when org-par-open
25605     (insert "</p>")
25606     (setq org-par-open nil)))
25607 (defun org-close-li ()
25608   "Close <li> if necessary."
25609   (org-close-par-maybe)
25610   (insert "</li>\n"))
25612 (defvar body-only) ; dynamically scoped into this.
25613 (defun org-html-level-start (level title umax with-toc head-count)
25614   "Insert a new level in HTML export.
25615 When TITLE is nil, just close all open levels."
25616   (org-close-par-maybe)
25617   (let ((l org-level-max))
25618     (while (>= l level)
25619       (if (aref org-levels-open (1- l))
25620           (progn
25621             (org-html-level-close l umax)
25622             (aset org-levels-open (1- l) nil)))
25623       (setq l (1- l)))
25624     (when title
25625       ;; If title is nil, this means this function is called to close
25626       ;; all levels, so the rest is done only if title is given
25627         (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25628           (setq title (replace-match
25629                        (if org-export-with-tags
25630                            (save-match-data
25631                              (concat
25632                               "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
25633                               (mapconcat 'identity (org-split-string
25634                                                     (match-string 1 title) ":")
25635                                          "&nbsp;")
25636                               "</span>"))
25637                          "")
25638                        t t title)))
25639       (if (> level umax)
25640           (progn
25641             (if (aref org-levels-open (1- level))
25642                 (progn
25643                   (org-close-li)
25644                   (insert "<li>" title "<br/>\n"))
25645               (aset org-levels-open (1- level) t)
25646               (org-close-par-maybe)
25647               (insert "<ul>\n<li>" title "<br/>\n")))
25648         (aset org-levels-open (1- level) t)
25649         (if (and org-export-with-section-numbers (not body-only))
25650             (setq title (concat (org-section-number level) " " title)))
25651         (setq level (+ level org-export-html-toplevel-hlevel -1))
25652         (if with-toc
25653             (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
25654                             level level head-count title level))
25655           (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
25656         (org-open-par)))))
25658 (defun org-html-level-close (level max-outline-level)
25659   "Terminate one level in HTML export."
25660   (if (<= level max-outline-level)
25661       (insert "</div>\n")
25662     (org-close-li)
25663     (insert "</ul>\n")))
25665 ;;; iCalendar export
25667 ;;;###autoload
25668 (defun org-export-icalendar-this-file ()
25669   "Export current file as an iCalendar file.
25670 The iCalendar file will be located in the same directory as the Org-mode
25671 file, but with extension `.ics'."
25672   (interactive)
25673   (org-export-icalendar nil buffer-file-name))
25675 ;;;###autoload
25676 (defun org-export-icalendar-all-agenda-files ()
25677   "Export all files in `org-agenda-files' to iCalendar .ics files.
25678 Each iCalendar file will be located in the same directory as the Org-mode
25679 file, but with extension `.ics'."
25680   (interactive)
25681   (apply 'org-export-icalendar nil (org-agenda-files t)))
25683 ;;;###autoload
25684 (defun org-export-icalendar-combine-agenda-files ()
25685   "Export all files in `org-agenda-files' to a single combined iCalendar file.
25686 The file is stored under the name `org-combined-agenda-icalendar-file'."
25687   (interactive)
25688   (apply 'org-export-icalendar t (org-agenda-files t)))
25690 (defun org-export-icalendar (combine &rest files)
25691   "Create iCalendar files for all elements of FILES.
25692 If COMBINE is non-nil, combine all calendar entries into a single large
25693 file and store it under the name `org-combined-agenda-icalendar-file'."
25694   (save-excursion
25695     (org-prepare-agenda-buffers files)
25696     (let* ((dir (org-export-directory
25697                  :ical (list :publishing-directory
25698                              org-export-publishing-directory)))
25699            file ical-file ical-buffer category started org-agenda-new-buffers)
25701       (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
25702       (when combine
25703         (setq ical-file
25704               (if (file-name-absolute-p org-combined-agenda-icalendar-file)
25705                   org-combined-agenda-icalendar-file
25706                 (expand-file-name org-combined-agenda-icalendar-file dir))
25707               ical-buffer (org-get-agenda-file-buffer ical-file))
25708         (set-buffer ical-buffer) (erase-buffer))
25709       (while (setq file (pop files))
25710         (catch 'nextfile
25711           (org-check-agenda-file file)
25712           (set-buffer (org-get-agenda-file-buffer file))
25713           (unless combine
25714             (setq ical-file (concat (file-name-as-directory dir)
25715                                     (file-name-sans-extension
25716                                      (file-name-nondirectory buffer-file-name))
25717                                     ".ics"))
25718             (setq ical-buffer (org-get-agenda-file-buffer ical-file))
25719             (with-current-buffer ical-buffer (erase-buffer)))
25720           (setq category (or org-category
25721                              (file-name-sans-extension
25722                               (file-name-nondirectory buffer-file-name))))
25723           (if (symbolp category) (setq category (symbol-name category)))
25724           (let ((standard-output ical-buffer))
25725             (if combine
25726                 (and (not started) (setq started t)
25727                      (org-start-icalendar-file org-icalendar-combined-name))
25728               (org-start-icalendar-file category))
25729             (org-print-icalendar-entries combine)
25730             (when (or (and combine (not files)) (not combine))
25731               (org-finish-icalendar-file)
25732               (set-buffer ical-buffer)
25733               (save-buffer)
25734               (run-hooks 'org-after-save-iCalendar-file-hook)))))
25735       (org-release-buffers org-agenda-new-buffers))))
25737 (defvar org-after-save-iCalendar-file-hook nil
25738   "Hook run after an iCalendar file has been saved.
25739 The iCalendar buffer is still current when this hook is run.
25740 A good way to use this is to tell a desktop calenndar application to re-read
25741 the iCalendar file.")
25743 (defun org-print-icalendar-entries (&optional combine)
25744   "Print iCalendar entries for the current Org-mode file to `standard-output'.
25745 When COMBINE is non nil, add the category to each line."
25746   (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
25747         (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
25748         (dts (org-ical-ts-to-string
25749               (format-time-string (cdr org-time-stamp-formats) (current-time))
25750               "DTSTART"))
25751         hd ts ts2 state status (inc t) pos b sexp rrule
25752         scheduledp deadlinep tmp pri category entry location summary desc
25753         (sexp-buffer (get-buffer-create "*ical-tmp*")))
25754     (org-refresh-category-properties)
25755     (save-excursion
25756       (goto-char (point-min))
25757       (while (re-search-forward re1 nil t)
25758         (catch :skip
25759           (org-agenda-skip)
25760           (setq pos (match-beginning 0)
25761                 ts (match-string 0)
25762                 inc t
25763                 hd (org-get-heading)
25764                 summary (org-icalendar-cleanup-string
25765                          (org-entry-get nil "SUMMARY"))
25766                 desc (org-icalendar-cleanup-string
25767                       (or (org-entry-get nil "DESCRIPTION")
25768                           (and org-icalendar-include-body (org-get-entry)))
25769                       t org-icalendar-include-body)
25770                 location (org-icalendar-cleanup-string
25771                           (org-entry-get nil "LOCATION"))
25772                 category (org-get-category))
25773           (if (looking-at re2)
25774               (progn
25775                 (goto-char (match-end 0))
25776                 (setq ts2 (match-string 1) inc nil))
25777             (setq tmp (buffer-substring (max (point-min)
25778                                              (- pos org-ds-keyword-length))
25779                                         pos)
25780                   ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
25781                           (progn
25782                             (setq inc nil)
25783                             (replace-match "\\1" t nil ts))
25784                         ts)
25785                   deadlinep (string-match org-deadline-regexp tmp)
25786                   scheduledp (string-match org-scheduled-regexp tmp)
25787                   ;; donep (org-entry-is-done-p)
25788                   ))
25789           (if (or (string-match org-tr-regexp hd)
25790                   (string-match org-ts-regexp hd))
25791               (setq hd (replace-match "" t t hd)))
25792           (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
25793               (setq rrule
25794                     (concat "\nRRULE:FREQ="
25795                             (cdr (assoc
25796                                   (match-string 2 ts)
25797                                   '(("d" . "DAILY")("w" . "WEEKLY")
25798                                     ("m" . "MONTHLY")("y" . "YEARLY"))))
25799                             ";INTERVAL=" (match-string 1 ts)))
25800             (setq rrule ""))
25801           (setq summary (or summary hd))
25802           (if (string-match org-bracket-link-regexp summary)
25803               (setq summary
25804                     (replace-match (if (match-end 3)
25805                                        (match-string 3 summary)
25806                                         (match-string 1 summary))
25807                                       t t summary)))
25808           (if deadlinep (setq summary (concat "DL: " summary)))
25809           (if scheduledp (setq summary (concat "S: " summary)))
25810           (if (string-match "\\`<%%" ts)
25811               (with-current-buffer sexp-buffer
25812                 (insert (substring ts 1 -1) " " summary "\n"))
25813             (princ (format "BEGIN:VEVENT
25815 %s%s
25816 SUMMARY:%s%s%s
25817 CATEGORIES:%s
25818 END:VEVENT\n"
25819                            (org-ical-ts-to-string ts "DTSTART")
25820                            (org-ical-ts-to-string ts2 "DTEND" inc)
25821                            rrule summary
25822                            (if (and desc (string-match "\\S-" desc))
25823                                (concat "\nDESCRIPTION: " desc) "")
25824                            (if (and location (string-match "\\S-" location))
25825                                (concat "\nLOCATION: " location) "")
25826                            category)))))
25828       (when (and org-icalendar-include-sexps
25829                  (condition-case nil (require 'icalendar) (error nil))
25830                  (fboundp 'icalendar-export-region))
25831         ;; Get all the literal sexps
25832         (goto-char (point-min))
25833         (while (re-search-forward "^&?%%(" nil t)
25834           (catch :skip
25835             (org-agenda-skip)
25836             (setq b (match-beginning 0))
25837             (goto-char (1- (match-end 0)))
25838             (forward-sexp 1)
25839             (end-of-line 1)
25840             (setq sexp (buffer-substring b (point)))
25841             (with-current-buffer sexp-buffer
25842               (insert sexp "\n"))
25843             (princ (org-diary-to-ical-string sexp-buffer)))))
25845       (when org-icalendar-include-todo
25846         (goto-char (point-min))
25847         (while (re-search-forward org-todo-line-regexp nil t)
25848           (catch :skip
25849             (org-agenda-skip)
25850             (setq state (match-string 2))
25851             (setq status (if (member state org-done-keywords)
25852                              "COMPLETED" "NEEDS-ACTION"))
25853             (when (and state
25854                        (or (not (member state org-done-keywords))
25855                            (eq org-icalendar-include-todo 'all))
25856                        (not (member org-archive-tag (org-get-tags-at)))
25857                        )
25858               (setq hd (match-string 3)
25859                     summary (org-icalendar-cleanup-string
25860                              (org-entry-get nil "SUMMARY"))
25861                     desc (org-icalendar-cleanup-string
25862                           (or (org-entry-get nil "DESCRIPTION")
25863                               (and org-icalendar-include-body (org-get-entry)))
25864                           t org-icalendar-include-body)
25865                     location (org-icalendar-cleanup-string
25866                               (org-entry-get nil "LOCATION")))
25867               (if (string-match org-bracket-link-regexp hd)
25868                   (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
25869                                             (match-string 1 hd))
25870                                           t t hd)))
25871               (if (string-match org-priority-regexp hd)
25872                   (setq pri (string-to-char (match-string 2 hd))
25873                         hd (concat (substring hd 0 (match-beginning 1))
25874                                    (substring hd (match-end 1))))
25875                 (setq pri org-default-priority))
25876               (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
25877                                             (- org-lowest-priority org-highest-priority))))))
25879               (princ (format "BEGIN:VTODO
25881 SUMMARY:%s%s%s
25882 CATEGORIES:%s
25883 SEQUENCE:1
25884 PRIORITY:%d
25885 STATUS:%s
25886 END:VTODO\n"
25887                              dts
25888                              (or summary hd)
25889                              (if (and location (string-match "\\S-" location))
25890                                  (concat "\nLOCATION: " location) "")
25891                              (if (and desc (string-match "\\S-" desc))
25892                                  (concat "\nDESCRIPTION: " desc) "")
25893                              category pri status)))))))))
25895 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
25896   "Take out stuff and quote what needs to be quoted.
25897 When IS-BODY is non-nil, assume that this is the body of an item, clean up
25898 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
25899 characters."
25900   (if (not s)
25901       nil
25902     (when is-body
25903       (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
25904             (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
25905         (while (string-match re s) (setq s (replace-match "" t t s)))
25906         (while (string-match re2 s) (setq s (replace-match "" t t s)))))
25907     (let ((start 0))
25908       (while (string-match "\\([,;\\]\\)" s start)
25909         (setq start (+ (match-beginning 0) 2)
25910               s (replace-match "\\\\\\1" nil nil s))))
25911     (when is-body
25912       (while (string-match "[ \t]*\n[ \t]*" s)
25913         (setq s (replace-match "\\n" t t s))))
25914     (setq s (org-trim s))
25915     (if is-body
25916         (if maxlength
25917             (if (and (numberp maxlength)
25918                      (> (length s) maxlength))
25919                 (setq s (substring s 0 maxlength)))))
25920     s))
25922 (defun org-get-entry ()
25923   "Clean-up description string."
25924   (save-excursion
25925     (org-back-to-heading t)
25926     (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
25928 (defun org-start-icalendar-file (name)
25929   "Start an iCalendar file by inserting the header."
25930   (let ((user user-full-name)
25931         (name (or name "unknown"))
25932         (timezone (cadr (current-time-zone))))
25933     (princ
25934      (format "BEGIN:VCALENDAR
25935 VERSION:2.0
25936 X-WR-CALNAME:%s
25937 PRODID:-//%s//Emacs with Org-mode//EN
25938 X-WR-TIMEZONE:%s
25939 CALSCALE:GREGORIAN\n" name user timezone))))
25941 (defun org-finish-icalendar-file ()
25942   "Finish an iCalendar file by inserting the END statement."
25943   (princ "END:VCALENDAR\n"))
25945 (defun org-ical-ts-to-string (s keyword &optional inc)
25946   "Take a time string S and convert it to iCalendar format.
25947 KEYWORD is added in front, to make a complete line like DTSTART....
25948 When INC is non-nil, increase the hour by two (if time string contains
25949 a time), or the day by one (if it does not contain a time)."
25950   (let ((t1 (org-parse-time-string s 'nodefault))
25951         t2 fmt have-time time)
25952     (if (and (car t1) (nth 1 t1) (nth 2 t1))
25953         (setq t2 t1 have-time t)
25954       (setq t2 (org-parse-time-string s)))
25955     (let ((s (car t2))   (mi (nth 1 t2)) (h (nth 2 t2))
25956           (d (nth 3 t2)) (m  (nth 4 t2)) (y (nth 5 t2)))
25957       (when inc
25958         (if have-time
25959             (if org-agenda-default-appointment-duration
25960                 (setq mi (+ org-agenda-default-appointment-duration mi))
25961               (setq h (+ 2 h)))
25962           (setq d (1+ d))))
25963       (setq time (encode-time s mi h d m y)))
25964     (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
25965     (concat keyword (format-time-string fmt time))))
25967 ;;; XOXO export
25969 (defun org-export-as-xoxo-insert-into (buffer &rest output)
25970   (with-current-buffer buffer
25971     (apply 'insert output)))
25972 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
25974 (defun org-export-as-xoxo (&optional buffer)
25975   "Export the org buffer as XOXO.
25976 The XOXO buffer is named *xoxo-<source buffer name>*"
25977   (interactive (list (current-buffer)))
25978   ;; A quickie abstraction
25980   ;; Output everything as XOXO
25981   (with-current-buffer (get-buffer buffer)
25982     (let* ((pos (point))
25983            (opt-plist (org-combine-plists (org-default-export-plist)
25984                                         (org-infile-export-plist)))
25985            (filename (concat (file-name-as-directory
25986                               (org-export-directory :xoxo opt-plist))
25987                              (file-name-sans-extension
25988                               (file-name-nondirectory buffer-file-name))
25989                              ".html"))
25990            (out (find-file-noselect filename))
25991            (last-level 1)
25992            (hanging-li nil))
25993       (goto-char (point-min))  ;; CD:  beginning-of-buffer is not allowed.
25994       ;; Check the output buffer is empty.
25995       (with-current-buffer out (erase-buffer))
25996       ;; Kick off the output
25997       (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
25998       (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
25999         (let* ((hd (match-string-no-properties 1))
26000                (level (length hd))
26001                (text (concat
26002                       (match-string-no-properties 2)
26003                       (save-excursion
26004                         (goto-char (match-end 0))
26005                         (let ((str ""))
26006                           (catch 'loop
26007                             (while 't
26008                               (forward-line)
26009                               (if (looking-at "^[ \t]\\(.*\\)")
26010                                   (setq str (concat str (match-string-no-properties 1)))
26011                                 (throw 'loop str)))))))))
26013           ;; Handle level rendering
26014           (cond
26015            ((> level last-level)
26016             (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26018            ((< level last-level)
26019             (dotimes (- (- last-level level) 1)
26020               (if hanging-li
26021                   (org-export-as-xoxo-insert-into out "</li>\n"))
26022               (org-export-as-xoxo-insert-into out "</ol>\n"))
26023             (when hanging-li
26024               (org-export-as-xoxo-insert-into out "</li>\n")
26025               (setq hanging-li nil)))
26027            ((equal level last-level)
26028             (if hanging-li
26029                 (org-export-as-xoxo-insert-into out "</li>\n")))
26030            )
26032           (setq last-level level)
26034           ;; And output the new li
26035           (setq hanging-li 't)
26036           (if (equal ?+ (elt text 0))
26037               (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26038             (org-export-as-xoxo-insert-into out "<li>" text))))
26040       ;; Finally finish off the ol
26041       (dotimes (- last-level 1)
26042         (if hanging-li
26043             (org-export-as-xoxo-insert-into out "</li>\n"))
26044         (org-export-as-xoxo-insert-into out "</ol>\n"))
26046       (goto-char pos)
26047       ;; Finish the buffer off and clean it up.
26048       (switch-to-buffer-other-window out)
26049       (indent-region (point-min) (point-max) nil)
26050       (save-buffer)
26051       (goto-char (point-min))
26052       )))
26055 ;;;; Key bindings
26057 ;; Make `C-c C-x' a prefix key
26058 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26060 ;; TAB key with modifiers
26061 (org-defkey org-mode-map "\C-i"       'org-cycle)
26062 (org-defkey org-mode-map [(tab)]      'org-cycle)
26063 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26064 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26065 (org-defkey org-mode-map "\M-\t" 'org-complete)
26066 (org-defkey org-mode-map "\M-\C-i"      'org-complete)
26067 ;; The following line is necessary under Suse GNU/Linux
26068 (unless (featurep 'xemacs)
26069   (org-defkey org-mode-map [S-iso-lefttab]  'org-shifttab))
26070 (org-defkey org-mode-map [(shift tab)]    'org-shifttab)
26071 (define-key org-mode-map [backtab] 'org-shifttab)
26073 (org-defkey org-mode-map [(shift return)]   'org-table-copy-down)
26074 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26075 (org-defkey org-mode-map [(meta return)]       'org-meta-return)
26077 ;; Cursor keys with modifiers
26078 (org-defkey org-mode-map [(meta left)]  'org-metaleft)
26079 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26080 (org-defkey org-mode-map [(meta up)]    'org-metaup)
26081 (org-defkey org-mode-map [(meta down)]  'org-metadown)
26083 (org-defkey org-mode-map [(meta shift left)]   'org-shiftmetaleft)
26084 (org-defkey org-mode-map [(meta shift right)]  'org-shiftmetaright)
26085 (org-defkey org-mode-map [(meta shift up)]     'org-shiftmetaup)
26086 (org-defkey org-mode-map [(meta shift down)]   'org-shiftmetadown)
26088 (org-defkey org-mode-map [(shift up)]          'org-shiftup)
26089 (org-defkey org-mode-map [(shift down)]        'org-shiftdown)
26090 (org-defkey org-mode-map [(shift left)]        'org-shiftleft)
26091 (org-defkey org-mode-map [(shift right)]       'org-shiftright)
26093 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26094 (org-defkey org-mode-map [(control shift left)]  'org-shiftcontrolleft)
26096 ;;; Extra keys for tty access.
26097 ;;  We only set them when really needed because otherwise the
26098 ;;  menus don't show the simple keys
26100 (when (or (featurep 'xemacs)   ;; because XEmacs supports multi-device stuff
26101           (not window-system))
26102   (org-defkey org-mode-map "\C-c\C-xc"    'org-table-copy-down)
26103   (org-defkey org-mode-map "\C-c\C-xM"    'org-insert-todo-heading)
26104   (org-defkey org-mode-map "\C-c\C-xm"    'org-meta-return)
26105   (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26106   (org-defkey org-mode-map [?\e (left)]   'org-metaleft)
26107   (org-defkey org-mode-map "\C-c\C-xl"    'org-metaleft)
26108   (org-defkey org-mode-map [?\e (right)]  'org-metaright)
26109   (org-defkey org-mode-map "\C-c\C-xr"    'org-metaright)
26110   (org-defkey org-mode-map [?\e (up)]     'org-metaup)
26111   (org-defkey org-mode-map "\C-c\C-xu"    'org-metaup)
26112   (org-defkey org-mode-map [?\e (down)]   'org-metadown)
26113   (org-defkey org-mode-map "\C-c\C-xd"    'org-metadown)
26114   (org-defkey org-mode-map "\C-c\C-xL"    'org-shiftmetaleft)
26115   (org-defkey org-mode-map "\C-c\C-xR"    'org-shiftmetaright)
26116   (org-defkey org-mode-map "\C-c\C-xU"    'org-shiftmetaup)
26117   (org-defkey org-mode-map "\C-c\C-xD"    'org-shiftmetadown)
26118   (org-defkey org-mode-map [?\C-c (up)]    'org-shiftup)
26119   (org-defkey org-mode-map [?\C-c (down)]  'org-shiftdown)
26120   (org-defkey org-mode-map [?\C-c (left)]  'org-shiftleft)
26121   (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26122   (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26123   (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26125   ;; All the other keys
26127 (org-defkey org-mode-map "\C-c\C-a" 'show-all)  ; in case allout messed up.
26128 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26129 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26130 (org-defkey org-mode-map "\C-c$"    'org-archive-subtree)
26131 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26132 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26133 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26134 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26135 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26136 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26137 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26138 (org-defkey org-mode-map "\C-c;"    'org-toggle-comment)
26139 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26140 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26141 (org-defkey org-mode-map "\C-c/"    'org-sparse-tree)   ; Minor-mode reserved
26142 (org-defkey org-mode-map "\C-c\\"   'org-tags-sparse-tree) ; Minor-mode res.
26143 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26144 (org-defkey org-mode-map "\M-\C-m"  'org-insert-heading)
26145 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26146 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26147 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26148 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26149 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26150 (org-defkey org-mode-map "\C-c%"    'org-mark-ring-push)
26151 (org-defkey org-mode-map "\C-c&"    'org-mark-ring-goto)
26152 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp)  ; Alternative binding
26153 (org-defkey org-mode-map "\C-c."    'org-time-stamp)  ; Minor-mode reserved
26154 (org-defkey org-mode-map "\C-c!"    'org-time-stamp-inactive) ; Minor-mode r.
26155 (org-defkey org-mode-map "\C-c,"    'org-priority)    ; Minor-mode reserved
26156 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26157 (org-defkey org-mode-map "\C-c>"    'org-goto-calendar)
26158 (org-defkey org-mode-map "\C-c<"    'org-date-from-calendar)
26159 (org-defkey org-mode-map [(control ?,)]     'org-cycle-agenda-files)
26160 (org-defkey org-mode-map [(control ?\')]     'org-cycle-agenda-files)
26161 (org-defkey org-mode-map "\C-c["    'org-agenda-file-to-front)
26162 (org-defkey org-mode-map "\C-c]"    'org-remove-file)
26163 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26164 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26165 (org-defkey org-mode-map "\C-c-"    'org-ctrl-c-minus)
26166 (org-defkey org-mode-map "\C-c^"    'org-sort)
26167 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26168 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26169 (org-defkey org-mode-map "\C-c#"    'org-update-checkbox-count)
26170 (org-defkey org-mode-map "\C-m"     'org-return)
26171 (org-defkey org-mode-map "\C-j"     'org-return-indent)
26172 (org-defkey org-mode-map "\C-c?"    'org-table-field-info)
26173 (org-defkey org-mode-map "\C-c "    'org-table-blank-field)
26174 (org-defkey org-mode-map "\C-c+"    'org-table-sum)
26175 (org-defkey org-mode-map "\C-c="    'org-table-eval-formula)
26176 (org-defkey org-mode-map "\C-c'"    'org-table-edit-formulas)
26177 (org-defkey org-mode-map "\C-c`"    'org-table-edit-field)
26178 (org-defkey org-mode-map "\C-c|"    'org-table-create-or-convert-from-region)
26179 (org-defkey org-mode-map "\C-c*"    'org-table-recalculate)
26180 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26181 (org-defkey org-mode-map "\C-c~"    'org-table-create-with-table.el)
26182 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26183 (org-defkey org-mode-map "\C-c}"    'org-table-toggle-coordinate-overlays)
26184 (org-defkey org-mode-map "\C-c{"    'org-table-toggle-formula-debugger)
26185 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26186 (org-defkey org-mode-map "\C-c:"    'org-toggle-fixed-width-section)
26187 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26189 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26190 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26191 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26192 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26194 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26195 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26196 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26197 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26198 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26199 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26200 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26201 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26202 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26203 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26204 (org-defkey org-mode-map "\C-c\C-xp"    'org-set-property)
26205 (org-defkey org-mode-map "\C-c\C-xr"    'org-insert-columns-dblock)
26207 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26209 (when (featurep 'xemacs)
26210   (org-defkey org-mode-map 'button3   'popup-mode-menu))
26212 (defsubst org-table-p () (org-at-table-p))
26214 (defun org-self-insert-command (N)
26215   "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26216 If the cursor is in a table looking at whitespace, the whitespace is
26217 overwritten, and the table is not marked as requiring realignment."
26218   (interactive "p")
26219   (if (and (org-table-p)
26220            (progn
26221              ;; check if we blank the field, and if that triggers align
26222              (and org-table-auto-blank-field
26223                   (member last-command
26224                           '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
26225                   (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]*  |"))
26226                       ;; got extra space, this field does not determine column width
26227                       (let (org-table-may-need-update) (org-table-blank-field))
26228                     ;; no extra space, this field may determine column width
26229                     (org-table-blank-field)))
26230              t)
26231            (eq N 1)
26232            (looking-at "[^|\n]*  |"))
26233       (let (org-table-may-need-update)
26234         (goto-char (1- (match-end 0)))
26235         (delete-backward-char 1)
26236         (goto-char (match-beginning 0))
26237         (self-insert-command N))
26238     (setq org-table-may-need-update t)
26239     (self-insert-command N)
26240     (org-fix-tags-on-the-fly)))
26242 (defun org-fix-tags-on-the-fly ()
26243   (when (and (equal (char-after (point-at-bol)) ?*)
26244              (org-on-heading-p))
26245     (org-align-tags-here org-tags-column)))
26247 (defun org-delete-backward-char (N)
26248   "Like `delete-backward-char', insert whitespace at field end in tables.
26249 When deleting backwards, in tables this function will insert whitespace in
26250 front of the next \"|\" separator, to keep the table aligned.  The table will
26251 still be marked for re-alignment if the field did fill the entire column,
26252 because, in this case the deletion might narrow the column."
26253   (interactive "p")
26254   (if (and (org-table-p)
26255            (eq N 1)
26256            (string-match "|" (buffer-substring (point-at-bol) (point)))
26257            (looking-at ".*?|"))
26258       (let ((pos (point))
26259             (noalign (looking-at "[^|\n\r]*  |"))
26260             (c org-table-may-need-update))
26261         (backward-delete-char N)
26262         (skip-chars-forward "^|")
26263         (insert " ")
26264         (goto-char (1- pos))
26265         ;; noalign: if there were two spaces at the end, this field
26266         ;; does not determine the width of the column.
26267         (if noalign (setq org-table-may-need-update c)))
26268     (backward-delete-char N)
26269     (org-fix-tags-on-the-fly)))
26271 (defun org-delete-char (N)
26272   "Like `delete-char', but insert whitespace at field end in tables.
26273 When deleting characters, in tables this function will insert whitespace in
26274 front of the next \"|\" separator, to keep the table aligned.  The table will
26275 still be marked for re-alignment if the field did fill the entire column,
26276 because, in this case the deletion might narrow the column."
26277   (interactive "p")
26278   (if (and (org-table-p)
26279            (not (bolp))
26280            (not (= (char-after) ?|))
26281            (eq N 1))
26282       (if (looking-at ".*?|")
26283           (let ((pos (point))
26284                 (noalign (looking-at "[^|\n\r]*  |"))
26285                 (c org-table-may-need-update))
26286             (replace-match (concat
26287                             (substring (match-string 0) 1 -1)
26288                             " |"))
26289             (goto-char pos)
26290             ;; noalign: if there were two spaces at the end, this field
26291             ;; does not determine the width of the column.
26292             (if noalign (setq org-table-may-need-update c)))
26293         (delete-char N))
26294     (delete-char N)
26295     (org-fix-tags-on-the-fly)))
26297 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
26298 (put 'org-self-insert-command 'delete-selection t)
26299 (put 'orgtbl-self-insert-command 'delete-selection t)
26300 (put 'org-delete-char 'delete-selection 'supersede)
26301 (put 'org-delete-backward-char 'delete-selection 'supersede)
26303 ;; Make `flyspell-mode' delay after some commands
26304 (put 'org-self-insert-command 'flyspell-delayed t)
26305 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
26306 (put 'org-delete-char 'flyspell-delayed t)
26307 (put 'org-delete-backward-char 'flyspell-delayed t)
26309 ;; Make pabbrev-mode expand after org-mode commands
26310 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
26311 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
26313 ;; How to do this: Measure non-white length of current string
26314 ;; If equal to column width, we should realign.
26316 (defun org-remap (map &rest commands)
26317   "In MAP, remap the functions given in COMMANDS.
26318 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
26319   (let (new old)
26320     (while commands
26321       (setq old (pop commands) new (pop commands))
26322       (if (fboundp 'command-remapping)
26323           (org-defkey map (vector 'remap old) new)
26324         (substitute-key-definition old new map global-map)))))
26326 (when (eq org-enable-table-editor 'optimized)
26327   ;; If the user wants maximum table support, we need to hijack
26328   ;; some standard editing functions
26329   (org-remap org-mode-map
26330              'self-insert-command 'org-self-insert-command
26331              'delete-char 'org-delete-char
26332              'delete-backward-char 'org-delete-backward-char)
26333   (org-defkey org-mode-map "|" 'org-force-self-insert))
26335 (defun org-shiftcursor-error ()
26336   "Throw an error because Shift-Cursor command was applied in wrong context."
26337   (error "This command is active in special context like tables, headlines or timestamps"))
26339 (defun org-shifttab (&optional arg)
26340   "Global visibility cycling or move to previous table field.
26341 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
26342 on context.
26343 See the individual commands for more information."
26344   (interactive "P")
26345   (cond
26346    ((org-at-table-p) (call-interactively 'org-table-previous-field))
26347    (arg (message  "Content view to level: ")
26348         (org-content (prefix-numeric-value arg))
26349         (setq org-cycle-global-status 'overview))
26350    (t (call-interactively 'org-global-cycle))))
26352 (defun org-shiftmetaleft ()
26353   "Promote subtree or delete table column.
26354 Calls `org-promote-subtree', `org-outdent-item',
26355 or `org-table-delete-column', depending on context.
26356 See the individual commands for more information."
26357   (interactive)
26358   (cond
26359    ((org-at-table-p) (call-interactively 'org-table-delete-column))
26360    ((org-on-heading-p) (call-interactively 'org-promote-subtree))
26361    ((org-at-item-p) (call-interactively 'org-outdent-item))
26362    (t (org-shiftcursor-error))))
26364 (defun org-shiftmetaright ()
26365   "Demote subtree or insert table column.
26366 Calls `org-demote-subtree', `org-indent-item',
26367 or `org-table-insert-column', depending on context.
26368 See the individual commands for more information."
26369   (interactive)
26370   (cond
26371    ((org-at-table-p) (call-interactively 'org-table-insert-column))
26372    ((org-on-heading-p) (call-interactively 'org-demote-subtree))
26373    ((org-at-item-p) (call-interactively 'org-indent-item))
26374    (t (org-shiftcursor-error))))
26376 (defun org-shiftmetaup (&optional arg)
26377   "Move subtree up or kill table row.
26378 Calls `org-move-subtree-up' or `org-table-kill-row' or
26379 `org-move-item-up' depending on context.  See the individual commands
26380 for more information."
26381   (interactive "P")
26382   (cond
26383    ((org-at-table-p) (call-interactively 'org-table-kill-row))
26384    ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26385    ((org-at-item-p) (call-interactively 'org-move-item-up))
26386    (t (org-shiftcursor-error))))
26387 (defun org-shiftmetadown (&optional arg)
26388   "Move subtree down or insert table row.
26389 Calls `org-move-subtree-down' or `org-table-insert-row' or
26390 `org-move-item-down', depending on context.  See the individual
26391 commands for more information."
26392   (interactive "P")
26393   (cond
26394    ((org-at-table-p) (call-interactively 'org-table-insert-row))
26395    ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26396    ((org-at-item-p) (call-interactively 'org-move-item-down))
26397    (t (org-shiftcursor-error))))
26399 (defun org-metaleft (&optional arg)
26400   "Promote heading or move table column to left.
26401 Calls `org-do-promote' or `org-table-move-column', depending on context.
26402 With no specific context, calls the Emacs default `backward-word'.
26403 See the individual commands for more information."
26404   (interactive "P")
26405   (cond
26406    ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
26407    ((or (org-on-heading-p) (org-region-active-p))
26408     (call-interactively 'org-do-promote))
26409    ((org-at-item-p) (call-interactively 'org-outdent-item))
26410    (t (call-interactively 'backward-word))))
26412 (defun org-metaright (&optional arg)
26413   "Demote subtree or move table column to right.
26414 Calls `org-do-demote' or `org-table-move-column', depending on context.
26415 With no specific context, calls the Emacs default `forward-word'.
26416 See the individual commands for more information."
26417   (interactive "P")
26418   (cond
26419    ((org-at-table-p) (call-interactively 'org-table-move-column))
26420    ((or (org-on-heading-p) (org-region-active-p))
26421     (call-interactively 'org-do-demote))
26422    ((org-at-item-p) (call-interactively 'org-indent-item))
26423    (t (call-interactively 'forward-word))))
26425 (defun org-metaup (&optional arg)
26426   "Move subtree up or move table row up.
26427 Calls `org-move-subtree-up' or `org-table-move-row' or
26428 `org-move-item-up', depending on context.  See the individual commands
26429 for more information."
26430   (interactive "P")
26431   (cond
26432    ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
26433    ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26434    ((org-at-item-p) (call-interactively 'org-move-item-up))
26435    (t (transpose-lines 1) (beginning-of-line -1))))
26437 (defun org-metadown (&optional arg)
26438   "Move subtree down or move table row down.
26439 Calls `org-move-subtree-down' or `org-table-move-row' or
26440 `org-move-item-down', depending on context.  See the individual
26441 commands for more information."
26442   (interactive "P")
26443   (cond
26444    ((org-at-table-p) (call-interactively 'org-table-move-row))
26445    ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26446    ((org-at-item-p) (call-interactively 'org-move-item-down))
26447    (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
26449 (defun org-shiftup (&optional arg)
26450   "Increase item in timestamp or increase priority of current headline.
26451 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
26452 depending on context.  See the individual commands for more information."
26453   (interactive "P")
26454   (cond
26455    ((org-at-timestamp-p t)
26456     (call-interactively (if org-edit-timestamp-down-means-later
26457                             'org-timestamp-down 'org-timestamp-up)))
26458    ((org-on-heading-p) (call-interactively 'org-priority-up))
26459    ((org-at-item-p) (call-interactively 'org-previous-item))
26460    (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
26462 (defun org-shiftdown (&optional arg)
26463   "Decrease item in timestamp or decrease priority of current headline.
26464 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
26465 depending on context.  See the individual commands for more information."
26466   (interactive "P")
26467   (cond
26468    ((org-at-timestamp-p t)
26469     (call-interactively (if org-edit-timestamp-down-means-later
26470                             'org-timestamp-up 'org-timestamp-down)))
26471    ((org-on-heading-p) (call-interactively 'org-priority-down))
26472    (t (call-interactively 'org-next-item))))
26474 (defun org-shiftright ()
26475   "Next TODO keyword or timestamp one day later, depending on context."
26476   (interactive)
26477   (cond
26478    ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
26479    ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
26480    ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
26481    ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
26482    (t (org-shiftcursor-error))))
26484 (defun org-shiftleft ()
26485   "Previous TODO keyword or timestamp one day earlier, depending on context."
26486   (interactive)
26487   (cond
26488    ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
26489    ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
26490    ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
26491    ((org-at-property-p)
26492     (call-interactively 'org-property-previous-allowed-value))
26493    (t (org-shiftcursor-error))))
26495 (defun org-shiftcontrolright ()
26496   "Switch to next TODO set."
26497   (interactive)
26498   (cond
26499    ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
26500    (t (org-shiftcursor-error))))
26502 (defun org-shiftcontrolleft ()
26503   "Switch to previous TODO set."
26504   (interactive)
26505   (cond
26506    ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
26507    (t (org-shiftcursor-error))))
26509 (defun org-ctrl-c-ret ()
26510   "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
26511   (interactive)
26512   (cond
26513    ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
26514    (t (call-interactively 'org-insert-heading))))
26516 (defun org-copy-special ()
26517   "Copy region in table or copy current subtree.
26518 Calls `org-table-copy' or `org-copy-subtree', depending on context.
26519 See the individual commands for more information."
26520   (interactive)
26521   (call-interactively
26522    (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
26524 (defun org-cut-special ()
26525   "Cut region in table or cut current subtree.
26526 Calls `org-table-copy' or `org-cut-subtree', depending on context.
26527 See the individual commands for more information."
26528   (interactive)
26529   (call-interactively
26530    (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
26532 (defun org-paste-special (arg)
26533   "Paste rectangular region into table, or past subtree relative to level.
26534 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
26535 See the individual commands for more information."
26536   (interactive "P")
26537   (if (org-at-table-p)
26538       (org-table-paste-rectangle)
26539     (org-paste-subtree arg)))
26541 (defun org-ctrl-c-ctrl-c (&optional arg)
26542   "Set tags in headline, or update according to changed information at point.
26544 This command does many different things, depending on context:
26546 - If the cursor is in a headline, prompt for tags and insert them
26547   into the current line, aligned to `org-tags-column'.  When called
26548   with prefix arg, realign all tags in the current buffer.
26550 - If the cursor is in one of the special #+KEYWORD lines, this
26551   triggers scanning the buffer for these lines and updating the
26552   information.
26554 - If the cursor is inside a table, realign the table.  This command
26555   works even if the automatic table editor has been turned off.
26557 - If the cursor is on a #+TBLFM line, re-apply the formulas to
26558   the entire table.
26560 - If the cursor is a the beginning of a dynamic block, update it.
26562 - If the cursor is inside a table created by the table.el package,
26563   activate that table.
26565 - If the current buffer is a remember buffer, close note and file it.
26566   with a prefix argument, file it without further interaction to the default
26567   location.
26569 - If the cursor is on a <<<target>>>, update radio targets and corresponding
26570   links in this buffer.
26572 - If the cursor is on a numbered item in a plain list, renumber the
26573   ordered list.
26575 - If the cursor is on a checkbox, toggle it."
26576   (interactive "P")
26577   (let  ((org-enable-table-editor t))
26578     (cond
26579      ((or org-clock-overlays
26580           org-occur-highlights
26581           org-latex-fragment-image-overlays)
26582       (org-remove-clock-overlays)
26583       (org-remove-occur-highlights)
26584       (org-remove-latex-fragment-image-overlays)
26585       (message "Temporary highlights/overlays removed from current buffer"))
26586      ((and (local-variable-p 'org-finish-function (current-buffer))
26587            (fboundp org-finish-function))
26588       (funcall org-finish-function))
26589      ((org-at-property-p)
26590       (call-interactively 'org-property-action))
26591      ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
26592      ((org-on-heading-p) (call-interactively 'org-set-tags))
26593      ((org-at-table.el-p)
26594       (require 'table)
26595       (beginning-of-line 1)
26596       (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
26597       (call-interactively 'table-recognize-table))
26598      ((org-at-table-p)
26599       (org-table-maybe-eval-formula)
26600       (if arg
26601           (call-interactively 'org-table-recalculate)
26602         (org-table-maybe-recalculate-line))
26603       (call-interactively 'org-table-align))
26604      ((org-at-item-checkbox-p)
26605       (call-interactively 'org-toggle-checkbox))
26606      ((org-at-item-p)
26607       (call-interactively 'org-maybe-renumber-ordered-list))
26608      ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
26609       ;; Dynamic block
26610       (beginning-of-line 1)
26611       (org-update-dblock))
26612      ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
26613       (cond
26614        ((equal (match-string 1) "TBLFM")
26615         ;; Recalculate the table before this line
26616         (save-excursion
26617           (beginning-of-line 1)
26618           (skip-chars-backward " \r\n\t")
26619           (if (org-at-table-p)
26620               (org-call-with-arg 'org-table-recalculate t))))
26621        (t
26622         (call-interactively 'org-mode-restart))))
26623      (t (error "C-c C-c can do nothing useful at this location.")))))
26625 (defun org-mode-restart ()
26626   "Restart Org-mode, to scan again for special lines.
26627 Also updates the keyword regular expressions."
26628   (interactive)
26629   (let ((org-inhibit-startup t)) (org-mode))
26630   (message "Org-mode restarted to refresh keyword and special line setup"))
26632 (defun org-kill-note-or-show-branches ()
26633   "If this is a Note buffer, abort storing the note. Else call `show-branches'."
26634   (interactive)
26635   (if (not org-finish-function)
26636       (call-interactively 'show-branches)
26637     (let ((org-note-abort t))
26638       (funcall org-finish-function))))
26640 (defun org-return (&optional indent)
26641   "Goto next table row or insert a newline.
26642 Calls `org-table-next-row' or `newline', depending on context.
26643 See the individual commands for more information."
26644   (interactive)
26645   (cond
26646    ((bobp) (if indent (newline-and-indent) (newline)))
26647    ((org-at-table-p)
26648     (org-table-justify-field-maybe)
26649     (call-interactively 'org-table-next-row))
26650    (t (if indent (newline-and-indent) (newline)))))
26652 (defun org-return-indent ()
26653   (interactive)
26654   "Goto next table row or insert a newline and indent.
26655 Calls `org-table-next-row' or `newline-and-indent', depending on
26656 context.  See the individual commands for more information."
26657   (org-return t))
26659 (defun org-ctrl-c-minus ()
26660   "Insert separator line in table or modify bullet type in list.
26661 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
26662 depending on context."
26663   (interactive)
26664   (cond
26665    ((org-at-table-p)
26666     (call-interactively 'org-table-insert-hline))
26667    ((org-on-heading-p)
26668     ;; Convert to item
26669     (save-excursion
26670       (beginning-of-line 1)
26671       (if (looking-at "\\*+ ")
26672           (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
26673    ((org-in-item-p)
26674     (call-interactively 'org-cycle-list-bullet))
26675    (t (error "`C-c -' does have no function here."))))
26677 (defun org-meta-return (&optional arg)
26678   "Insert a new heading or wrap a region in a table.
26679 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
26680 See the individual commands for more information."
26681   (interactive "P")
26682   (cond
26683    ((org-at-table-p)
26684     (call-interactively 'org-table-wrap-region))
26685    (t (call-interactively 'org-insert-heading))))
26687 ;;; Menu entries
26689 ;; Define the Org-mode menus
26690 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
26691   '("Tbl"
26692     ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
26693     ["Next Field" org-cycle (org-at-table-p)]
26694     ["Previous Field" org-shifttab (org-at-table-p)]
26695     ["Next Row" org-return (org-at-table-p)]
26696     "--"
26697     ["Blank Field" org-table-blank-field (org-at-table-p)]
26698     ["Edit Field" org-table-edit-field (org-at-table-p)]
26699     ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
26700     "--"
26701     ("Column"
26702      ["Move Column Left" org-metaleft (org-at-table-p)]
26703      ["Move Column Right" org-metaright (org-at-table-p)]
26704      ["Delete Column" org-shiftmetaleft (org-at-table-p)]
26705      ["Insert Column" org-shiftmetaright (org-at-table-p)])
26706     ("Row"
26707      ["Move Row Up" org-metaup (org-at-table-p)]
26708      ["Move Row Down" org-metadown (org-at-table-p)]
26709      ["Delete Row" org-shiftmetaup (org-at-table-p)]
26710      ["Insert Row" org-shiftmetadown (org-at-table-p)]
26711      ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
26712      "--"
26713      ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
26714     ("Rectangle"
26715      ["Copy Rectangle" org-copy-special (org-at-table-p)]
26716      ["Cut Rectangle" org-cut-special (org-at-table-p)]
26717      ["Paste Rectangle" org-paste-special (org-at-table-p)]
26718      ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
26719     "--"
26720     ("Calculate"
26721      ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
26722      ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
26723      ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
26724      "--"
26725      ["Recalculate line" org-table-recalculate (org-at-table-p)]
26726      ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
26727      ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
26728      "--"
26729      ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
26730      "--"
26731      ["Sum Column/Rectangle" org-table-sum
26732       (or (org-at-table-p) (org-region-active-p))]
26733      ["Which Column?" org-table-current-column (org-at-table-p)])
26734     ["Debug Formulas"
26735      org-table-toggle-formula-debugger
26736      :style toggle :selected org-table-formula-debug]
26737     ["Show Col/Row Numbers"
26738      org-table-toggle-coordinate-overlays
26739      :style toggle :selected org-table-overlay-coordinates]
26740     "--"
26741     ["Create" org-table-create (and (not (org-at-table-p))
26742                                     org-enable-table-editor)]
26743     ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
26744     ["Import from File" org-table-import (not (org-at-table-p))]
26745     ["Export to File" org-table-export (org-at-table-p)]
26746     "--"
26747     ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
26749 (easy-menu-define org-org-menu org-mode-map "Org menu"
26750   '("Org"
26751     ("Show/Hide"
26752      ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
26753      ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
26754      ["Sparse Tree" org-occur t]
26755      ["Reveal Context" org-reveal t]
26756      ["Show All" show-all t]
26757      "--"
26758      ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
26759     "--"
26760     ["New Heading" org-insert-heading t]
26761     ("Navigate Headings"
26762      ["Up" outline-up-heading t]
26763      ["Next" outline-next-visible-heading t]
26764      ["Previous" outline-previous-visible-heading t]
26765      ["Next Same Level" outline-forward-same-level t]
26766      ["Previous Same Level" outline-backward-same-level t]
26767      "--"
26768      ["Jump" org-goto t])
26769     ("Edit Structure"
26770      ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
26771      ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
26772      "--"
26773      ["Copy Subtree"  org-copy-special (not (org-at-table-p))]
26774      ["Cut Subtree"  org-cut-special (not (org-at-table-p))]
26775      ["Paste Subtree"  org-paste-special (not (org-at-table-p))]
26776      "--"
26777      ["Promote Heading" org-metaleft (not (org-at-table-p))]
26778      ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
26779      ["Demote Heading"  org-metaright (not (org-at-table-p))]
26780      ["Demote Subtree"  org-shiftmetaright (not (org-at-table-p))]
26781      "--"
26782      ["Sort Region/Children" org-sort  (not (org-at-table-p))]
26783      "--"
26784      ["Convert to odd levels" org-convert-to-odd-levels t]
26785      ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
26786     ("Editing"
26787      ["Emphasis..." org-emphasize t])
26788     ("Archive"
26789      ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
26790 ;     ["Check and Tag Children" (org-toggle-archive-tag (4))
26791 ;      :active t :keys "C-u C-c C-x C-a"]
26792      ["Sparse trees open ARCHIVE trees"
26793       (setq org-sparse-tree-open-archived-trees
26794             (not org-sparse-tree-open-archived-trees))
26795       :style toggle :selected org-sparse-tree-open-archived-trees]
26796      ["Cycling opens ARCHIVE trees"
26797       (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
26798       :style toggle :selected org-cycle-open-archived-trees]
26799      ["Agenda includes ARCHIVE trees"
26800       (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
26801       :style toggle :selected (not org-agenda-skip-archived-trees)]
26802      "--"
26803      ["Move Subtree to Archive" org-advertized-archive-subtree t]
26804  ;    ["Check and Move Children" (org-archive-subtree '(4))
26805  ;     :active t :keys "C-u C-c C-x C-s"]
26806      )
26807     "--"
26808     ("TODO Lists"
26809      ["TODO/DONE/-" org-todo t]
26810      ("Select keyword"
26811       ["Next keyword" org-shiftright (org-on-heading-p)]
26812       ["Previous keyword" org-shiftleft (org-on-heading-p)]
26813       ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
26814       ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
26815       ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
26816      ["Show TODO Tree" org-show-todo-tree t]
26817      ["Global TODO list" org-todo-list t]
26818      "--"
26819      ["Set Priority" org-priority t]
26820      ["Priority Up" org-shiftup t]
26821      ["Priority Down" org-shiftdown t])
26822     ("TAGS and Properties"
26823      ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
26824      ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
26825      "--"
26826      ["Set property" 'org-set-property t]
26827      ["Column view of properties" org-columns t]
26828      ["Insert Column View DBlock" org-insert-columns-dblock t])
26829     ("Dates and Scheduling"
26830      ["Timestamp" org-time-stamp t]
26831      ["Timestamp (inactive)" org-time-stamp-inactive t]
26832      ("Change Date"
26833       ["1 Day Later" org-shiftright t]
26834       ["1 Day Earlier" org-shiftleft t]
26835       ["1 ... Later" org-shiftup t]
26836       ["1 ... Earlier" org-shiftdown t])
26837      ["Compute Time Range" org-evaluate-time-range t]
26838      ["Schedule Item" org-schedule t]
26839      ["Deadline" org-deadline t]
26840      "--"
26841      ["Custom time format" org-toggle-time-stamp-overlays
26842       :style radio :selected org-display-custom-times]
26843      "--"
26844      ["Goto Calendar" org-goto-calendar t]
26845      ["Date from Calendar" org-date-from-calendar t])
26846     ("Logging work"
26847      ["Clock in" org-clock-in t]
26848      ["Clock out" org-clock-out t]
26849      ["Clock cancel" org-clock-cancel t]
26850      ["Goto running clock" org-clock-goto t]
26851      ["Display times" org-clock-display t]
26852      ["Create clock table" org-clock-report t]
26853      "--"
26854      ["Record DONE time"
26855       (progn (setq org-log-done (not org-log-done))
26856              (message "Switching to %s will %s record a timestamp"
26857                       (car org-done-keywords)
26858                       (if org-log-done "automatically" "not")))
26859       :style toggle :selected org-log-done])
26860     "--"
26861     ["Agenda Command..." org-agenda t]
26862     ["Set Restriction Lock" org-agenda-set-restriction-lock t]
26863     ("File List for Agenda")
26864     ("Special views current file"
26865      ["TODO Tree"  org-show-todo-tree t]
26866      ["Check Deadlines" org-check-deadlines t]
26867      ["Timeline" org-timeline t]
26868      ["Tags Tree" org-tags-sparse-tree t])
26869     "--"
26870     ("Hyperlinks"
26871      ["Store Link (Global)" org-store-link t]
26872      ["Insert Link" org-insert-link t]
26873      ["Follow Link" org-open-at-point t]
26874      "--"
26875      ["Next link" org-next-link t]
26876      ["Previous link" org-previous-link t]
26877      "--"
26878      ["Descriptive Links"
26879       (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
26880       :style radio :selected (member '(org-link) buffer-invisibility-spec)]
26881      ["Literal Links"
26882       (progn
26883         (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
26884       :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
26885     "--"
26886     ["Export/Publish..." org-export t]
26887     ("LaTeX"
26888      ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
26889       :selected org-cdlatex-mode]
26890      ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
26891      ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
26892      ["Modify math symbol" org-cdlatex-math-modify
26893       (org-inside-LaTeX-fragment-p)]
26894      ["Export LaTeX fragments as images"
26895       (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
26896       :style toggle :selected org-export-with-LaTeX-fragments])
26897     "--"
26898     ("Documentation"
26899      ["Show Version" org-version t]
26900      ["Info Documentation" org-info t])
26901     ("Customize"
26902      ["Browse Org Group" org-customize t]
26903      "--"
26904      ["Expand This Menu" org-create-customize-menu
26905       (fboundp 'customize-menu-create)])
26906     "--"
26907     ["Refresh setup" org-mode-restart t]
26908     ))
26910 (defun org-info (&optional node)
26911   "Read documentation for Org-mode in the info system.
26912 With optional NODE, go directly to that node."
26913   (interactive)
26914   (require 'info)
26915   (Info-goto-node (format "(org)%s" (or node ""))))
26917 (defun org-install-agenda-files-menu ()
26918   (let ((bl (buffer-list)))
26919     (save-excursion
26920       (while bl
26921         (set-buffer (pop bl))
26922         (if (org-mode-p) (setq bl nil)))
26923       (when (org-mode-p)
26924         (easy-menu-change
26925          '("Org") "File List for Agenda"
26926          (append
26927           (list
26928            ["Edit File List" (org-edit-agenda-file-list) t]
26929            ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
26930            ["Remove Current File from List" org-remove-file t]
26931            ["Cycle through agenda files" org-cycle-agenda-files t]
26932            ["Occur in all agenda files" org-occur-in-agenda-files t]
26933            "--")
26934           (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
26936 ;;;; Documentation
26938 (defun org-customize ()
26939   "Call the customize function with org as argument."
26940   (interactive)
26941   (customize-browse 'org))
26943 (defun org-create-customize-menu ()
26944   "Create a full customization menu for Org-mode, insert it into the menu."
26945   (interactive)
26946   (if (fboundp 'customize-menu-create)
26947       (progn
26948         (easy-menu-change
26949          '("Org") "Customize"
26950          `(["Browse Org group" org-customize t]
26951            "--"
26952            ,(customize-menu-create 'org)
26953            ["Set" Custom-set t]
26954            ["Save" Custom-save t]
26955            ["Reset to Current" Custom-reset-current t]
26956            ["Reset to Saved" Custom-reset-saved t]
26957            ["Reset to Standard Settings" Custom-reset-standard t]))
26958         (message "\"Org\"-menu now contains full customization menu"))
26959     (error "Cannot expand menu (outdated version of cus-edit.el)")))
26961 ;;;; Miscellaneous stuff
26964 ;;; Generally useful functions
26966 (defun org-context ()
26967   "Return a list of contexts of the current cursor position.
26968 If several contexts apply, all are returned.
26969 Each context entry is a list with a symbol naming the context, and
26970 two positions indicating start and end of the context.  Possible
26971 contexts are:
26973 :headline         anywhere in a headline
26974 :headline-stars   on the leading stars in a headline
26975 :todo-keyword     on a TODO keyword (including DONE) in a headline
26976 :tags             on the TAGS in a headline
26977 :priority         on the priority cookie in a headline
26978 :item             on the first line of a plain list item
26979 :item-bullet      on the bullet/number of a plain list item
26980 :checkbox         on the checkbox in a plain list item
26981 :table            in an org-mode table
26982 :table-special    on a special filed in a table
26983 :table-table      in a table.el table
26984 :link             on a hyperlink
26985 :keyword          on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
26986 :target           on a <<target>>
26987 :radio-target     on a <<<radio-target>>>
26988 :latex-fragment   on a LaTeX fragment
26989 :latex-preview    on a LaTeX fragment with overlayed preview image
26991 This function expects the position to be visible because it uses font-lock
26992 faces as a help to recognize the following contexts: :table-special, :link,
26993 and :keyword."
26994   (let* ((f (get-text-property (point) 'face))
26995          (faces (if (listp f) f (list f)))
26996          (p (point)) clist o)
26997     ;; First the large context
26998     (cond
26999      ((org-on-heading-p t)
27000       (push (list :headline (point-at-bol) (point-at-eol)) clist)
27001       (when (progn
27002               (beginning-of-line 1)
27003               (looking-at org-todo-line-tags-regexp))
27004         (push (org-point-in-group p 1 :headline-stars) clist)
27005         (push (org-point-in-group p 2 :todo-keyword) clist)
27006         (push (org-point-in-group p 4 :tags) clist))
27007       (goto-char p)
27008       (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27009       (if (looking-at "\\[#[A-Z0-9]\\]")
27010           (push (org-point-in-group p 0 :priority) clist)))
27012      ((org-at-item-p)
27013       (push (org-point-in-group p 2 :item-bullet) clist)
27014       (push (list :item (point-at-bol)
27015                   (save-excursion (org-end-of-item) (point)))
27016             clist)
27017       (and (org-at-item-checkbox-p)
27018            (push (org-point-in-group p 0 :checkbox) clist)))
27020      ((org-at-table-p)
27021       (push (list :table (org-table-begin) (org-table-end)) clist)
27022       (if (memq 'org-formula faces)
27023           (push (list :table-special
27024                       (previous-single-property-change p 'face)
27025                       (next-single-property-change p 'face)) clist)))
27026      ((org-at-table-p 'any)
27027       (push (list :table-table) clist)))
27028     (goto-char p)
27030     ;; Now the small context
27031     (cond
27032      ((org-at-timestamp-p)
27033       (push (org-point-in-group p 0 :timestamp) clist))
27034      ((memq 'org-link faces)
27035       (push (list :link
27036                   (previous-single-property-change p 'face)
27037                   (next-single-property-change p 'face)) clist))
27038      ((memq 'org-special-keyword faces)
27039       (push (list :keyword
27040                   (previous-single-property-change p 'face)
27041                   (next-single-property-change p 'face)) clist))
27042      ((org-on-target-p)
27043       (push (org-point-in-group p 0 :target) clist)
27044       (goto-char (1- (match-beginning 0)))
27045       (if (looking-at org-radio-target-regexp)
27046           (push (org-point-in-group p 0 :radio-target) clist))
27047       (goto-char p))
27048      ((setq o (car (delq nil
27049                          (mapcar
27050                           (lambda (x)
27051                             (if (memq x org-latex-fragment-image-overlays) x))
27052                           (org-overlays-at (point))))))
27053       (push (list :latex-fragment
27054                   (org-overlay-start o) (org-overlay-end o)) clist)
27055       (push (list :latex-preview
27056                   (org-overlay-start o) (org-overlay-end o)) clist))
27057      ((org-inside-LaTeX-fragment-p)
27058       ;; FIXME: positions wrong.
27059       (push (list :latex-fragment (point) (point)) clist)))
27061     (setq clist (nreverse (delq nil clist)))
27062     clist))
27064 ;; FIXME: Compare with at-regexp-p Do we need both?
27065 (defun org-in-regexp (re &optional nlines visually)
27066   "Check if point is inside a match of regexp.
27067 Normally only the current line is checked, but you can include NLINES extra
27068 lines both before and after point into the search.
27069 If VISUALLY is set, require that the cursor is not after the match but
27070 really on, so that the block visually is on the match."
27071   (catch 'exit
27072     (let ((pos (point))
27073           (eol (point-at-eol (+ 1 (or nlines 0))))
27074           (inc (if visually 1 0)))
27075       (save-excursion
27076         (beginning-of-line (- 1 (or nlines 0)))
27077         (while (re-search-forward re eol t)
27078           (if (and (<= (match-beginning 0) pos)
27079                    (>= (+ inc (match-end 0)) pos))
27080               (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27082 (defun org-at-regexp-p (regexp)
27083   "Is point inside a match of REGEXP in the current line?"
27084   (catch 'exit
27085     (save-excursion
27086       (let ((pos (point)) (end (point-at-eol)))
27087         (beginning-of-line 1)
27088         (while (re-search-forward regexp end t)
27089           (if (and (<= (match-beginning 0) pos)
27090                    (>= (match-end 0) pos))
27091               (throw 'exit t)))
27092         nil))))
27094 (defun org-occur-in-agenda-files (regexp &optional nlines)
27095   "Call `multi-occur' with buffers for all agenda files."
27096   (interactive "sOrg-files matching: \np")
27097   (let* ((files (org-agenda-files))
27098          (tnames (mapcar 'file-truename files))
27099          (extra org-agenda-multi-occur-extra-files)
27100          f)
27101     (while (setq f (pop extra))
27102       (unless (member (file-truename f) tnames)
27103         (add-to-list 'files f 'append)
27104         (add-to-list 'tnames (file-truename f) 'append)))
27105     (multi-occur
27106      (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27107      regexp)))
27109 (defun org-uniquify (list)
27110   "Remove duplicate elements from LIST."
27111   (let (res)
27112     (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27113     res))
27115 (defun org-delete-all (elts list)
27116   "Remove all elements in ELTS from LIST."
27117   (while elts
27118     (setq list (delete (pop elts) list)))
27119   list)
27121 (defun org-back-over-empty-lines ()
27122   "Move backwards over witespace, to the beginning of the first empty line.
27123 Returns the number o empty lines passed."
27124   (let ((pos (point)))
27125     (skip-chars-backward " \t\n\r")
27126     (beginning-of-line 2)
27127     (count-lines (point) pos)))
27129 (defun org-skip-whitespace ()
27130   (skip-chars-forward " \t\n\r"))
27132 (defun org-point-in-group (point group &optional context)
27133   "Check if POINT is in match-group GROUP.
27134 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27135 match.  If the match group does ot exist or point is not inside it,
27136 return nil."
27137   (and (match-beginning group)
27138        (>= point (match-beginning group))
27139        (<= point (match-end group))
27140        (if context
27141            (list context (match-beginning group) (match-end group))
27142          t)))
27144 (defun org-switch-to-buffer-other-window (&rest args)
27145   "Switch to buffer in a second window on the current frame.
27146 In particular, do not allow pop-up frames."
27147   (let (pop-up-frames special-display-buffer-names special-display-regexps
27148                       special-display-function)
27149     (apply 'switch-to-buffer-other-window args)))
27151 (defun org-combine-plists (&rest plists)
27152   "Create a single property list from all plists in PLISTS.
27153 The process starts by copying the first list, and then setting properties
27154 from the other lists.  Settings in the last list are the most significant
27155 ones and overrule settings in the other lists."
27156   (let ((rtn (copy-sequence (pop plists)))
27157         p v ls)
27158     (while plists
27159       (setq ls (pop plists))
27160       (while ls
27161         (setq p (pop ls) v (pop ls))
27162         (setq rtn (plist-put rtn p v))))
27163     rtn))
27165 (defun org-move-line-down (arg)
27166   "Move the current line down.  With prefix argument, move it past ARG lines."
27167   (interactive "p")
27168   (let ((col (current-column))
27169         beg end pos)
27170     (beginning-of-line 1) (setq beg (point))
27171     (beginning-of-line 2) (setq end (point))
27172     (beginning-of-line (+ 1 arg))
27173     (setq pos (move-marker (make-marker) (point)))
27174     (insert (delete-and-extract-region beg end))
27175     (goto-char pos)
27176     (move-to-column col)))
27178 (defun org-move-line-up (arg)
27179   "Move the current line up.  With prefix argument, move it past ARG lines."
27180   (interactive "p")
27181   (let ((col (current-column))
27182         beg end pos)
27183     (beginning-of-line 1) (setq beg (point))
27184     (beginning-of-line 2) (setq end (point))
27185     (beginning-of-line (- arg))
27186     (setq pos (move-marker (make-marker) (point)))
27187     (insert (delete-and-extract-region beg end))
27188     (goto-char pos)
27189     (move-to-column col)))
27191 (defun org-replace-escapes (string table)
27192   "Replace %-escapes in STRING with values in TABLE.
27193 TABLE is an association list with keys like \"%a\" and string values.
27194 The sequences in STRING may contain normal field width and padding information,
27195 for example \"%-5s\".  Replacements happen in the sequence given by TABLE,
27196 so values can contain further %-escapes if they are define later in TABLE."
27197   (let ((case-fold-search nil)
27198         e re rpl)
27199     (while (setq e (pop table))
27200       (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
27201       (while (string-match re string)
27202         (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
27203                           (cdr e)))
27204         (setq string (replace-match rpl t t string))))
27205     string))
27208 (defun org-sublist (list start end)
27209   "Return a section of LIST, from START to END.
27210 Counting starts at 1."
27211   (let (rtn (c start))
27212     (setq list (nthcdr (1- start) list))
27213     (while (and list (<= c end))
27214       (push (pop list) rtn)
27215       (setq c (1+ c)))
27216     (nreverse rtn)))
27218 (defun org-find-base-buffer-visiting (file)
27219   "Like `find-buffer-visiting' but alway return the base buffer and
27220 not an indirect buffer"
27221   (let ((buf (find-buffer-visiting file)))
27222     (if buf
27223         (or (buffer-base-buffer buf) buf)
27224       nil)))
27226 (defun org-image-file-name-regexp ()
27227   "Return regexp matching the file names of images."
27228   (if (fboundp 'image-file-name-regexp)
27229       (image-file-name-regexp)
27230     (let ((image-file-name-extensions
27231            '("png" "jpeg" "jpg" "gif" "tiff" "tif"
27232              "xbm" "xpm" "pbm" "pgm" "ppm")))
27233       (concat "\\."
27234               (regexp-opt (nconc (mapcar 'upcase
27235                                          image-file-name-extensions)
27236                                  image-file-name-extensions)
27237                           t)
27238               "\\'"))))
27240 (defun org-file-image-p (file)
27241   "Return non-nil if FILE is an image."
27242   (save-match-data
27243     (string-match (org-image-file-name-regexp) file)))
27245 ;;; Paragraph filling stuff.
27246 ;; We want this to be just right, so use the full arsenal.
27248 (defun org-indent-line-function ()
27249   "Indent line like previous, but further if previous was headline or item."
27250   (interactive)
27251   (let* ((pos (point))
27252          (itemp (org-at-item-p))
27253          column bpos bcol tpos tcol bullet btype bullet-type)
27254     ;; Find the previous relevant line
27255     (beginning-of-line 1)
27256     (cond
27257      ((looking-at "#") (setq column 0))
27258      ((looking-at "\\*+ ") (setq column 0))
27259      (t
27260       (beginning-of-line 0)
27261       (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
27262         (beginning-of-line 0))
27263       (cond
27264        ((looking-at "\\*+[ \t]+")
27265         (goto-char (match-end 0))
27266         (setq column (current-column)))
27267        ((org-in-item-p)
27268         (org-beginning-of-item)
27269 ;       (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27270         (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
27271         (setq bpos (match-beginning 1) tpos (match-end 0)
27272               bcol (progn (goto-char bpos) (current-column))
27273               tcol (progn (goto-char tpos) (current-column))
27274               bullet (match-string 1)
27275               bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
27276         (if (not itemp)
27277             (setq column tcol)
27278           (goto-char pos)
27279           (beginning-of-line 1)
27280           (if (looking-at "\\S-")
27281               (progn
27282                 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27283                 (setq bullet (match-string 1)
27284                       btype (if (string-match "[0-9]" bullet) "n" bullet))
27285                 (setq column (if (equal btype bullet-type) bcol tcol)))
27286             (setq column (org-get-indentation)))))
27287        (t (setq column (org-get-indentation))))))
27288     (goto-char pos)
27289     (if (<= (current-column) (current-indentation))
27290         (indent-line-to column)
27291       (save-excursion (indent-line-to column)))
27292     (setq column (current-column))
27293     (beginning-of-line 1)
27294     (if (looking-at
27295          "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
27296         (replace-match (concat "\\1" (format org-property-format
27297                                              (match-string 2) (match-string 3)))
27298                        t nil))
27299     (move-to-column column)))
27301 (defun org-set-autofill-regexps ()
27302   (interactive)
27303   ;; In the paragraph separator we include headlines, because filling
27304   ;; text in a line directly attached to a headline would otherwise
27305   ;; fill the headline as well.
27306   (org-set-local 'comment-start-skip "^#+[ \t]*")
27307   (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[    ]*$\\|[ \t]*[:|]")
27308   ;; The paragraph starter includes hand-formatted lists.
27309   (org-set-local 'paragraph-start
27310                  "\f\\|[        ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
27311   ;; Inhibit auto-fill for headers, tables and fixed-width lines.
27312   ;; But only if the user has not turned off tables or fixed-width regions
27313   (org-set-local
27314    'auto-fill-inhibit-regexp
27315    (concat "\\*+ \\|#\\+"
27316            "\\|[ \t]*" org-keyword-time-regexp
27317            (if (or org-enable-table-editor org-enable-fixed-width-editor)
27318                (concat
27319                 "\\|[ \t]*["
27320                 (if org-enable-table-editor "|" "")
27321                 (if org-enable-fixed-width-editor ":"  "")
27322                 "]"))))
27323   ;; We use our own fill-paragraph function, to make sure that tables
27324   ;; and fixed-width regions are not wrapped.  That function will pass
27325   ;; through to `fill-paragraph' when appropriate.
27326   (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
27327   ; Adaptive filling: To get full control, first make sure that
27328   ;; `adaptive-fill-regexp' never matches.  Then install our own matcher.
27329   (org-set-local 'adaptive-fill-regexp "\000")
27330   (org-set-local 'adaptive-fill-function
27331                  'org-adaptive-fill-function))
27333 (defun org-fill-paragraph (&optional justify)
27334   "Re-align a table, pass through to fill-paragraph if no table."
27335   (let ((table-p (org-at-table-p))
27336         (table.el-p (org-at-table.el-p)))
27337     (cond ((and (equal (char-after (point-at-bol)) ?*)
27338                 (save-excursion (goto-char (point-at-bol))
27339                                 (looking-at outline-regexp)))
27340            t)                                        ; skip headlines
27341           (table.el-p t)                             ; skip table.el tables
27342           (table-p (org-table-align) t)              ; align org-mode tables
27343           (t nil))))                                 ; call paragraph-fill
27345 ;; For reference, this is the default value of adaptive-fill-regexp
27346 ;;  "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
27348 (defun org-adaptive-fill-function ()
27349   "Return a fill prefix for org-mode files.
27350 In particular, this makes sure hanging paragraphs for hand-formatted lists
27351 work correctly."
27352   (cond ((looking-at "#[ \t]+")
27353          (match-string 0))
27354         ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
27355          (save-excursion
27356            (goto-char (match-end 0))
27357            (make-string (current-column) ?\ )))
27358         (t nil)))
27360 ;;;; Functions extending outline functionality
27362 (defun org-beginning-of-line (&optional arg)
27363   "Go to the beginning of the current line.  If that is invisible, continue
27364 to a visible line beginning.  This makes the function of C-a more intuitive.
27365 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27366 first attempt, and only move to after the tags when the cursor is already
27367 beyond the end of the headline."
27368   (interactive "P")
27369   (let ((pos (point)))
27370     (beginning-of-line 1)
27371     (if (bobp)
27372         nil
27373       (backward-char 1)
27374       (if (org-invisible-p)
27375           (while (and (not (bobp)) (org-invisible-p))
27376             (backward-char 1)
27377             (beginning-of-line 1))
27378         (forward-char 1)))
27379     (when org-special-ctrl-a/e
27380       (cond
27381        ((and (looking-at org-todo-line-regexp)
27382              (= (char-after (match-end 1)) ?\ ))
27383         (goto-char
27384          (if (eq org-special-ctrl-a/e t)
27385              (cond ((> pos (match-beginning 3)) (match-beginning 3))
27386                    ((= pos (point)) (match-beginning 3))
27387                    (t (point)))
27388            (cond ((> pos (point)) (point))
27389                  ((not (eq last-command this-command)) (point))
27390                  (t (match-beginning 3))))))
27391        ((org-at-item-p)
27392         (goto-char
27393          (if (eq org-special-ctrl-a/e t)
27394              (cond ((> pos (match-end 4)) (match-end 4))
27395                    ((= pos (point)) (match-end 4))
27396                    (t (point)))
27397            (cond ((> pos (point)) (point))
27398                  ((not (eq last-command this-command)) (point))
27399                  (t (match-end 4))))))))))
27401 (defun org-end-of-line (&optional arg)
27402   "Go to the end of the line.
27403 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27404 first attempt, and only move to after the tags when the cursor is already
27405 beyond the end of the headline."
27406   (interactive "P")
27407   (if (or (not org-special-ctrl-a/e)
27408           (not (org-on-heading-p)))
27409       (end-of-line arg)
27410     (let ((pos (point)))
27411       (beginning-of-line 1)
27412       (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
27413           (if (eq org-special-ctrl-a/e t)
27414               (if (or (< pos (match-beginning 1))
27415                       (= pos (match-end 0)))
27416                   (goto-char (match-beginning 1))
27417                 (goto-char (match-end 0)))
27418             (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
27419                 (goto-char (match-end 0))
27420               (goto-char (match-beginning 1))))
27421         (end-of-line arg)))))
27423 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
27424 (define-key org-mode-map "\C-e" 'org-end-of-line)
27426 (defun org-invisible-p ()
27427   "Check if point is at a character currently not visible."
27428   ;; Early versions of noutline don't have `outline-invisible-p'.
27429   (if (fboundp 'outline-invisible-p)
27430       (outline-invisible-p)
27431     (get-char-property (point) 'invisible)))
27433 (defun org-invisible-p2 ()
27434   "Check if point is at a character currently not visible."
27435   (save-excursion
27436     (if (and (eolp) (not (bobp))) (backward-char 1))
27437     ;; Early versions of noutline don't have `outline-invisible-p'.
27438     (if (fboundp 'outline-invisible-p)
27439         (outline-invisible-p)
27440       (get-char-property (point) 'invisible))))
27442 (defalias 'org-back-to-heading 'outline-back-to-heading)
27443 (defalias 'org-on-heading-p 'outline-on-heading-p)
27444 (defalias 'org-at-heading-p 'outline-on-heading-p)
27445 (defun org-at-heading-or-item-p ()
27446   (or (org-on-heading-p) (org-at-item-p)))
27448 (defun org-on-target-p ()
27449   (or (org-in-regexp org-radio-target-regexp)
27450       (org-in-regexp org-target-regexp)))
27452 (defun org-up-heading-all (arg)
27453   "Move to the heading line of which the present line is a subheading.
27454 This function considers both visible and invisible heading lines.
27455 With argument, move up ARG levels."
27456   (if (fboundp 'outline-up-heading-all)
27457       (outline-up-heading-all arg)   ; emacs 21 version of outline.el
27458     (outline-up-heading arg t)))     ; emacs 22 version of outline.el
27460 (defun org-up-heading-safe ()
27461   "Move to the heading line of which the present line is a subheading.
27462 This version will not throw an error.  It will return the level of the
27463 headline found, or nil if no higher level is found."
27464   (let ((pos (point)) start-level level
27465         (re (concat "^" outline-regexp)))
27466     (catch 'exit
27467       (outline-back-to-heading t)
27468       (setq start-level (funcall outline-level))
27469       (if (equal start-level 1) (throw 'exit nil))
27470       (while (re-search-backward re nil t)
27471         (setq level (funcall outline-level))
27472         (if (< level start-level) (throw 'exit level)))
27473       nil)))
27475 (defun org-first-sibling-p ()
27476   "Is this heading the first child of its parents?"
27477   (interactive)
27478   (let ((re (concat "^" outline-regexp))
27479         level l)
27480     (unless (org-at-heading-p t)
27481       (error "Not at a heading"))
27482     (setq level (funcall outline-level))
27483     (save-excursion
27484       (if (not (re-search-backward re nil t))
27485           t
27486         (setq l (funcall outline-level))
27487         (< l level)))))
27489 (defun org-goto-sibling (&optional previous)
27490   "Goto the next sibling, even if it is invisible.
27491 When PREVIOUS is set, go to the previous sibling instead.  Returns t
27492 when a sibling was found.  When none is found, return nil and don't
27493 move point."
27494   (let ((fun (if previous 're-search-backward 're-search-forward))
27495         (pos (point))
27496         (re (concat "^" outline-regexp))
27497         level l)
27498     (when (condition-case nil (org-back-to-heading t) (error nil))
27499       (setq level (funcall outline-level))
27500       (catch 'exit
27501         (or previous (forward-char 1))
27502         (while (funcall fun re nil t)
27503           (setq l (funcall outline-level))
27504           (when (< l level) (goto-char pos) (throw 'exit nil))
27505           (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
27506         (goto-char pos)
27507         nil))))
27509 (defun org-show-siblings ()
27510   "Show all siblings of the current headline."
27511   (save-excursion
27512     (while (org-goto-sibling) (org-flag-heading nil)))
27513   (save-excursion
27514     (while (org-goto-sibling 'previous)
27515       (org-flag-heading nil))))
27517 (defun org-show-hidden-entry ()
27518   "Show an entry where even the heading is hidden."
27519   (save-excursion
27520     (org-show-entry)))
27522 (defun org-flag-heading (flag &optional entry)
27523   "Flag the current heading.  FLAG non-nil means make invisible.
27524 When ENTRY is non-nil, show the entire entry."
27525   (save-excursion
27526     (org-back-to-heading t)
27527     ;; Check if we should show the entire entry
27528     (if entry
27529         (progn
27530           (org-show-entry)
27531           (save-excursion
27532             (and (outline-next-heading)
27533                  (org-flag-heading nil))))
27534       (outline-flag-region (max (point-min) (1- (point)))
27535                            (save-excursion (outline-end-of-heading) (point))
27536                            flag))))
27538 (defun org-end-of-subtree (&optional invisible-OK to-heading)
27539   ;; This is an exact copy of the original function, but it uses
27540   ;; `org-back-to-heading', to make it work also in invisible
27541   ;; trees.  And is uses an invisible-OK argument.
27542   ;; Under Emacs this is not needed, but the old outline.el needs this fix.
27543   (org-back-to-heading invisible-OK)
27544   (let ((first t)
27545         (level (funcall outline-level)))
27546     (while (and (not (eobp))
27547                 (or first (> (funcall outline-level) level)))
27548       (setq first nil)
27549       (outline-next-heading))
27550     (unless to-heading
27551       (if (memq (preceding-char) '(?\n ?\^M))
27552           (progn
27553             ;; Go to end of line before heading
27554             (forward-char -1)
27555             (if (memq (preceding-char) '(?\n ?\^M))
27556                 ;; leave blank line before heading
27557                 (forward-char -1))))))
27558   (point))
27560 (defun org-show-subtree ()
27561   "Show everything after this heading at deeper levels."
27562   (outline-flag-region
27563    (point)
27564    (save-excursion
27565      (outline-end-of-subtree) (outline-next-heading) (point))
27566    nil))
27568 (defun org-show-entry ()
27569   "Show the body directly following this heading.
27570 Show the heading too, if it is currently invisible."
27571   (interactive)
27572   (save-excursion
27573     (condition-case nil
27574         (progn
27575           (org-back-to-heading t)
27576           (outline-flag-region
27577            (max (point-min) (1- (point)))
27578            (save-excursion
27579              (re-search-forward
27580               (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
27581              (or (match-beginning 1) (point-max)))
27582            nil))
27583       (error nil))))
27585 (defun org-make-options-regexp (kwds)
27586   "Make a regular expression for keyword lines."
27587   (concat
27588    "^"
27589    "#?[ \t]*\\+\\("
27590    (mapconcat 'regexp-quote kwds "\\|")
27591    "\\):[ \t]*"
27592    "\\(.+\\)"))
27594 ;; Make isearch reveal the necessary context
27595 (defun org-isearch-end ()
27596   "Reveal context after isearch exits."
27597   (when isearch-success ; only if search was successful
27598     (if (featurep 'xemacs)
27599         ;; Under XEmacs, the hook is run in the correct place,
27600         ;; we directly show the context.
27601         (org-show-context 'isearch)
27602       ;; In Emacs the hook runs *before* restoring the overlays.
27603       ;; So we have to use a one-time post-command-hook to do this.
27604       ;; (Emacs 22 has a special variable, see function `org-mode')
27605       (unless (and (boundp 'isearch-mode-end-hook-quit)
27606                    isearch-mode-end-hook-quit)
27607         ;; Only when the isearch was not quitted.
27608         (org-add-hook 'post-command-hook 'org-isearch-post-command
27609                       'append 'local)))))
27611 (defun org-isearch-post-command ()
27612   "Remove self from hook, and show context."
27613   (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
27614   (org-show-context 'isearch))
27617 ;;;; Integration with and fixes for other packages
27619 ;;; Imenu support
27621 (defvar org-imenu-markers nil
27622   "All markers currently used by Imenu.")
27623 (make-variable-buffer-local 'org-imenu-markers)
27625 (defun org-imenu-new-marker (&optional pos)
27626   "Return a new marker for use by Imenu, and remember the marker."
27627   (let ((m (make-marker)))
27628     (move-marker m (or pos (point)))
27629     (push m org-imenu-markers)
27630     m))
27632 (defun org-imenu-get-tree ()
27633   "Produce the index for Imenu."
27634   (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
27635   (setq org-imenu-markers nil)
27636   (let* ((n org-imenu-depth)
27637          (re (concat "^" outline-regexp))
27638          (subs (make-vector (1+ n) nil))
27639          (last-level 0)
27640          m tree level head)
27641     (save-excursion
27642       (save-restriction
27643         (widen)
27644         (goto-char (point-max))
27645         (while (re-search-backward re nil t)
27646           (setq level (org-reduced-level (funcall outline-level)))
27647           (when (<= level n)
27648             (looking-at org-complex-heading-regexp)
27649             (setq head (org-match-string-no-properties 4)
27650                   m (org-imenu-new-marker))
27651             (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
27652             (if (>= level last-level)
27653                 (push (cons head m) (aref subs level))
27654               (push (cons head (aref subs (1+ level))) (aref subs level))
27655               (loop for i from (1+ level) to n do (aset subs i nil)))
27656             (setq last-level level)))))
27657     (aref subs 1)))
27659 (eval-after-load "imenu"
27660   '(progn
27661      (add-hook 'imenu-after-jump-hook
27662                (lambda () (org-show-context 'org-goto)))))
27664 ;; Speedbar support
27666 (defun org-speedbar-set-agenda-restriction ()
27667   "Restrict future agenda commands to the location at point in speedbar.
27668 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
27669   (interactive)
27670   (let (p m tp np dir txt w)
27671     (cond
27672      ((setq p (text-property-any (point-at-bol) (point-at-eol)
27673                                  'org-imenu t))
27674       (setq m (get-text-property p 'org-imenu-marker))
27675       (save-excursion
27676         (save-restriction
27677           (set-buffer (marker-buffer m))
27678           (goto-char m)
27679           (org-agenda-set-restriction-lock 'subtree))))
27680      ((setq p (text-property-any (point-at-bol) (point-at-eol)
27681                                  'speedbar-function 'speedbar-find-file))
27682       (setq tp (previous-single-property-change
27683                 (1+ p) 'speedbar-function)
27684             np (next-single-property-change
27685                 tp 'speedbar-function)
27686             dir (speedbar-line-directory)
27687             txt (buffer-substring-no-properties (or tp (point-min))
27688                                                 (or np (point-max))))
27689       (save-excursion
27690         (save-restriction
27691           (set-buffer (find-file-noselect
27692                        (let ((default-directory dir))
27693                          (expand-file-name txt))))
27694           (unless (org-mode-p)
27695             (error "Cannot restrict to non-Org-mode file"))
27696           (org-agenda-set-restriction-lock 'file))))
27697      (t (error "Don't know how to restrict Org-mode's agenda")))
27698     (org-move-overlay org-speedbar-restriction-lock-overlay
27699                       (point-at-bol) (point-at-eol))
27700     (setq current-prefix-arg nil)
27701     (org-agenda-maybe-redo)))
27703 (eval-after-load "speedbar"
27704   '(progn
27705      (speedbar-add-supported-extension ".org")
27706      (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
27707      (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
27708      (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
27709      (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
27710      (add-hook 'speedbar-visiting-tag-hook
27711                (lambda () (org-show-context 'org-goto)))))
27714 ;;; Fixes and Hacks
27716 ;; Make flyspell not check words in links, to not mess up our keymap
27717 (defun org-mode-flyspell-verify ()
27718   "Don't let flyspell put overlays at active buttons."
27719   (not (get-text-property (point) 'keymap)))
27721 ;; Make `bookmark-jump' show the jump location if it was hidden.
27722 (eval-after-load "bookmark"
27723   '(if (boundp 'bookmark-after-jump-hook)
27724        ;; We can use the hook
27725        (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
27726      ;; Hook not available, use advice
27727      (defadvice bookmark-jump (after org-make-visible activate)
27728        "Make the position visible."
27729        (org-bookmark-jump-unhide))))
27731 (defun org-bookmark-jump-unhide ()
27732   "Unhide the current position, to show the bookmark location."
27733   (and (org-mode-p)
27734        (or (org-invisible-p)
27735            (save-excursion (goto-char (max (point-min) (1- (point))))
27736                            (org-invisible-p)))
27737        (org-show-context 'bookmark-jump)))
27739 ;; Fix a bug in htmlize where there are text properties (face nil)
27740 (eval-after-load "htmlize"
27741   '(progn
27742      (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
27743        "Make sure there are no nil faces"
27744        (setq ad-return-value (delq nil ad-return-value)))))
27746 ;; Make session.el ignore our circular variable
27747 (eval-after-load "session"
27748   '(add-to-list 'session-globals-exclude 'org-mark-ring))
27750 ;;;; Experimental code
27752 (defun org-closed-in-range ()
27753   "Sparse tree of items closed in a certain time range.
27754 Still experimental, may disappear in the future."
27755   (interactive)
27756   ;; Get the time interval from the user.
27757   (let* ((time1 (time-to-seconds
27758                  (org-read-date nil 'to-time nil "Starting date: ")))
27759          (time2 (time-to-seconds
27760                  (org-read-date nil 'to-time nil "End date:")))
27761          ;; callback function
27762          (callback (lambda ()
27763                      (let ((time
27764                             (time-to-seconds
27765                              (apply 'encode-time
27766                                     (org-parse-time-string
27767                                      (match-string 1))))))
27768                        ;; check if time in interval
27769                        (and (>= time time1) (<= time time2))))))
27770     ;; make tree, check each match with the callback
27771     (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
27773 ;;;; Finish up
27775 (provide 'org)
27777 (run-hooks 'org-load-hook)
27779 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
27780 ;;; org.el ends here